SemaExpr.cpp 697 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TreeTransform.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ExprOpenMP.h"
  25. #include "clang/AST/RecursiveASTVisitor.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/Basic/FixedPoint.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/Overload.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaFixItUtils.h"
  44. #include "clang/Sema/SemaInternal.h"
  45. #include "clang/Sema/Template.h"
  46. #include "llvm/Support/ConvertUTF.h"
  47. using namespace clang;
  48. using namespace sema;
  49. /// Determine whether the use of this declaration is valid, without
  50. /// emitting diagnostics.
  51. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  52. // See if this is an auto-typed variable whose initializer we are parsing.
  53. if (ParsingInitForAutoVars.count(D))
  54. return false;
  55. // See if this is a deleted function.
  56. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  57. if (FD->isDeleted())
  58. return false;
  59. // If the function has a deduced return type, and we can't deduce it,
  60. // then we can't use it either.
  61. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  62. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  63. return false;
  64. // See if this is an aligned allocation/deallocation function that is
  65. // unavailable.
  66. if (TreatUnavailableAsInvalid &&
  67. isUnavailableAlignedAllocationFunction(*FD))
  68. return false;
  69. }
  70. // See if this function is unavailable.
  71. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  72. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  73. return false;
  74. return true;
  75. }
  76. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  77. // Warn if this is used but marked unused.
  78. if (const auto *A = D->getAttr<UnusedAttr>()) {
  79. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  80. // should diagnose them.
  81. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  82. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  83. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  84. if (DC && !DC->hasAttr<UnusedAttr>())
  85. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  86. }
  87. }
  88. }
  89. /// Emit a note explaining that this function is deleted.
  90. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  91. assert(Decl->isDeleted());
  92. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  93. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  94. // If the method was explicitly defaulted, point at that declaration.
  95. if (!Method->isImplicit())
  96. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  97. // Try to diagnose why this special member function was implicitly
  98. // deleted. This might fail, if that reason no longer applies.
  99. CXXSpecialMember CSM = getSpecialMember(Method);
  100. if (CSM != CXXInvalid)
  101. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  102. return;
  103. }
  104. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  105. if (Ctor && Ctor->isInheritingConstructor())
  106. return NoteDeletedInheritingConstructor(Ctor);
  107. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  108. << Decl << 1;
  109. }
  110. /// Determine whether a FunctionDecl was ever declared with an
  111. /// explicit storage class.
  112. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  113. for (auto I : D->redecls()) {
  114. if (I->getStorageClass() != SC_None)
  115. return true;
  116. }
  117. return false;
  118. }
  119. /// Check whether we're in an extern inline function and referring to a
  120. /// variable or function with internal linkage (C11 6.7.4p3).
  121. ///
  122. /// This is only a warning because we used to silently accept this code, but
  123. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  124. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  125. /// and so while there may still be user mistakes, most of the time we can't
  126. /// prove that there are errors.
  127. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  128. const NamedDecl *D,
  129. SourceLocation Loc) {
  130. // This is disabled under C++; there are too many ways for this to fire in
  131. // contexts where the warning is a false positive, or where it is technically
  132. // correct but benign.
  133. if (S.getLangOpts().CPlusPlus)
  134. return;
  135. // Check if this is an inlined function or method.
  136. FunctionDecl *Current = S.getCurFunctionDecl();
  137. if (!Current)
  138. return;
  139. if (!Current->isInlined())
  140. return;
  141. if (!Current->isExternallyVisible())
  142. return;
  143. // Check if the decl has internal linkage.
  144. if (D->getFormalLinkage() != InternalLinkage)
  145. return;
  146. // Downgrade from ExtWarn to Extension if
  147. // (1) the supposedly external inline function is in the main file,
  148. // and probably won't be included anywhere else.
  149. // (2) the thing we're referencing is a pure function.
  150. // (3) the thing we're referencing is another inline function.
  151. // This last can give us false negatives, but it's better than warning on
  152. // wrappers for simple C library functions.
  153. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  154. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  155. if (!DowngradeWarning && UsedFn)
  156. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  157. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  158. : diag::ext_internal_in_extern_inline)
  159. << /*IsVar=*/!UsedFn << D;
  160. S.MaybeSuggestAddingStaticToDecl(Current);
  161. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  162. << D;
  163. }
  164. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  165. const FunctionDecl *First = Cur->getFirstDecl();
  166. // Suggest "static" on the function, if possible.
  167. if (!hasAnyExplicitStorageClass(First)) {
  168. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  169. Diag(DeclBegin, diag::note_convert_inline_to_static)
  170. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  171. }
  172. }
  173. /// Determine whether the use of this declaration is valid, and
  174. /// emit any corresponding diagnostics.
  175. ///
  176. /// This routine diagnoses various problems with referencing
  177. /// declarations that can occur when using a declaration. For example,
  178. /// it might warn if a deprecated or unavailable declaration is being
  179. /// used, or produce an error (and return true) if a C++0x deleted
  180. /// function is being used.
  181. ///
  182. /// \returns true if there was an error (this declaration cannot be
  183. /// referenced), false otherwise.
  184. ///
  185. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  186. const ObjCInterfaceDecl *UnknownObjCClass,
  187. bool ObjCPropertyAccess,
  188. bool AvoidPartialAvailabilityChecks,
  189. ObjCInterfaceDecl *ClassReceiver) {
  190. SourceLocation Loc = Locs.front();
  191. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  192. // If there were any diagnostics suppressed by template argument deduction,
  193. // emit them now.
  194. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  195. if (Pos != SuppressedDiagnostics.end()) {
  196. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  197. Diag(Suppressed.first, Suppressed.second);
  198. // Clear out the list of suppressed diagnostics, so that we don't emit
  199. // them again for this specialization. However, we don't obsolete this
  200. // entry from the table, because we want to avoid ever emitting these
  201. // diagnostics again.
  202. Pos->second.clear();
  203. }
  204. // C++ [basic.start.main]p3:
  205. // The function 'main' shall not be used within a program.
  206. if (cast<FunctionDecl>(D)->isMain())
  207. Diag(Loc, diag::ext_main_used);
  208. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  209. }
  210. // See if this is an auto-typed variable whose initializer we are parsing.
  211. if (ParsingInitForAutoVars.count(D)) {
  212. if (isa<BindingDecl>(D)) {
  213. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  214. << D->getDeclName();
  215. } else {
  216. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  217. << D->getDeclName() << cast<VarDecl>(D)->getType();
  218. }
  219. return true;
  220. }
  221. // See if this is a deleted function.
  222. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  223. if (FD->isDeleted()) {
  224. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  225. if (Ctor && Ctor->isInheritingConstructor())
  226. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  227. << Ctor->getParent()
  228. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  229. else
  230. Diag(Loc, diag::err_deleted_function_use);
  231. NoteDeletedFunction(FD);
  232. return true;
  233. }
  234. // If the function has a deduced return type, and we can't deduce it,
  235. // then we can't use it either.
  236. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  237. DeduceReturnType(FD, Loc))
  238. return true;
  239. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  240. return true;
  241. }
  242. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  243. // Lambdas are only default-constructible or assignable in C++2a onwards.
  244. if (MD->getParent()->isLambda() &&
  245. ((isa<CXXConstructorDecl>(MD) &&
  246. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  247. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  248. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  249. << !isa<CXXConstructorDecl>(MD);
  250. }
  251. }
  252. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  253. const ObjCPropertyDecl * {
  254. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  255. return MD->findPropertyDecl();
  256. return nullptr;
  257. };
  258. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  259. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  260. return true;
  261. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  262. return true;
  263. }
  264. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  265. // Only the variables omp_in and omp_out are allowed in the combiner.
  266. // Only the variables omp_priv and omp_orig are allowed in the
  267. // initializer-clause.
  268. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  269. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  270. isa<VarDecl>(D)) {
  271. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  272. << getCurFunction()->HasOMPDeclareReductionCombiner;
  273. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  274. return true;
  275. }
  276. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  277. // List-items in map clauses on this construct may only refer to the declared
  278. // variable var and entities that could be referenced by a procedure defined
  279. // at the same location
  280. auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
  281. if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
  282. isa<VarDecl>(D)) {
  283. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  284. << DMD->getVarName().getAsString();
  285. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  286. return true;
  287. }
  288. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  289. AvoidPartialAvailabilityChecks, ClassReceiver);
  290. DiagnoseUnusedOfDecl(*this, D, Loc);
  291. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  292. return false;
  293. }
  294. /// DiagnoseSentinelCalls - This routine checks whether a call or
  295. /// message-send is to a declaration with the sentinel attribute, and
  296. /// if so, it checks that the requirements of the sentinel are
  297. /// satisfied.
  298. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  299. ArrayRef<Expr *> Args) {
  300. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  301. if (!attr)
  302. return;
  303. // The number of formal parameters of the declaration.
  304. unsigned numFormalParams;
  305. // The kind of declaration. This is also an index into a %select in
  306. // the diagnostic.
  307. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  308. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  309. numFormalParams = MD->param_size();
  310. calleeType = CT_Method;
  311. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  312. numFormalParams = FD->param_size();
  313. calleeType = CT_Function;
  314. } else if (isa<VarDecl>(D)) {
  315. QualType type = cast<ValueDecl>(D)->getType();
  316. const FunctionType *fn = nullptr;
  317. if (const PointerType *ptr = type->getAs<PointerType>()) {
  318. fn = ptr->getPointeeType()->getAs<FunctionType>();
  319. if (!fn) return;
  320. calleeType = CT_Function;
  321. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  322. fn = ptr->getPointeeType()->castAs<FunctionType>();
  323. calleeType = CT_Block;
  324. } else {
  325. return;
  326. }
  327. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  328. numFormalParams = proto->getNumParams();
  329. } else {
  330. numFormalParams = 0;
  331. }
  332. } else {
  333. return;
  334. }
  335. // "nullPos" is the number of formal parameters at the end which
  336. // effectively count as part of the variadic arguments. This is
  337. // useful if you would prefer to not have *any* formal parameters,
  338. // but the language forces you to have at least one.
  339. unsigned nullPos = attr->getNullPos();
  340. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  341. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  342. // The number of arguments which should follow the sentinel.
  343. unsigned numArgsAfterSentinel = attr->getSentinel();
  344. // If there aren't enough arguments for all the formal parameters,
  345. // the sentinel, and the args after the sentinel, complain.
  346. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  347. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  348. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  349. return;
  350. }
  351. // Otherwise, find the sentinel expression.
  352. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  353. if (!sentinelExpr) return;
  354. if (sentinelExpr->isValueDependent()) return;
  355. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  356. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  357. // or 'NULL' if those are actually defined in the context. Only use
  358. // 'nil' for ObjC methods, where it's much more likely that the
  359. // variadic arguments form a list of object pointers.
  360. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  361. std::string NullValue;
  362. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  363. NullValue = "nil";
  364. else if (getLangOpts().CPlusPlus11)
  365. NullValue = "nullptr";
  366. else if (PP.isMacroDefined("NULL"))
  367. NullValue = "NULL";
  368. else
  369. NullValue = "(void*) 0";
  370. if (MissingNilLoc.isInvalid())
  371. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  372. else
  373. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  374. << int(calleeType)
  375. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  376. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  377. }
  378. SourceRange Sema::getExprRange(Expr *E) const {
  379. return E ? E->getSourceRange() : SourceRange();
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // Standard Promotions and Conversions
  383. //===----------------------------------------------------------------------===//
  384. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  385. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  386. // Handle any placeholder expressions which made it here.
  387. if (E->getType()->isPlaceholderType()) {
  388. ExprResult result = CheckPlaceholderExpr(E);
  389. if (result.isInvalid()) return ExprError();
  390. E = result.get();
  391. }
  392. QualType Ty = E->getType();
  393. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  394. if (Ty->isFunctionType()) {
  395. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  396. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  397. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  398. return ExprError();
  399. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  400. CK_FunctionToPointerDecay).get();
  401. } else if (Ty->isArrayType()) {
  402. // In C90 mode, arrays only promote to pointers if the array expression is
  403. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  404. // type 'array of type' is converted to an expression that has type 'pointer
  405. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  406. // that has type 'array of type' ...". The relevant change is "an lvalue"
  407. // (C90) to "an expression" (C99).
  408. //
  409. // C++ 4.2p1:
  410. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  411. // T" can be converted to an rvalue of type "pointer to T".
  412. //
  413. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  414. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  415. CK_ArrayToPointerDecay).get();
  416. }
  417. return E;
  418. }
  419. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  420. // Check to see if we are dereferencing a null pointer. If so,
  421. // and if not volatile-qualified, this is undefined behavior that the
  422. // optimizer will delete, so warn about it. People sometimes try to use this
  423. // to get a deterministic trap and are surprised by clang's behavior. This
  424. // only handles the pattern "*null", which is a very syntactic check.
  425. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  426. if (UO->getOpcode() == UO_Deref &&
  427. UO->getSubExpr()->IgnoreParenCasts()->
  428. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  429. !UO->getType().isVolatileQualified()) {
  430. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  431. S.PDiag(diag::warn_indirection_through_null)
  432. << UO->getSubExpr()->getSourceRange());
  433. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  434. S.PDiag(diag::note_indirection_through_null));
  435. }
  436. }
  437. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  438. SourceLocation AssignLoc,
  439. const Expr* RHS) {
  440. const ObjCIvarDecl *IV = OIRE->getDecl();
  441. if (!IV)
  442. return;
  443. DeclarationName MemberName = IV->getDeclName();
  444. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  445. if (!Member || !Member->isStr("isa"))
  446. return;
  447. const Expr *Base = OIRE->getBase();
  448. QualType BaseType = Base->getType();
  449. if (OIRE->isArrow())
  450. BaseType = BaseType->getPointeeType();
  451. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  452. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  453. ObjCInterfaceDecl *ClassDeclared = nullptr;
  454. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  455. if (!ClassDeclared->getSuperClass()
  456. && (*ClassDeclared->ivar_begin()) == IV) {
  457. if (RHS) {
  458. NamedDecl *ObjectSetClass =
  459. S.LookupSingleName(S.TUScope,
  460. &S.Context.Idents.get("object_setClass"),
  461. SourceLocation(), S.LookupOrdinaryName);
  462. if (ObjectSetClass) {
  463. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  464. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  465. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  466. "object_setClass(")
  467. << FixItHint::CreateReplacement(
  468. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  469. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  470. }
  471. else
  472. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  473. } else {
  474. NamedDecl *ObjectGetClass =
  475. S.LookupSingleName(S.TUScope,
  476. &S.Context.Idents.get("object_getClass"),
  477. SourceLocation(), S.LookupOrdinaryName);
  478. if (ObjectGetClass)
  479. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  480. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  481. "object_getClass(")
  482. << FixItHint::CreateReplacement(
  483. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  484. else
  485. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  486. }
  487. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  488. }
  489. }
  490. }
  491. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  492. // Handle any placeholder expressions which made it here.
  493. if (E->getType()->isPlaceholderType()) {
  494. ExprResult result = CheckPlaceholderExpr(E);
  495. if (result.isInvalid()) return ExprError();
  496. E = result.get();
  497. }
  498. // C++ [conv.lval]p1:
  499. // A glvalue of a non-function, non-array type T can be
  500. // converted to a prvalue.
  501. if (!E->isGLValue()) return E;
  502. QualType T = E->getType();
  503. assert(!T.isNull() && "r-value conversion on typeless expression?");
  504. // We don't want to throw lvalue-to-rvalue casts on top of
  505. // expressions of certain types in C++.
  506. if (getLangOpts().CPlusPlus &&
  507. (E->getType() == Context.OverloadTy ||
  508. T->isDependentType() ||
  509. T->isRecordType()))
  510. return E;
  511. // The C standard is actually really unclear on this point, and
  512. // DR106 tells us what the result should be but not why. It's
  513. // generally best to say that void types just doesn't undergo
  514. // lvalue-to-rvalue at all. Note that expressions of unqualified
  515. // 'void' type are never l-values, but qualified void can be.
  516. if (T->isVoidType())
  517. return E;
  518. // OpenCL usually rejects direct accesses to values of 'half' type.
  519. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  520. T->isHalfType()) {
  521. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  522. << 0 << T;
  523. return ExprError();
  524. }
  525. CheckForNullPointerDereference(*this, E);
  526. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  527. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  528. &Context.Idents.get("object_getClass"),
  529. SourceLocation(), LookupOrdinaryName);
  530. if (ObjectGetClass)
  531. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  532. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  533. << FixItHint::CreateReplacement(
  534. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  535. else
  536. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  537. }
  538. else if (const ObjCIvarRefExpr *OIRE =
  539. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  540. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  541. // C++ [conv.lval]p1:
  542. // [...] If T is a non-class type, the type of the prvalue is the
  543. // cv-unqualified version of T. Otherwise, the type of the
  544. // rvalue is T.
  545. //
  546. // C99 6.3.2.1p2:
  547. // If the lvalue has qualified type, the value has the unqualified
  548. // version of the type of the lvalue; otherwise, the value has the
  549. // type of the lvalue.
  550. if (T.hasQualifiers())
  551. T = T.getUnqualifiedType();
  552. // Under the MS ABI, lock down the inheritance model now.
  553. if (T->isMemberPointerType() &&
  554. Context.getTargetInfo().getCXXABI().isMicrosoft())
  555. (void)isCompleteType(E->getExprLoc(), T);
  556. ExprResult Res = CheckLValueToRValueConversionOperand(E);
  557. if (Res.isInvalid())
  558. return Res;
  559. E = Res.get();
  560. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  561. // balance that.
  562. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  563. Cleanup.setExprNeedsCleanups(true);
  564. // C++ [conv.lval]p3:
  565. // If T is cv std::nullptr_t, the result is a null pointer constant.
  566. CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
  567. Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
  568. // C11 6.3.2.1p2:
  569. // ... if the lvalue has atomic type, the value has the non-atomic version
  570. // of the type of the lvalue ...
  571. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  572. T = Atomic->getValueType().getUnqualifiedType();
  573. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  574. nullptr, VK_RValue);
  575. }
  576. return Res;
  577. }
  578. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  579. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  580. if (Res.isInvalid())
  581. return ExprError();
  582. Res = DefaultLvalueConversion(Res.get());
  583. if (Res.isInvalid())
  584. return ExprError();
  585. return Res;
  586. }
  587. /// CallExprUnaryConversions - a special case of an unary conversion
  588. /// performed on a function designator of a call expression.
  589. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  590. QualType Ty = E->getType();
  591. ExprResult Res = E;
  592. // Only do implicit cast for a function type, but not for a pointer
  593. // to function type.
  594. if (Ty->isFunctionType()) {
  595. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  596. CK_FunctionToPointerDecay).get();
  597. if (Res.isInvalid())
  598. return ExprError();
  599. }
  600. Res = DefaultLvalueConversion(Res.get());
  601. if (Res.isInvalid())
  602. return ExprError();
  603. return Res.get();
  604. }
  605. /// UsualUnaryConversions - Performs various conversions that are common to most
  606. /// operators (C99 6.3). The conversions of array and function types are
  607. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  608. /// apply if the array is an argument to the sizeof or address (&) operators.
  609. /// In these instances, this routine should *not* be called.
  610. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  611. // First, convert to an r-value.
  612. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  613. if (Res.isInvalid())
  614. return ExprError();
  615. E = Res.get();
  616. QualType Ty = E->getType();
  617. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  618. // Half FP have to be promoted to float unless it is natively supported
  619. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  620. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  621. // Try to perform integral promotions if the object has a theoretically
  622. // promotable type.
  623. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  624. // C99 6.3.1.1p2:
  625. //
  626. // The following may be used in an expression wherever an int or
  627. // unsigned int may be used:
  628. // - an object or expression with an integer type whose integer
  629. // conversion rank is less than or equal to the rank of int
  630. // and unsigned int.
  631. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  632. //
  633. // If an int can represent all values of the original type, the
  634. // value is converted to an int; otherwise, it is converted to an
  635. // unsigned int. These are called the integer promotions. All
  636. // other types are unchanged by the integer promotions.
  637. QualType PTy = Context.isPromotableBitField(E);
  638. if (!PTy.isNull()) {
  639. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  640. return E;
  641. }
  642. if (Ty->isPromotableIntegerType()) {
  643. QualType PT = Context.getPromotedIntegerType(Ty);
  644. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  645. return E;
  646. }
  647. }
  648. return E;
  649. }
  650. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  651. /// do not have a prototype. Arguments that have type float or __fp16
  652. /// are promoted to double. All other argument types are converted by
  653. /// UsualUnaryConversions().
  654. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  655. QualType Ty = E->getType();
  656. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  657. ExprResult Res = UsualUnaryConversions(E);
  658. if (Res.isInvalid())
  659. return ExprError();
  660. E = Res.get();
  661. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  662. // promote to double.
  663. // Note that default argument promotion applies only to float (and
  664. // half/fp16); it does not apply to _Float16.
  665. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  666. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  667. BTy->getKind() == BuiltinType::Float)) {
  668. if (getLangOpts().OpenCL &&
  669. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  670. if (BTy->getKind() == BuiltinType::Half) {
  671. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  672. }
  673. } else {
  674. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  675. }
  676. }
  677. // C++ performs lvalue-to-rvalue conversion as a default argument
  678. // promotion, even on class types, but note:
  679. // C++11 [conv.lval]p2:
  680. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  681. // operand or a subexpression thereof the value contained in the
  682. // referenced object is not accessed. Otherwise, if the glvalue
  683. // has a class type, the conversion copy-initializes a temporary
  684. // of type T from the glvalue and the result of the conversion
  685. // is a prvalue for the temporary.
  686. // FIXME: add some way to gate this entire thing for correctness in
  687. // potentially potentially evaluated contexts.
  688. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  689. ExprResult Temp = PerformCopyInitialization(
  690. InitializedEntity::InitializeTemporary(E->getType()),
  691. E->getExprLoc(), E);
  692. if (Temp.isInvalid())
  693. return ExprError();
  694. E = Temp.get();
  695. }
  696. return E;
  697. }
  698. /// Determine the degree of POD-ness for an expression.
  699. /// Incomplete types are considered POD, since this check can be performed
  700. /// when we're in an unevaluated context.
  701. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  702. if (Ty->isIncompleteType()) {
  703. // C++11 [expr.call]p7:
  704. // After these conversions, if the argument does not have arithmetic,
  705. // enumeration, pointer, pointer to member, or class type, the program
  706. // is ill-formed.
  707. //
  708. // Since we've already performed array-to-pointer and function-to-pointer
  709. // decay, the only such type in C++ is cv void. This also handles
  710. // initializer lists as variadic arguments.
  711. if (Ty->isVoidType())
  712. return VAK_Invalid;
  713. if (Ty->isObjCObjectType())
  714. return VAK_Invalid;
  715. return VAK_Valid;
  716. }
  717. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  718. return VAK_Invalid;
  719. if (Ty.isCXX98PODType(Context))
  720. return VAK_Valid;
  721. // C++11 [expr.call]p7:
  722. // Passing a potentially-evaluated argument of class type (Clause 9)
  723. // having a non-trivial copy constructor, a non-trivial move constructor,
  724. // or a non-trivial destructor, with no corresponding parameter,
  725. // is conditionally-supported with implementation-defined semantics.
  726. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  727. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  728. if (!Record->hasNonTrivialCopyConstructor() &&
  729. !Record->hasNonTrivialMoveConstructor() &&
  730. !Record->hasNonTrivialDestructor())
  731. return VAK_ValidInCXX11;
  732. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  733. return VAK_Valid;
  734. if (Ty->isObjCObjectType())
  735. return VAK_Invalid;
  736. if (getLangOpts().MSVCCompat)
  737. return VAK_MSVCUndefined;
  738. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  739. // permitted to reject them. We should consider doing so.
  740. return VAK_Undefined;
  741. }
  742. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  743. // Don't allow one to pass an Objective-C interface to a vararg.
  744. const QualType &Ty = E->getType();
  745. VarArgKind VAK = isValidVarArgType(Ty);
  746. // Complain about passing non-POD types through varargs.
  747. switch (VAK) {
  748. case VAK_ValidInCXX11:
  749. DiagRuntimeBehavior(
  750. E->getBeginLoc(), nullptr,
  751. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  752. LLVM_FALLTHROUGH;
  753. case VAK_Valid:
  754. if (Ty->isRecordType()) {
  755. // This is unlikely to be what the user intended. If the class has a
  756. // 'c_str' member function, the user probably meant to call that.
  757. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  758. PDiag(diag::warn_pass_class_arg_to_vararg)
  759. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  760. }
  761. break;
  762. case VAK_Undefined:
  763. case VAK_MSVCUndefined:
  764. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  765. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  766. << getLangOpts().CPlusPlus11 << Ty << CT);
  767. break;
  768. case VAK_Invalid:
  769. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  770. Diag(E->getBeginLoc(),
  771. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  772. << Ty << CT;
  773. else if (Ty->isObjCObjectType())
  774. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  775. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  776. << Ty << CT);
  777. else
  778. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  779. << isa<InitListExpr>(E) << Ty << CT;
  780. break;
  781. }
  782. }
  783. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  784. /// will create a trap if the resulting type is not a POD type.
  785. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  786. FunctionDecl *FDecl) {
  787. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  788. // Strip the unbridged-cast placeholder expression off, if applicable.
  789. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  790. (CT == VariadicMethod ||
  791. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  792. E = stripARCUnbridgedCast(E);
  793. // Otherwise, do normal placeholder checking.
  794. } else {
  795. ExprResult ExprRes = CheckPlaceholderExpr(E);
  796. if (ExprRes.isInvalid())
  797. return ExprError();
  798. E = ExprRes.get();
  799. }
  800. }
  801. ExprResult ExprRes = DefaultArgumentPromotion(E);
  802. if (ExprRes.isInvalid())
  803. return ExprError();
  804. E = ExprRes.get();
  805. // Diagnostics regarding non-POD argument types are
  806. // emitted along with format string checking in Sema::CheckFunctionCall().
  807. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  808. // Turn this into a trap.
  809. CXXScopeSpec SS;
  810. SourceLocation TemplateKWLoc;
  811. UnqualifiedId Name;
  812. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  813. E->getBeginLoc());
  814. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  815. /*HasTrailingLParen=*/true,
  816. /*IsAddressOfOperand=*/false);
  817. if (TrapFn.isInvalid())
  818. return ExprError();
  819. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  820. None, E->getEndLoc());
  821. if (Call.isInvalid())
  822. return ExprError();
  823. ExprResult Comma =
  824. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  825. if (Comma.isInvalid())
  826. return ExprError();
  827. return Comma.get();
  828. }
  829. if (!getLangOpts().CPlusPlus &&
  830. RequireCompleteType(E->getExprLoc(), E->getType(),
  831. diag::err_call_incomplete_argument))
  832. return ExprError();
  833. return E;
  834. }
  835. /// Converts an integer to complex float type. Helper function of
  836. /// UsualArithmeticConversions()
  837. ///
  838. /// \return false if the integer expression is an integer type and is
  839. /// successfully converted to the complex type.
  840. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  841. ExprResult &ComplexExpr,
  842. QualType IntTy,
  843. QualType ComplexTy,
  844. bool SkipCast) {
  845. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  846. if (SkipCast) return false;
  847. if (IntTy->isIntegerType()) {
  848. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  849. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  850. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  851. CK_FloatingRealToComplex);
  852. } else {
  853. assert(IntTy->isComplexIntegerType());
  854. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  855. CK_IntegralComplexToFloatingComplex);
  856. }
  857. return false;
  858. }
  859. /// Handle arithmetic conversion with complex types. Helper function of
  860. /// UsualArithmeticConversions()
  861. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  862. ExprResult &RHS, QualType LHSType,
  863. QualType RHSType,
  864. bool IsCompAssign) {
  865. // if we have an integer operand, the result is the complex type.
  866. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  867. /*skipCast*/false))
  868. return LHSType;
  869. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  870. /*skipCast*/IsCompAssign))
  871. return RHSType;
  872. // This handles complex/complex, complex/float, or float/complex.
  873. // When both operands are complex, the shorter operand is converted to the
  874. // type of the longer, and that is the type of the result. This corresponds
  875. // to what is done when combining two real floating-point operands.
  876. // The fun begins when size promotion occur across type domains.
  877. // From H&S 6.3.4: When one operand is complex and the other is a real
  878. // floating-point type, the less precise type is converted, within it's
  879. // real or complex domain, to the precision of the other type. For example,
  880. // when combining a "long double" with a "double _Complex", the
  881. // "double _Complex" is promoted to "long double _Complex".
  882. // Compute the rank of the two types, regardless of whether they are complex.
  883. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  884. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  885. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  886. QualType LHSElementType =
  887. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  888. QualType RHSElementType =
  889. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  890. QualType ResultType = S.Context.getComplexType(LHSElementType);
  891. if (Order < 0) {
  892. // Promote the precision of the LHS if not an assignment.
  893. ResultType = S.Context.getComplexType(RHSElementType);
  894. if (!IsCompAssign) {
  895. if (LHSComplexType)
  896. LHS =
  897. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  898. else
  899. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  900. }
  901. } else if (Order > 0) {
  902. // Promote the precision of the RHS.
  903. if (RHSComplexType)
  904. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  905. else
  906. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  907. }
  908. return ResultType;
  909. }
  910. /// Handle arithmetic conversion from integer to float. Helper function
  911. /// of UsualArithmeticConversions()
  912. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  913. ExprResult &IntExpr,
  914. QualType FloatTy, QualType IntTy,
  915. bool ConvertFloat, bool ConvertInt) {
  916. if (IntTy->isIntegerType()) {
  917. if (ConvertInt)
  918. // Convert intExpr to the lhs floating point type.
  919. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  920. CK_IntegralToFloating);
  921. return FloatTy;
  922. }
  923. // Convert both sides to the appropriate complex float.
  924. assert(IntTy->isComplexIntegerType());
  925. QualType result = S.Context.getComplexType(FloatTy);
  926. // _Complex int -> _Complex float
  927. if (ConvertInt)
  928. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  929. CK_IntegralComplexToFloatingComplex);
  930. // float -> _Complex float
  931. if (ConvertFloat)
  932. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  933. CK_FloatingRealToComplex);
  934. return result;
  935. }
  936. /// Handle arithmethic conversion with floating point types. Helper
  937. /// function of UsualArithmeticConversions()
  938. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  939. ExprResult &RHS, QualType LHSType,
  940. QualType RHSType, bool IsCompAssign) {
  941. bool LHSFloat = LHSType->isRealFloatingType();
  942. bool RHSFloat = RHSType->isRealFloatingType();
  943. // If we have two real floating types, convert the smaller operand
  944. // to the bigger result.
  945. if (LHSFloat && RHSFloat) {
  946. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  947. if (order > 0) {
  948. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  949. return LHSType;
  950. }
  951. assert(order < 0 && "illegal float comparison");
  952. if (!IsCompAssign)
  953. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  954. return RHSType;
  955. }
  956. if (LHSFloat) {
  957. // Half FP has to be promoted to float unless it is natively supported
  958. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  959. LHSType = S.Context.FloatTy;
  960. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  961. /*ConvertFloat=*/!IsCompAssign,
  962. /*ConvertInt=*/ true);
  963. }
  964. assert(RHSFloat);
  965. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  966. /*convertInt=*/ true,
  967. /*convertFloat=*/!IsCompAssign);
  968. }
  969. /// Diagnose attempts to convert between __float128 and long double if
  970. /// there is no support for such conversion. Helper function of
  971. /// UsualArithmeticConversions().
  972. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  973. QualType RHSType) {
  974. /* No issue converting if at least one of the types is not a floating point
  975. type or the two types have the same rank.
  976. */
  977. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  978. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  979. return false;
  980. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  981. "The remaining types must be floating point types.");
  982. auto *LHSComplex = LHSType->getAs<ComplexType>();
  983. auto *RHSComplex = RHSType->getAs<ComplexType>();
  984. QualType LHSElemType = LHSComplex ?
  985. LHSComplex->getElementType() : LHSType;
  986. QualType RHSElemType = RHSComplex ?
  987. RHSComplex->getElementType() : RHSType;
  988. // No issue if the two types have the same representation
  989. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  990. &S.Context.getFloatTypeSemantics(RHSElemType))
  991. return false;
  992. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  993. RHSElemType == S.Context.LongDoubleTy);
  994. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  995. RHSElemType == S.Context.Float128Ty);
  996. // We've handled the situation where __float128 and long double have the same
  997. // representation. We allow all conversions for all possible long double types
  998. // except PPC's double double.
  999. return Float128AndLongDouble &&
  1000. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  1001. &llvm::APFloat::PPCDoubleDouble());
  1002. }
  1003. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1004. namespace {
  1005. /// These helper callbacks are placed in an anonymous namespace to
  1006. /// permit their use as function template parameters.
  1007. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1008. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1009. }
  1010. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1011. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1012. CK_IntegralComplexCast);
  1013. }
  1014. }
  1015. /// Handle integer arithmetic conversions. Helper function of
  1016. /// UsualArithmeticConversions()
  1017. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1018. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1019. ExprResult &RHS, QualType LHSType,
  1020. QualType RHSType, bool IsCompAssign) {
  1021. // The rules for this case are in C99 6.3.1.8
  1022. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1023. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1024. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1025. if (LHSSigned == RHSSigned) {
  1026. // Same signedness; use the higher-ranked type
  1027. if (order >= 0) {
  1028. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1029. return LHSType;
  1030. } else if (!IsCompAssign)
  1031. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1032. return RHSType;
  1033. } else if (order != (LHSSigned ? 1 : -1)) {
  1034. // The unsigned type has greater than or equal rank to the
  1035. // signed type, so use the unsigned type
  1036. if (RHSSigned) {
  1037. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1038. return LHSType;
  1039. } else if (!IsCompAssign)
  1040. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1041. return RHSType;
  1042. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1043. // The two types are different widths; if we are here, that
  1044. // means the signed type is larger than the unsigned type, so
  1045. // use the signed type.
  1046. if (LHSSigned) {
  1047. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1048. return LHSType;
  1049. } else if (!IsCompAssign)
  1050. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1051. return RHSType;
  1052. } else {
  1053. // The signed type is higher-ranked than the unsigned type,
  1054. // but isn't actually any bigger (like unsigned int and long
  1055. // on most 32-bit systems). Use the unsigned type corresponding
  1056. // to the signed type.
  1057. QualType result =
  1058. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1059. RHS = (*doRHSCast)(S, RHS.get(), result);
  1060. if (!IsCompAssign)
  1061. LHS = (*doLHSCast)(S, LHS.get(), result);
  1062. return result;
  1063. }
  1064. }
  1065. /// Handle conversions with GCC complex int extension. Helper function
  1066. /// of UsualArithmeticConversions()
  1067. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1068. ExprResult &RHS, QualType LHSType,
  1069. QualType RHSType,
  1070. bool IsCompAssign) {
  1071. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1072. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1073. if (LHSComplexInt && RHSComplexInt) {
  1074. QualType LHSEltType = LHSComplexInt->getElementType();
  1075. QualType RHSEltType = RHSComplexInt->getElementType();
  1076. QualType ScalarType =
  1077. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1078. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1079. return S.Context.getComplexType(ScalarType);
  1080. }
  1081. if (LHSComplexInt) {
  1082. QualType LHSEltType = LHSComplexInt->getElementType();
  1083. QualType ScalarType =
  1084. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1085. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1086. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1087. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1088. CK_IntegralRealToComplex);
  1089. return ComplexType;
  1090. }
  1091. assert(RHSComplexInt);
  1092. QualType RHSEltType = RHSComplexInt->getElementType();
  1093. QualType ScalarType =
  1094. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1095. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1096. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1097. if (!IsCompAssign)
  1098. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1099. CK_IntegralRealToComplex);
  1100. return ComplexType;
  1101. }
  1102. /// Return the rank of a given fixed point or integer type. The value itself
  1103. /// doesn't matter, but the values must be increasing with proper increasing
  1104. /// rank as described in N1169 4.1.1.
  1105. static unsigned GetFixedPointRank(QualType Ty) {
  1106. const auto *BTy = Ty->getAs<BuiltinType>();
  1107. assert(BTy && "Expected a builtin type.");
  1108. switch (BTy->getKind()) {
  1109. case BuiltinType::ShortFract:
  1110. case BuiltinType::UShortFract:
  1111. case BuiltinType::SatShortFract:
  1112. case BuiltinType::SatUShortFract:
  1113. return 1;
  1114. case BuiltinType::Fract:
  1115. case BuiltinType::UFract:
  1116. case BuiltinType::SatFract:
  1117. case BuiltinType::SatUFract:
  1118. return 2;
  1119. case BuiltinType::LongFract:
  1120. case BuiltinType::ULongFract:
  1121. case BuiltinType::SatLongFract:
  1122. case BuiltinType::SatULongFract:
  1123. return 3;
  1124. case BuiltinType::ShortAccum:
  1125. case BuiltinType::UShortAccum:
  1126. case BuiltinType::SatShortAccum:
  1127. case BuiltinType::SatUShortAccum:
  1128. return 4;
  1129. case BuiltinType::Accum:
  1130. case BuiltinType::UAccum:
  1131. case BuiltinType::SatAccum:
  1132. case BuiltinType::SatUAccum:
  1133. return 5;
  1134. case BuiltinType::LongAccum:
  1135. case BuiltinType::ULongAccum:
  1136. case BuiltinType::SatLongAccum:
  1137. case BuiltinType::SatULongAccum:
  1138. return 6;
  1139. default:
  1140. if (BTy->isInteger())
  1141. return 0;
  1142. llvm_unreachable("Unexpected fixed point or integer type");
  1143. }
  1144. }
  1145. /// handleFixedPointConversion - Fixed point operations between fixed
  1146. /// point types and integers or other fixed point types do not fall under
  1147. /// usual arithmetic conversion since these conversions could result in loss
  1148. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1149. /// the full precision of their result type (N1169 4.1.6.2.1).
  1150. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1151. QualType RHSTy) {
  1152. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1153. "Expected at least one of the operands to be a fixed point type");
  1154. assert((LHSTy->isFixedPointOrIntegerType() ||
  1155. RHSTy->isFixedPointOrIntegerType()) &&
  1156. "Special fixed point arithmetic operation conversions are only "
  1157. "applied to ints or other fixed point types");
  1158. // If one operand has signed fixed-point type and the other operand has
  1159. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1160. // converted to its corresponding signed fixed-point type and the resulting
  1161. // type is the type of the converted operand.
  1162. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1163. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1164. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1165. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1166. // The result type is the type with the highest rank, whereby a fixed-point
  1167. // conversion rank is always greater than an integer conversion rank; if the
  1168. // type of either of the operands is a saturating fixedpoint type, the result
  1169. // type shall be the saturating fixed-point type corresponding to the type
  1170. // with the highest rank; the resulting value is converted (taking into
  1171. // account rounding and overflow) to the precision of the resulting type.
  1172. // Same ranks between signed and unsigned types are resolved earlier, so both
  1173. // types are either signed or both unsigned at this point.
  1174. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1175. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1176. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1177. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1178. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1179. return ResultTy;
  1180. }
  1181. /// UsualArithmeticConversions - Performs various conversions that are common to
  1182. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1183. /// routine returns the first non-arithmetic type found. The client is
  1184. /// responsible for emitting appropriate error diagnostics.
  1185. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1186. bool IsCompAssign) {
  1187. if (!IsCompAssign) {
  1188. LHS = UsualUnaryConversions(LHS.get());
  1189. if (LHS.isInvalid())
  1190. return QualType();
  1191. }
  1192. RHS = UsualUnaryConversions(RHS.get());
  1193. if (RHS.isInvalid())
  1194. return QualType();
  1195. // For conversion purposes, we ignore any qualifiers.
  1196. // For example, "const float" and "float" are equivalent.
  1197. QualType LHSType =
  1198. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1199. QualType RHSType =
  1200. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1201. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1202. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1203. LHSType = AtomicLHS->getValueType();
  1204. // If both types are identical, no conversion is needed.
  1205. if (LHSType == RHSType)
  1206. return LHSType;
  1207. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1208. // The caller can deal with this (e.g. pointer + int).
  1209. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1210. return QualType();
  1211. // Apply unary and bitfield promotions to the LHS's type.
  1212. QualType LHSUnpromotedType = LHSType;
  1213. if (LHSType->isPromotableIntegerType())
  1214. LHSType = Context.getPromotedIntegerType(LHSType);
  1215. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1216. if (!LHSBitfieldPromoteTy.isNull())
  1217. LHSType = LHSBitfieldPromoteTy;
  1218. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1219. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1220. // If both types are identical, no conversion is needed.
  1221. if (LHSType == RHSType)
  1222. return LHSType;
  1223. // At this point, we have two different arithmetic types.
  1224. // Diagnose attempts to convert between __float128 and long double where
  1225. // such conversions currently can't be handled.
  1226. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1227. return QualType();
  1228. // Handle complex types first (C99 6.3.1.8p1).
  1229. if (LHSType->isComplexType() || RHSType->isComplexType())
  1230. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1231. IsCompAssign);
  1232. // Now handle "real" floating types (i.e. float, double, long double).
  1233. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1234. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1235. IsCompAssign);
  1236. // Handle GCC complex int extension.
  1237. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1238. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1239. IsCompAssign);
  1240. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1241. return handleFixedPointConversion(*this, LHSType, RHSType);
  1242. // Finally, we have two differing integer types.
  1243. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1244. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1245. }
  1246. //===----------------------------------------------------------------------===//
  1247. // Semantic Analysis for various Expression Types
  1248. //===----------------------------------------------------------------------===//
  1249. ExprResult
  1250. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1251. SourceLocation DefaultLoc,
  1252. SourceLocation RParenLoc,
  1253. Expr *ControllingExpr,
  1254. ArrayRef<ParsedType> ArgTypes,
  1255. ArrayRef<Expr *> ArgExprs) {
  1256. unsigned NumAssocs = ArgTypes.size();
  1257. assert(NumAssocs == ArgExprs.size());
  1258. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1259. for (unsigned i = 0; i < NumAssocs; ++i) {
  1260. if (ArgTypes[i])
  1261. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1262. else
  1263. Types[i] = nullptr;
  1264. }
  1265. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1266. ControllingExpr,
  1267. llvm::makeArrayRef(Types, NumAssocs),
  1268. ArgExprs);
  1269. delete [] Types;
  1270. return ER;
  1271. }
  1272. ExprResult
  1273. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1274. SourceLocation DefaultLoc,
  1275. SourceLocation RParenLoc,
  1276. Expr *ControllingExpr,
  1277. ArrayRef<TypeSourceInfo *> Types,
  1278. ArrayRef<Expr *> Exprs) {
  1279. unsigned NumAssocs = Types.size();
  1280. assert(NumAssocs == Exprs.size());
  1281. // Decay and strip qualifiers for the controlling expression type, and handle
  1282. // placeholder type replacement. See committee discussion from WG14 DR423.
  1283. {
  1284. EnterExpressionEvaluationContext Unevaluated(
  1285. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1286. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1287. if (R.isInvalid())
  1288. return ExprError();
  1289. ControllingExpr = R.get();
  1290. }
  1291. // The controlling expression is an unevaluated operand, so side effects are
  1292. // likely unintended.
  1293. if (!inTemplateInstantiation() &&
  1294. ControllingExpr->HasSideEffects(Context, false))
  1295. Diag(ControllingExpr->getExprLoc(),
  1296. diag::warn_side_effects_unevaluated_context);
  1297. bool TypeErrorFound = false,
  1298. IsResultDependent = ControllingExpr->isTypeDependent(),
  1299. ContainsUnexpandedParameterPack
  1300. = ControllingExpr->containsUnexpandedParameterPack();
  1301. for (unsigned i = 0; i < NumAssocs; ++i) {
  1302. if (Exprs[i]->containsUnexpandedParameterPack())
  1303. ContainsUnexpandedParameterPack = true;
  1304. if (Types[i]) {
  1305. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1306. ContainsUnexpandedParameterPack = true;
  1307. if (Types[i]->getType()->isDependentType()) {
  1308. IsResultDependent = true;
  1309. } else {
  1310. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1311. // complete object type other than a variably modified type."
  1312. unsigned D = 0;
  1313. if (Types[i]->getType()->isIncompleteType())
  1314. D = diag::err_assoc_type_incomplete;
  1315. else if (!Types[i]->getType()->isObjectType())
  1316. D = diag::err_assoc_type_nonobject;
  1317. else if (Types[i]->getType()->isVariablyModifiedType())
  1318. D = diag::err_assoc_type_variably_modified;
  1319. if (D != 0) {
  1320. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1321. << Types[i]->getTypeLoc().getSourceRange()
  1322. << Types[i]->getType();
  1323. TypeErrorFound = true;
  1324. }
  1325. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1326. // selection shall specify compatible types."
  1327. for (unsigned j = i+1; j < NumAssocs; ++j)
  1328. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1329. Context.typesAreCompatible(Types[i]->getType(),
  1330. Types[j]->getType())) {
  1331. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1332. diag::err_assoc_compatible_types)
  1333. << Types[j]->getTypeLoc().getSourceRange()
  1334. << Types[j]->getType()
  1335. << Types[i]->getType();
  1336. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1337. diag::note_compat_assoc)
  1338. << Types[i]->getTypeLoc().getSourceRange()
  1339. << Types[i]->getType();
  1340. TypeErrorFound = true;
  1341. }
  1342. }
  1343. }
  1344. }
  1345. if (TypeErrorFound)
  1346. return ExprError();
  1347. // If we determined that the generic selection is result-dependent, don't
  1348. // try to compute the result expression.
  1349. if (IsResultDependent)
  1350. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1351. Exprs, DefaultLoc, RParenLoc,
  1352. ContainsUnexpandedParameterPack);
  1353. SmallVector<unsigned, 1> CompatIndices;
  1354. unsigned DefaultIndex = -1U;
  1355. for (unsigned i = 0; i < NumAssocs; ++i) {
  1356. if (!Types[i])
  1357. DefaultIndex = i;
  1358. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1359. Types[i]->getType()))
  1360. CompatIndices.push_back(i);
  1361. }
  1362. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1363. // type compatible with at most one of the types named in its generic
  1364. // association list."
  1365. if (CompatIndices.size() > 1) {
  1366. // We strip parens here because the controlling expression is typically
  1367. // parenthesized in macro definitions.
  1368. ControllingExpr = ControllingExpr->IgnoreParens();
  1369. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1370. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1371. << (unsigned)CompatIndices.size();
  1372. for (unsigned I : CompatIndices) {
  1373. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1374. diag::note_compat_assoc)
  1375. << Types[I]->getTypeLoc().getSourceRange()
  1376. << Types[I]->getType();
  1377. }
  1378. return ExprError();
  1379. }
  1380. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1381. // its controlling expression shall have type compatible with exactly one of
  1382. // the types named in its generic association list."
  1383. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1384. // We strip parens here because the controlling expression is typically
  1385. // parenthesized in macro definitions.
  1386. ControllingExpr = ControllingExpr->IgnoreParens();
  1387. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1388. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1389. return ExprError();
  1390. }
  1391. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1392. // type name that is compatible with the type of the controlling expression,
  1393. // then the result expression of the generic selection is the expression
  1394. // in that generic association. Otherwise, the result expression of the
  1395. // generic selection is the expression in the default generic association."
  1396. unsigned ResultIndex =
  1397. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1398. return GenericSelectionExpr::Create(
  1399. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1400. ContainsUnexpandedParameterPack, ResultIndex);
  1401. }
  1402. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1403. /// location of the token and the offset of the ud-suffix within it.
  1404. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1405. unsigned Offset) {
  1406. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1407. S.getLangOpts());
  1408. }
  1409. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1410. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1411. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1412. IdentifierInfo *UDSuffix,
  1413. SourceLocation UDSuffixLoc,
  1414. ArrayRef<Expr*> Args,
  1415. SourceLocation LitEndLoc) {
  1416. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1417. QualType ArgTy[2];
  1418. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1419. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1420. if (ArgTy[ArgIdx]->isArrayType())
  1421. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1422. }
  1423. DeclarationName OpName =
  1424. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1425. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1426. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1427. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1428. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1429. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1430. /*AllowStringTemplate*/ false,
  1431. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1432. return ExprError();
  1433. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1434. }
  1435. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1436. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1437. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1438. /// multiple tokens. However, the common case is that StringToks points to one
  1439. /// string.
  1440. ///
  1441. ExprResult
  1442. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1443. assert(!StringToks.empty() && "Must have at least one string!");
  1444. StringLiteralParser Literal(StringToks, PP);
  1445. if (Literal.hadError)
  1446. return ExprError();
  1447. SmallVector<SourceLocation, 4> StringTokLocs;
  1448. for (const Token &Tok : StringToks)
  1449. StringTokLocs.push_back(Tok.getLocation());
  1450. QualType CharTy = Context.CharTy;
  1451. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1452. if (Literal.isWide()) {
  1453. CharTy = Context.getWideCharType();
  1454. Kind = StringLiteral::Wide;
  1455. } else if (Literal.isUTF8()) {
  1456. if (getLangOpts().Char8)
  1457. CharTy = Context.Char8Ty;
  1458. Kind = StringLiteral::UTF8;
  1459. } else if (Literal.isUTF16()) {
  1460. CharTy = Context.Char16Ty;
  1461. Kind = StringLiteral::UTF16;
  1462. } else if (Literal.isUTF32()) {
  1463. CharTy = Context.Char32Ty;
  1464. Kind = StringLiteral::UTF32;
  1465. } else if (Literal.isPascal()) {
  1466. CharTy = Context.UnsignedCharTy;
  1467. }
  1468. // Warn on initializing an array of char from a u8 string literal; this
  1469. // becomes ill-formed in C++2a.
  1470. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
  1471. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1472. Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
  1473. // Create removals for all 'u8' prefixes in the string literal(s). This
  1474. // ensures C++2a compatibility (but may change the program behavior when
  1475. // built by non-Clang compilers for which the execution character set is
  1476. // not always UTF-8).
  1477. auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
  1478. SourceLocation RemovalDiagLoc;
  1479. for (const Token &Tok : StringToks) {
  1480. if (Tok.getKind() == tok::utf8_string_literal) {
  1481. if (RemovalDiagLoc.isInvalid())
  1482. RemovalDiagLoc = Tok.getLocation();
  1483. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1484. Tok.getLocation(),
  1485. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1486. getSourceManager(), getLangOpts())));
  1487. }
  1488. }
  1489. Diag(RemovalDiagLoc, RemovalDiag);
  1490. }
  1491. QualType StrTy =
  1492. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1493. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1494. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1495. Kind, Literal.Pascal, StrTy,
  1496. &StringTokLocs[0],
  1497. StringTokLocs.size());
  1498. if (Literal.getUDSuffix().empty())
  1499. return Lit;
  1500. // We're building a user-defined literal.
  1501. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1502. SourceLocation UDSuffixLoc =
  1503. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1504. Literal.getUDSuffixOffset());
  1505. // Make sure we're allowed user-defined literals here.
  1506. if (!UDLScope)
  1507. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1508. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1509. // operator "" X (str, len)
  1510. QualType SizeType = Context.getSizeType();
  1511. DeclarationName OpName =
  1512. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1513. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1514. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1515. QualType ArgTy[] = {
  1516. Context.getArrayDecayedType(StrTy), SizeType
  1517. };
  1518. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1519. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1520. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1521. /*AllowStringTemplate*/ true,
  1522. /*DiagnoseMissing*/ true)) {
  1523. case LOLR_Cooked: {
  1524. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1525. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1526. StringTokLocs[0]);
  1527. Expr *Args[] = { Lit, LenArg };
  1528. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1529. }
  1530. case LOLR_StringTemplate: {
  1531. TemplateArgumentListInfo ExplicitArgs;
  1532. unsigned CharBits = Context.getIntWidth(CharTy);
  1533. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1534. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1535. TemplateArgument TypeArg(CharTy);
  1536. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1537. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1538. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1539. Value = Lit->getCodeUnit(I);
  1540. TemplateArgument Arg(Context, Value, CharTy);
  1541. TemplateArgumentLocInfo ArgInfo;
  1542. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1543. }
  1544. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1545. &ExplicitArgs);
  1546. }
  1547. case LOLR_Raw:
  1548. case LOLR_Template:
  1549. case LOLR_ErrorNoDiagnostic:
  1550. llvm_unreachable("unexpected literal operator lookup result");
  1551. case LOLR_Error:
  1552. return ExprError();
  1553. }
  1554. llvm_unreachable("unexpected literal operator lookup result");
  1555. }
  1556. DeclRefExpr *
  1557. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1558. SourceLocation Loc,
  1559. const CXXScopeSpec *SS) {
  1560. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1561. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1562. }
  1563. DeclRefExpr *
  1564. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1565. const DeclarationNameInfo &NameInfo,
  1566. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1567. SourceLocation TemplateKWLoc,
  1568. const TemplateArgumentListInfo *TemplateArgs) {
  1569. NestedNameSpecifierLoc NNS =
  1570. SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
  1571. return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
  1572. TemplateArgs);
  1573. }
  1574. NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
  1575. // A declaration named in an unevaluated operand never constitutes an odr-use.
  1576. if (isUnevaluatedContext())
  1577. return NOUR_Unevaluated;
  1578. // C++2a [basic.def.odr]p4:
  1579. // A variable x whose name appears as a potentially-evaluated expression e
  1580. // is odr-used by e unless [...] x is a reference that is usable in
  1581. // constant expressions.
  1582. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1583. if (VD->getType()->isReferenceType() &&
  1584. !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
  1585. VD->isUsableInConstantExpressions(Context))
  1586. return NOUR_Constant;
  1587. }
  1588. // All remaining non-variable cases constitute an odr-use. For variables, we
  1589. // need to wait and see how the expression is used.
  1590. return NOUR_None;
  1591. }
  1592. /// BuildDeclRefExpr - Build an expression that references a
  1593. /// declaration that does not require a closure capture.
  1594. DeclRefExpr *
  1595. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1596. const DeclarationNameInfo &NameInfo,
  1597. NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
  1598. SourceLocation TemplateKWLoc,
  1599. const TemplateArgumentListInfo *TemplateArgs) {
  1600. bool RefersToCapturedVariable =
  1601. isa<VarDecl>(D) &&
  1602. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1603. DeclRefExpr *E = DeclRefExpr::Create(
  1604. Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
  1605. VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
  1606. MarkDeclRefReferenced(E);
  1607. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1608. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1609. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1610. getCurFunction()->recordUseOfWeak(E);
  1611. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1612. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1613. FD = IFD->getAnonField();
  1614. if (FD) {
  1615. UnusedPrivateFields.remove(FD);
  1616. // Just in case we're building an illegal pointer-to-member.
  1617. if (FD->isBitField())
  1618. E->setObjectKind(OK_BitField);
  1619. }
  1620. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1621. // designates a bit-field.
  1622. if (auto *BD = dyn_cast<BindingDecl>(D))
  1623. if (auto *BE = BD->getBinding())
  1624. E->setObjectKind(BE->getObjectKind());
  1625. return E;
  1626. }
  1627. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1628. /// possibly a list of template arguments.
  1629. ///
  1630. /// If this produces template arguments, it is permitted to call
  1631. /// DecomposeTemplateName.
  1632. ///
  1633. /// This actually loses a lot of source location information for
  1634. /// non-standard name kinds; we should consider preserving that in
  1635. /// some way.
  1636. void
  1637. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1638. TemplateArgumentListInfo &Buffer,
  1639. DeclarationNameInfo &NameInfo,
  1640. const TemplateArgumentListInfo *&TemplateArgs) {
  1641. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1642. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1643. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1644. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1645. Id.TemplateId->NumArgs);
  1646. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1647. TemplateName TName = Id.TemplateId->Template.get();
  1648. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1649. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1650. TemplateArgs = &Buffer;
  1651. } else {
  1652. NameInfo = GetNameFromUnqualifiedId(Id);
  1653. TemplateArgs = nullptr;
  1654. }
  1655. }
  1656. static void emitEmptyLookupTypoDiagnostic(
  1657. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1658. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1659. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1660. DeclContext *Ctx =
  1661. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1662. if (!TC) {
  1663. // Emit a special diagnostic for failed member lookups.
  1664. // FIXME: computing the declaration context might fail here (?)
  1665. if (Ctx)
  1666. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1667. << SS.getRange();
  1668. else
  1669. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1670. return;
  1671. }
  1672. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1673. bool DroppedSpecifier =
  1674. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1675. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1676. ? diag::note_implicit_param_decl
  1677. : diag::note_previous_decl;
  1678. if (!Ctx)
  1679. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1680. SemaRef.PDiag(NoteID));
  1681. else
  1682. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1683. << Typo << Ctx << DroppedSpecifier
  1684. << SS.getRange(),
  1685. SemaRef.PDiag(NoteID));
  1686. }
  1687. /// Diagnose an empty lookup.
  1688. ///
  1689. /// \return false if new lookup candidates were found
  1690. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1691. CorrectionCandidateCallback &CCC,
  1692. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1693. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1694. DeclarationName Name = R.getLookupName();
  1695. unsigned diagnostic = diag::err_undeclared_var_use;
  1696. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1697. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1698. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1699. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1700. diagnostic = diag::err_undeclared_use;
  1701. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1702. }
  1703. // If the original lookup was an unqualified lookup, fake an
  1704. // unqualified lookup. This is useful when (for example) the
  1705. // original lookup would not have found something because it was a
  1706. // dependent name.
  1707. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1708. while (DC) {
  1709. if (isa<CXXRecordDecl>(DC)) {
  1710. LookupQualifiedName(R, DC);
  1711. if (!R.empty()) {
  1712. // Don't give errors about ambiguities in this lookup.
  1713. R.suppressDiagnostics();
  1714. // During a default argument instantiation the CurContext points
  1715. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1716. // function parameter list, hence add an explicit check.
  1717. bool isDefaultArgument =
  1718. !CodeSynthesisContexts.empty() &&
  1719. CodeSynthesisContexts.back().Kind ==
  1720. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1721. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1722. bool isInstance = CurMethod &&
  1723. CurMethod->isInstance() &&
  1724. DC == CurMethod->getParent() && !isDefaultArgument;
  1725. // Give a code modification hint to insert 'this->'.
  1726. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1727. // Actually quite difficult!
  1728. if (getLangOpts().MSVCCompat)
  1729. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1730. if (isInstance) {
  1731. Diag(R.getNameLoc(), diagnostic) << Name
  1732. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1733. CheckCXXThisCapture(R.getNameLoc());
  1734. } else {
  1735. Diag(R.getNameLoc(), diagnostic) << Name;
  1736. }
  1737. // Do we really want to note all of these?
  1738. for (NamedDecl *D : R)
  1739. Diag(D->getLocation(), diag::note_dependent_var_use);
  1740. // Return true if we are inside a default argument instantiation
  1741. // and the found name refers to an instance member function, otherwise
  1742. // the function calling DiagnoseEmptyLookup will try to create an
  1743. // implicit member call and this is wrong for default argument.
  1744. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1745. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1746. return true;
  1747. }
  1748. // Tell the callee to try to recover.
  1749. return false;
  1750. }
  1751. R.clear();
  1752. }
  1753. DC = DC->getLookupParent();
  1754. }
  1755. // We didn't find anything, so try to correct for a typo.
  1756. TypoCorrection Corrected;
  1757. if (S && Out) {
  1758. SourceLocation TypoLoc = R.getNameLoc();
  1759. assert(!ExplicitTemplateArgs &&
  1760. "Diagnosing an empty lookup with explicit template args!");
  1761. *Out = CorrectTypoDelayed(
  1762. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1763. [=](const TypoCorrection &TC) {
  1764. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1765. diagnostic, diagnostic_suggest);
  1766. },
  1767. nullptr, CTK_ErrorRecovery);
  1768. if (*Out)
  1769. return true;
  1770. } else if (S &&
  1771. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1772. S, &SS, CCC, CTK_ErrorRecovery))) {
  1773. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1774. bool DroppedSpecifier =
  1775. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1776. R.setLookupName(Corrected.getCorrection());
  1777. bool AcceptableWithRecovery = false;
  1778. bool AcceptableWithoutRecovery = false;
  1779. NamedDecl *ND = Corrected.getFoundDecl();
  1780. if (ND) {
  1781. if (Corrected.isOverloaded()) {
  1782. OverloadCandidateSet OCS(R.getNameLoc(),
  1783. OverloadCandidateSet::CSK_Normal);
  1784. OverloadCandidateSet::iterator Best;
  1785. for (NamedDecl *CD : Corrected) {
  1786. if (FunctionTemplateDecl *FTD =
  1787. dyn_cast<FunctionTemplateDecl>(CD))
  1788. AddTemplateOverloadCandidate(
  1789. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1790. Args, OCS);
  1791. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1792. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1793. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1794. Args, OCS);
  1795. }
  1796. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1797. case OR_Success:
  1798. ND = Best->FoundDecl;
  1799. Corrected.setCorrectionDecl(ND);
  1800. break;
  1801. default:
  1802. // FIXME: Arbitrarily pick the first declaration for the note.
  1803. Corrected.setCorrectionDecl(ND);
  1804. break;
  1805. }
  1806. }
  1807. R.addDecl(ND);
  1808. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1809. CXXRecordDecl *Record = nullptr;
  1810. if (Corrected.getCorrectionSpecifier()) {
  1811. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1812. Record = Ty->getAsCXXRecordDecl();
  1813. }
  1814. if (!Record)
  1815. Record = cast<CXXRecordDecl>(
  1816. ND->getDeclContext()->getRedeclContext());
  1817. R.setNamingClass(Record);
  1818. }
  1819. auto *UnderlyingND = ND->getUnderlyingDecl();
  1820. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1821. isa<FunctionTemplateDecl>(UnderlyingND);
  1822. // FIXME: If we ended up with a typo for a type name or
  1823. // Objective-C class name, we're in trouble because the parser
  1824. // is in the wrong place to recover. Suggest the typo
  1825. // correction, but don't make it a fix-it since we're not going
  1826. // to recover well anyway.
  1827. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  1828. getAsTypeTemplateDecl(UnderlyingND) ||
  1829. isa<ObjCInterfaceDecl>(UnderlyingND);
  1830. } else {
  1831. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1832. // because we aren't able to recover.
  1833. AcceptableWithoutRecovery = true;
  1834. }
  1835. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1836. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1837. ? diag::note_implicit_param_decl
  1838. : diag::note_previous_decl;
  1839. if (SS.isEmpty())
  1840. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1841. PDiag(NoteID), AcceptableWithRecovery);
  1842. else
  1843. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1844. << Name << computeDeclContext(SS, false)
  1845. << DroppedSpecifier << SS.getRange(),
  1846. PDiag(NoteID), AcceptableWithRecovery);
  1847. // Tell the callee whether to try to recover.
  1848. return !AcceptableWithRecovery;
  1849. }
  1850. }
  1851. R.clear();
  1852. // Emit a special diagnostic for failed member lookups.
  1853. // FIXME: computing the declaration context might fail here (?)
  1854. if (!SS.isEmpty()) {
  1855. Diag(R.getNameLoc(), diag::err_no_member)
  1856. << Name << computeDeclContext(SS, false)
  1857. << SS.getRange();
  1858. return true;
  1859. }
  1860. // Give up, we can't recover.
  1861. Diag(R.getNameLoc(), diagnostic) << Name;
  1862. return true;
  1863. }
  1864. /// In Microsoft mode, if we are inside a template class whose parent class has
  1865. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1866. /// assume the identifier is a member of a dependent base class. We can only
  1867. /// recover successfully in static methods, instance methods, and other contexts
  1868. /// where 'this' is available. This doesn't precisely match MSVC's
  1869. /// instantiation model, but it's close enough.
  1870. static Expr *
  1871. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1872. DeclarationNameInfo &NameInfo,
  1873. SourceLocation TemplateKWLoc,
  1874. const TemplateArgumentListInfo *TemplateArgs) {
  1875. // Only try to recover from lookup into dependent bases in static methods or
  1876. // contexts where 'this' is available.
  1877. QualType ThisType = S.getCurrentThisType();
  1878. const CXXRecordDecl *RD = nullptr;
  1879. if (!ThisType.isNull())
  1880. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1881. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1882. RD = MD->getParent();
  1883. if (!RD || !RD->hasAnyDependentBases())
  1884. return nullptr;
  1885. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1886. // is available, suggest inserting 'this->' as a fixit.
  1887. SourceLocation Loc = NameInfo.getLoc();
  1888. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1889. DB << NameInfo.getName() << RD;
  1890. if (!ThisType.isNull()) {
  1891. DB << FixItHint::CreateInsertion(Loc, "this->");
  1892. return CXXDependentScopeMemberExpr::Create(
  1893. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1894. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1895. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  1896. }
  1897. // Synthesize a fake NNS that points to the derived class. This will
  1898. // perform name lookup during template instantiation.
  1899. CXXScopeSpec SS;
  1900. auto *NNS =
  1901. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1902. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1903. return DependentScopeDeclRefExpr::Create(
  1904. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1905. TemplateArgs);
  1906. }
  1907. ExprResult
  1908. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1909. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1910. bool HasTrailingLParen, bool IsAddressOfOperand,
  1911. CorrectionCandidateCallback *CCC,
  1912. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1913. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1914. "cannot be direct & operand and have a trailing lparen");
  1915. if (SS.isInvalid())
  1916. return ExprError();
  1917. TemplateArgumentListInfo TemplateArgsBuffer;
  1918. // Decompose the UnqualifiedId into the following data.
  1919. DeclarationNameInfo NameInfo;
  1920. const TemplateArgumentListInfo *TemplateArgs;
  1921. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1922. DeclarationName Name = NameInfo.getName();
  1923. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1924. SourceLocation NameLoc = NameInfo.getLoc();
  1925. if (II && II->isEditorPlaceholder()) {
  1926. // FIXME: When typed placeholders are supported we can create a typed
  1927. // placeholder expression node.
  1928. return ExprError();
  1929. }
  1930. // C++ [temp.dep.expr]p3:
  1931. // An id-expression is type-dependent if it contains:
  1932. // -- an identifier that was declared with a dependent type,
  1933. // (note: handled after lookup)
  1934. // -- a template-id that is dependent,
  1935. // (note: handled in BuildTemplateIdExpr)
  1936. // -- a conversion-function-id that specifies a dependent type,
  1937. // -- a nested-name-specifier that contains a class-name that
  1938. // names a dependent type.
  1939. // Determine whether this is a member of an unknown specialization;
  1940. // we need to handle these differently.
  1941. bool DependentID = false;
  1942. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1943. Name.getCXXNameType()->isDependentType()) {
  1944. DependentID = true;
  1945. } else if (SS.isSet()) {
  1946. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1947. if (RequireCompleteDeclContext(SS, DC))
  1948. return ExprError();
  1949. } else {
  1950. DependentID = true;
  1951. }
  1952. }
  1953. if (DependentID)
  1954. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1955. IsAddressOfOperand, TemplateArgs);
  1956. // Perform the required lookup.
  1957. LookupResult R(*this, NameInfo,
  1958. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1959. ? LookupObjCImplicitSelfParam
  1960. : LookupOrdinaryName);
  1961. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1962. // Lookup the template name again to correctly establish the context in
  1963. // which it was found. This is really unfortunate as we already did the
  1964. // lookup to determine that it was a template name in the first place. If
  1965. // this becomes a performance hit, we can work harder to preserve those
  1966. // results until we get here but it's likely not worth it.
  1967. bool MemberOfUnknownSpecialization;
  1968. AssumedTemplateKind AssumedTemplate;
  1969. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1970. MemberOfUnknownSpecialization, TemplateKWLoc,
  1971. &AssumedTemplate))
  1972. return ExprError();
  1973. if (MemberOfUnknownSpecialization ||
  1974. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1975. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1976. IsAddressOfOperand, TemplateArgs);
  1977. } else {
  1978. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1979. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1980. // If the result might be in a dependent base class, this is a dependent
  1981. // id-expression.
  1982. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1983. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1984. IsAddressOfOperand, TemplateArgs);
  1985. // If this reference is in an Objective-C method, then we need to do
  1986. // some special Objective-C lookup, too.
  1987. if (IvarLookupFollowUp) {
  1988. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1989. if (E.isInvalid())
  1990. return ExprError();
  1991. if (Expr *Ex = E.getAs<Expr>())
  1992. return Ex;
  1993. }
  1994. }
  1995. if (R.isAmbiguous())
  1996. return ExprError();
  1997. // This could be an implicitly declared function reference (legal in C90,
  1998. // extension in C99, forbidden in C++).
  1999. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  2000. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2001. if (D) R.addDecl(D);
  2002. }
  2003. // Determine whether this name might be a candidate for
  2004. // argument-dependent lookup.
  2005. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2006. if (R.empty() && !ADL) {
  2007. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2008. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2009. TemplateKWLoc, TemplateArgs))
  2010. return E;
  2011. }
  2012. // Don't diagnose an empty lookup for inline assembly.
  2013. if (IsInlineAsmIdentifier)
  2014. return ExprError();
  2015. // If this name wasn't predeclared and if this is not a function
  2016. // call, diagnose the problem.
  2017. TypoExpr *TE = nullptr;
  2018. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2019. : nullptr);
  2020. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2021. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2022. "Typo correction callback misconfigured");
  2023. if (CCC) {
  2024. // Make sure the callback knows what the typo being diagnosed is.
  2025. CCC->setTypoName(II);
  2026. if (SS.isValid())
  2027. CCC->setTypoNNS(SS.getScopeRep());
  2028. }
  2029. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2030. // a template name, but we happen to have always already looked up the name
  2031. // before we get here if it must be a template name.
  2032. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2033. None, &TE)) {
  2034. if (TE && KeywordReplacement) {
  2035. auto &State = getTypoExprState(TE);
  2036. auto BestTC = State.Consumer->getNextCorrection();
  2037. if (BestTC.isKeyword()) {
  2038. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2039. if (State.DiagHandler)
  2040. State.DiagHandler(BestTC);
  2041. KeywordReplacement->startToken();
  2042. KeywordReplacement->setKind(II->getTokenID());
  2043. KeywordReplacement->setIdentifierInfo(II);
  2044. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2045. // Clean up the state associated with the TypoExpr, since it has
  2046. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2047. clearDelayedTypo(TE);
  2048. // Signal that a correction to a keyword was performed by returning a
  2049. // valid-but-null ExprResult.
  2050. return (Expr*)nullptr;
  2051. }
  2052. State.Consumer->resetCorrectionStream();
  2053. }
  2054. return TE ? TE : ExprError();
  2055. }
  2056. assert(!R.empty() &&
  2057. "DiagnoseEmptyLookup returned false but added no results");
  2058. // If we found an Objective-C instance variable, let
  2059. // LookupInObjCMethod build the appropriate expression to
  2060. // reference the ivar.
  2061. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2062. R.clear();
  2063. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2064. // In a hopelessly buggy code, Objective-C instance variable
  2065. // lookup fails and no expression will be built to reference it.
  2066. if (!E.isInvalid() && !E.get())
  2067. return ExprError();
  2068. return E;
  2069. }
  2070. }
  2071. // This is guaranteed from this point on.
  2072. assert(!R.empty() || ADL);
  2073. // Check whether this might be a C++ implicit instance member access.
  2074. // C++ [class.mfct.non-static]p3:
  2075. // When an id-expression that is not part of a class member access
  2076. // syntax and not used to form a pointer to member is used in the
  2077. // body of a non-static member function of class X, if name lookup
  2078. // resolves the name in the id-expression to a non-static non-type
  2079. // member of some class C, the id-expression is transformed into a
  2080. // class member access expression using (*this) as the
  2081. // postfix-expression to the left of the . operator.
  2082. //
  2083. // But we don't actually need to do this for '&' operands if R
  2084. // resolved to a function or overloaded function set, because the
  2085. // expression is ill-formed if it actually works out to be a
  2086. // non-static member function:
  2087. //
  2088. // C++ [expr.ref]p4:
  2089. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2090. // [t]he expression can be used only as the left-hand operand of a
  2091. // member function call.
  2092. //
  2093. // There are other safeguards against such uses, but it's important
  2094. // to get this right here so that we don't end up making a
  2095. // spuriously dependent expression if we're inside a dependent
  2096. // instance method.
  2097. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2098. bool MightBeImplicitMember;
  2099. if (!IsAddressOfOperand)
  2100. MightBeImplicitMember = true;
  2101. else if (!SS.isEmpty())
  2102. MightBeImplicitMember = false;
  2103. else if (R.isOverloadedResult())
  2104. MightBeImplicitMember = false;
  2105. else if (R.isUnresolvableResult())
  2106. MightBeImplicitMember = true;
  2107. else
  2108. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2109. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2110. isa<MSPropertyDecl>(R.getFoundDecl());
  2111. if (MightBeImplicitMember)
  2112. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2113. R, TemplateArgs, S);
  2114. }
  2115. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2116. // In C++1y, if this is a variable template id, then check it
  2117. // in BuildTemplateIdExpr().
  2118. // The single lookup result must be a variable template declaration.
  2119. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2120. Id.TemplateId->Kind == TNK_Var_template) {
  2121. assert(R.getAsSingle<VarTemplateDecl>() &&
  2122. "There should only be one declaration found.");
  2123. }
  2124. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2125. }
  2126. return BuildDeclarationNameExpr(SS, R, ADL);
  2127. }
  2128. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2129. /// declaration name, generally during template instantiation.
  2130. /// There's a large number of things which don't need to be done along
  2131. /// this path.
  2132. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2133. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2134. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2135. DeclContext *DC = computeDeclContext(SS, false);
  2136. if (!DC)
  2137. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2138. NameInfo, /*TemplateArgs=*/nullptr);
  2139. if (RequireCompleteDeclContext(SS, DC))
  2140. return ExprError();
  2141. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2142. LookupQualifiedName(R, DC);
  2143. if (R.isAmbiguous())
  2144. return ExprError();
  2145. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2146. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2147. NameInfo, /*TemplateArgs=*/nullptr);
  2148. if (R.empty()) {
  2149. Diag(NameInfo.getLoc(), diag::err_no_member)
  2150. << NameInfo.getName() << DC << SS.getRange();
  2151. return ExprError();
  2152. }
  2153. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2154. // Diagnose a missing typename if this resolved unambiguously to a type in
  2155. // a dependent context. If we can recover with a type, downgrade this to
  2156. // a warning in Microsoft compatibility mode.
  2157. unsigned DiagID = diag::err_typename_missing;
  2158. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2159. DiagID = diag::ext_typename_missing;
  2160. SourceLocation Loc = SS.getBeginLoc();
  2161. auto D = Diag(Loc, DiagID);
  2162. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2163. << SourceRange(Loc, NameInfo.getEndLoc());
  2164. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2165. // context.
  2166. if (!RecoveryTSI)
  2167. return ExprError();
  2168. // Only issue the fixit if we're prepared to recover.
  2169. D << FixItHint::CreateInsertion(Loc, "typename ");
  2170. // Recover by pretending this was an elaborated type.
  2171. QualType Ty = Context.getTypeDeclType(TD);
  2172. TypeLocBuilder TLB;
  2173. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2174. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2175. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2176. QTL.setElaboratedKeywordLoc(SourceLocation());
  2177. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2178. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2179. return ExprEmpty();
  2180. }
  2181. // Defend against this resolving to an implicit member access. We usually
  2182. // won't get here if this might be a legitimate a class member (we end up in
  2183. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2184. // a pointer-to-member or in an unevaluated context in C++11.
  2185. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2186. return BuildPossibleImplicitMemberExpr(SS,
  2187. /*TemplateKWLoc=*/SourceLocation(),
  2188. R, /*TemplateArgs=*/nullptr, S);
  2189. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2190. }
  2191. /// The parser has read a name in, and Sema has detected that we're currently
  2192. /// inside an ObjC method. Perform some additional checks and determine if we
  2193. /// should form a reference to an ivar.
  2194. ///
  2195. /// Ideally, most of this would be done by lookup, but there's
  2196. /// actually quite a lot of extra work involved.
  2197. DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
  2198. IdentifierInfo *II) {
  2199. SourceLocation Loc = Lookup.getNameLoc();
  2200. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2201. // Check for error condition which is already reported.
  2202. if (!CurMethod)
  2203. return DeclResult(true);
  2204. // There are two cases to handle here. 1) scoped lookup could have failed,
  2205. // in which case we should look for an ivar. 2) scoped lookup could have
  2206. // found a decl, but that decl is outside the current instance method (i.e.
  2207. // a global variable). In these two cases, we do a lookup for an ivar with
  2208. // this name, if the lookup sucedes, we replace it our current decl.
  2209. // If we're in a class method, we don't normally want to look for
  2210. // ivars. But if we don't find anything else, and there's an
  2211. // ivar, that's an error.
  2212. bool IsClassMethod = CurMethod->isClassMethod();
  2213. bool LookForIvars;
  2214. if (Lookup.empty())
  2215. LookForIvars = true;
  2216. else if (IsClassMethod)
  2217. LookForIvars = false;
  2218. else
  2219. LookForIvars = (Lookup.isSingleResult() &&
  2220. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2221. ObjCInterfaceDecl *IFace = nullptr;
  2222. if (LookForIvars) {
  2223. IFace = CurMethod->getClassInterface();
  2224. ObjCInterfaceDecl *ClassDeclared;
  2225. ObjCIvarDecl *IV = nullptr;
  2226. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2227. // Diagnose using an ivar in a class method.
  2228. if (IsClassMethod) {
  2229. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2230. return DeclResult(true);
  2231. }
  2232. // Diagnose the use of an ivar outside of the declaring class.
  2233. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2234. !declaresSameEntity(ClassDeclared, IFace) &&
  2235. !getLangOpts().DebuggerSupport)
  2236. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2237. // Success.
  2238. return IV;
  2239. }
  2240. } else if (CurMethod->isInstanceMethod()) {
  2241. // We should warn if a local variable hides an ivar.
  2242. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2243. ObjCInterfaceDecl *ClassDeclared;
  2244. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2245. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2246. declaresSameEntity(IFace, ClassDeclared))
  2247. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2248. }
  2249. }
  2250. } else if (Lookup.isSingleResult() &&
  2251. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2252. // If accessing a stand-alone ivar in a class method, this is an error.
  2253. if (const ObjCIvarDecl *IV =
  2254. dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
  2255. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2256. return DeclResult(true);
  2257. }
  2258. }
  2259. // Didn't encounter an error, didn't find an ivar.
  2260. return DeclResult(false);
  2261. }
  2262. ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
  2263. ObjCIvarDecl *IV) {
  2264. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2265. assert(CurMethod && CurMethod->isInstanceMethod() &&
  2266. "should not reference ivar from this context");
  2267. ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
  2268. assert(IFace && "should not reference ivar from this context");
  2269. // If we're referencing an invalid decl, just return this as a silent
  2270. // error node. The error diagnostic was already emitted on the decl.
  2271. if (IV->isInvalidDecl())
  2272. return ExprError();
  2273. // Check if referencing a field with __attribute__((deprecated)).
  2274. if (DiagnoseUseOfDecl(IV, Loc))
  2275. return ExprError();
  2276. // FIXME: This should use a new expr for a direct reference, don't
  2277. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2278. IdentifierInfo &II = Context.Idents.get("self");
  2279. UnqualifiedId SelfName;
  2280. SelfName.setIdentifier(&II, SourceLocation());
  2281. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2282. CXXScopeSpec SelfScopeSpec;
  2283. SourceLocation TemplateKWLoc;
  2284. ExprResult SelfExpr =
  2285. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2286. /*HasTrailingLParen=*/false,
  2287. /*IsAddressOfOperand=*/false);
  2288. if (SelfExpr.isInvalid())
  2289. return ExprError();
  2290. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2291. if (SelfExpr.isInvalid())
  2292. return ExprError();
  2293. MarkAnyDeclReferenced(Loc, IV, true);
  2294. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2295. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2296. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2297. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2298. ObjCIvarRefExpr *Result = new (Context)
  2299. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2300. IV->getLocation(), SelfExpr.get(), true, true);
  2301. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2302. if (!isUnevaluatedContext() &&
  2303. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2304. getCurFunction()->recordUseOfWeak(Result);
  2305. }
  2306. if (getLangOpts().ObjCAutoRefCount)
  2307. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2308. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2309. return Result;
  2310. }
  2311. /// The parser has read a name in, and Sema has detected that we're currently
  2312. /// inside an ObjC method. Perform some additional checks and determine if we
  2313. /// should form a reference to an ivar. If so, build an expression referencing
  2314. /// that ivar.
  2315. ExprResult
  2316. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2317. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2318. // FIXME: Integrate this lookup step into LookupParsedName.
  2319. DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
  2320. if (Ivar.isInvalid())
  2321. return ExprError();
  2322. if (Ivar.isUsable())
  2323. return BuildIvarRefExpr(S, Lookup.getNameLoc(),
  2324. cast<ObjCIvarDecl>(Ivar.get()));
  2325. if (Lookup.empty() && II && AllowBuiltinCreation)
  2326. LookupBuiltin(Lookup);
  2327. // Sentinel value saying that we didn't do anything special.
  2328. return ExprResult(false);
  2329. }
  2330. /// Cast a base object to a member's actual type.
  2331. ///
  2332. /// Logically this happens in three phases:
  2333. ///
  2334. /// * First we cast from the base type to the naming class.
  2335. /// The naming class is the class into which we were looking
  2336. /// when we found the member; it's the qualifier type if a
  2337. /// qualifier was provided, and otherwise it's the base type.
  2338. ///
  2339. /// * Next we cast from the naming class to the declaring class.
  2340. /// If the member we found was brought into a class's scope by
  2341. /// a using declaration, this is that class; otherwise it's
  2342. /// the class declaring the member.
  2343. ///
  2344. /// * Finally we cast from the declaring class to the "true"
  2345. /// declaring class of the member. This conversion does not
  2346. /// obey access control.
  2347. ExprResult
  2348. Sema::PerformObjectMemberConversion(Expr *From,
  2349. NestedNameSpecifier *Qualifier,
  2350. NamedDecl *FoundDecl,
  2351. NamedDecl *Member) {
  2352. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2353. if (!RD)
  2354. return From;
  2355. QualType DestRecordType;
  2356. QualType DestType;
  2357. QualType FromRecordType;
  2358. QualType FromType = From->getType();
  2359. bool PointerConversions = false;
  2360. if (isa<FieldDecl>(Member)) {
  2361. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2362. auto FromPtrType = FromType->getAs<PointerType>();
  2363. DestRecordType = Context.getAddrSpaceQualType(
  2364. DestRecordType, FromPtrType
  2365. ? FromType->getPointeeType().getAddressSpace()
  2366. : FromType.getAddressSpace());
  2367. if (FromPtrType) {
  2368. DestType = Context.getPointerType(DestRecordType);
  2369. FromRecordType = FromPtrType->getPointeeType();
  2370. PointerConversions = true;
  2371. } else {
  2372. DestType = DestRecordType;
  2373. FromRecordType = FromType;
  2374. }
  2375. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2376. if (Method->isStatic())
  2377. return From;
  2378. DestType = Method->getThisType();
  2379. DestRecordType = DestType->getPointeeType();
  2380. if (FromType->getAs<PointerType>()) {
  2381. FromRecordType = FromType->getPointeeType();
  2382. PointerConversions = true;
  2383. } else {
  2384. FromRecordType = FromType;
  2385. DestType = DestRecordType;
  2386. }
  2387. } else {
  2388. // No conversion necessary.
  2389. return From;
  2390. }
  2391. if (DestType->isDependentType() || FromType->isDependentType())
  2392. return From;
  2393. // If the unqualified types are the same, no conversion is necessary.
  2394. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2395. return From;
  2396. SourceRange FromRange = From->getSourceRange();
  2397. SourceLocation FromLoc = FromRange.getBegin();
  2398. ExprValueKind VK = From->getValueKind();
  2399. // C++ [class.member.lookup]p8:
  2400. // [...] Ambiguities can often be resolved by qualifying a name with its
  2401. // class name.
  2402. //
  2403. // If the member was a qualified name and the qualified referred to a
  2404. // specific base subobject type, we'll cast to that intermediate type
  2405. // first and then to the object in which the member is declared. That allows
  2406. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2407. //
  2408. // class Base { public: int x; };
  2409. // class Derived1 : public Base { };
  2410. // class Derived2 : public Base { };
  2411. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2412. //
  2413. // void VeryDerived::f() {
  2414. // x = 17; // error: ambiguous base subobjects
  2415. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2416. // }
  2417. if (Qualifier && Qualifier->getAsType()) {
  2418. QualType QType = QualType(Qualifier->getAsType(), 0);
  2419. assert(QType->isRecordType() && "lookup done with non-record type");
  2420. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2421. // In C++98, the qualifier type doesn't actually have to be a base
  2422. // type of the object type, in which case we just ignore it.
  2423. // Otherwise build the appropriate casts.
  2424. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2425. CXXCastPath BasePath;
  2426. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2427. FromLoc, FromRange, &BasePath))
  2428. return ExprError();
  2429. if (PointerConversions)
  2430. QType = Context.getPointerType(QType);
  2431. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2432. VK, &BasePath).get();
  2433. FromType = QType;
  2434. FromRecordType = QRecordType;
  2435. // If the qualifier type was the same as the destination type,
  2436. // we're done.
  2437. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2438. return From;
  2439. }
  2440. }
  2441. bool IgnoreAccess = false;
  2442. // If we actually found the member through a using declaration, cast
  2443. // down to the using declaration's type.
  2444. //
  2445. // Pointer equality is fine here because only one declaration of a
  2446. // class ever has member declarations.
  2447. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2448. assert(isa<UsingShadowDecl>(FoundDecl));
  2449. QualType URecordType = Context.getTypeDeclType(
  2450. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2451. // We only need to do this if the naming-class to declaring-class
  2452. // conversion is non-trivial.
  2453. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2454. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2455. CXXCastPath BasePath;
  2456. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2457. FromLoc, FromRange, &BasePath))
  2458. return ExprError();
  2459. QualType UType = URecordType;
  2460. if (PointerConversions)
  2461. UType = Context.getPointerType(UType);
  2462. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2463. VK, &BasePath).get();
  2464. FromType = UType;
  2465. FromRecordType = URecordType;
  2466. }
  2467. // We don't do access control for the conversion from the
  2468. // declaring class to the true declaring class.
  2469. IgnoreAccess = true;
  2470. }
  2471. CXXCastPath BasePath;
  2472. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2473. FromLoc, FromRange, &BasePath,
  2474. IgnoreAccess))
  2475. return ExprError();
  2476. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2477. VK, &BasePath);
  2478. }
  2479. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2480. const LookupResult &R,
  2481. bool HasTrailingLParen) {
  2482. // Only when used directly as the postfix-expression of a call.
  2483. if (!HasTrailingLParen)
  2484. return false;
  2485. // Never if a scope specifier was provided.
  2486. if (SS.isSet())
  2487. return false;
  2488. // Only in C++ or ObjC++.
  2489. if (!getLangOpts().CPlusPlus)
  2490. return false;
  2491. // Turn off ADL when we find certain kinds of declarations during
  2492. // normal lookup:
  2493. for (NamedDecl *D : R) {
  2494. // C++0x [basic.lookup.argdep]p3:
  2495. // -- a declaration of a class member
  2496. // Since using decls preserve this property, we check this on the
  2497. // original decl.
  2498. if (D->isCXXClassMember())
  2499. return false;
  2500. // C++0x [basic.lookup.argdep]p3:
  2501. // -- a block-scope function declaration that is not a
  2502. // using-declaration
  2503. // NOTE: we also trigger this for function templates (in fact, we
  2504. // don't check the decl type at all, since all other decl types
  2505. // turn off ADL anyway).
  2506. if (isa<UsingShadowDecl>(D))
  2507. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2508. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2509. return false;
  2510. // C++0x [basic.lookup.argdep]p3:
  2511. // -- a declaration that is neither a function or a function
  2512. // template
  2513. // And also for builtin functions.
  2514. if (isa<FunctionDecl>(D)) {
  2515. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2516. // But also builtin functions.
  2517. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2518. return false;
  2519. } else if (!isa<FunctionTemplateDecl>(D))
  2520. return false;
  2521. }
  2522. return true;
  2523. }
  2524. /// Diagnoses obvious problems with the use of the given declaration
  2525. /// as an expression. This is only actually called for lookups that
  2526. /// were not overloaded, and it doesn't promise that the declaration
  2527. /// will in fact be used.
  2528. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2529. if (D->isInvalidDecl())
  2530. return true;
  2531. if (isa<TypedefNameDecl>(D)) {
  2532. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2533. return true;
  2534. }
  2535. if (isa<ObjCInterfaceDecl>(D)) {
  2536. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2537. return true;
  2538. }
  2539. if (isa<NamespaceDecl>(D)) {
  2540. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2541. return true;
  2542. }
  2543. return false;
  2544. }
  2545. // Certain multiversion types should be treated as overloaded even when there is
  2546. // only one result.
  2547. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2548. assert(R.isSingleResult() && "Expected only a single result");
  2549. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2550. return FD &&
  2551. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2552. }
  2553. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2554. LookupResult &R, bool NeedsADL,
  2555. bool AcceptInvalidDecl) {
  2556. // If this is a single, fully-resolved result and we don't need ADL,
  2557. // just build an ordinary singleton decl ref.
  2558. if (!NeedsADL && R.isSingleResult() &&
  2559. !R.getAsSingle<FunctionTemplateDecl>() &&
  2560. !ShouldLookupResultBeMultiVersionOverload(R))
  2561. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2562. R.getRepresentativeDecl(), nullptr,
  2563. AcceptInvalidDecl);
  2564. // We only need to check the declaration if there's exactly one
  2565. // result, because in the overloaded case the results can only be
  2566. // functions and function templates.
  2567. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2568. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2569. return ExprError();
  2570. // Otherwise, just build an unresolved lookup expression. Suppress
  2571. // any lookup-related diagnostics; we'll hash these out later, when
  2572. // we've picked a target.
  2573. R.suppressDiagnostics();
  2574. UnresolvedLookupExpr *ULE
  2575. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2576. SS.getWithLocInContext(Context),
  2577. R.getLookupNameInfo(),
  2578. NeedsADL, R.isOverloadedResult(),
  2579. R.begin(), R.end());
  2580. return ULE;
  2581. }
  2582. static void
  2583. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2584. ValueDecl *var, DeclContext *DC);
  2585. /// Complete semantic analysis for a reference to the given declaration.
  2586. ExprResult Sema::BuildDeclarationNameExpr(
  2587. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2588. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2589. bool AcceptInvalidDecl) {
  2590. assert(D && "Cannot refer to a NULL declaration");
  2591. assert(!isa<FunctionTemplateDecl>(D) &&
  2592. "Cannot refer unambiguously to a function template");
  2593. SourceLocation Loc = NameInfo.getLoc();
  2594. if (CheckDeclInExpr(*this, Loc, D))
  2595. return ExprError();
  2596. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2597. // Specifically diagnose references to class templates that are missing
  2598. // a template argument list.
  2599. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2600. return ExprError();
  2601. }
  2602. // Make sure that we're referring to a value.
  2603. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2604. if (!VD) {
  2605. Diag(Loc, diag::err_ref_non_value)
  2606. << D << SS.getRange();
  2607. Diag(D->getLocation(), diag::note_declared_at);
  2608. return ExprError();
  2609. }
  2610. // Check whether this declaration can be used. Note that we suppress
  2611. // this check when we're going to perform argument-dependent lookup
  2612. // on this function name, because this might not be the function
  2613. // that overload resolution actually selects.
  2614. if (DiagnoseUseOfDecl(VD, Loc))
  2615. return ExprError();
  2616. // Only create DeclRefExpr's for valid Decl's.
  2617. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2618. return ExprError();
  2619. // Handle members of anonymous structs and unions. If we got here,
  2620. // and the reference is to a class member indirect field, then this
  2621. // must be the subject of a pointer-to-member expression.
  2622. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2623. if (!indirectField->isCXXClassMember())
  2624. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2625. indirectField);
  2626. {
  2627. QualType type = VD->getType();
  2628. if (type.isNull())
  2629. return ExprError();
  2630. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2631. // C++ [except.spec]p17:
  2632. // An exception-specification is considered to be needed when:
  2633. // - in an expression, the function is the unique lookup result or
  2634. // the selected member of a set of overloaded functions.
  2635. ResolveExceptionSpec(Loc, FPT);
  2636. type = VD->getType();
  2637. }
  2638. ExprValueKind valueKind = VK_RValue;
  2639. switch (D->getKind()) {
  2640. // Ignore all the non-ValueDecl kinds.
  2641. #define ABSTRACT_DECL(kind)
  2642. #define VALUE(type, base)
  2643. #define DECL(type, base) \
  2644. case Decl::type:
  2645. #include "clang/AST/DeclNodes.inc"
  2646. llvm_unreachable("invalid value decl kind");
  2647. // These shouldn't make it here.
  2648. case Decl::ObjCAtDefsField:
  2649. llvm_unreachable("forming non-member reference to ivar?");
  2650. // Enum constants are always r-values and never references.
  2651. // Unresolved using declarations are dependent.
  2652. case Decl::EnumConstant:
  2653. case Decl::UnresolvedUsingValue:
  2654. case Decl::OMPDeclareReduction:
  2655. case Decl::OMPDeclareMapper:
  2656. valueKind = VK_RValue;
  2657. break;
  2658. // Fields and indirect fields that got here must be for
  2659. // pointer-to-member expressions; we just call them l-values for
  2660. // internal consistency, because this subexpression doesn't really
  2661. // exist in the high-level semantics.
  2662. case Decl::Field:
  2663. case Decl::IndirectField:
  2664. case Decl::ObjCIvar:
  2665. assert(getLangOpts().CPlusPlus &&
  2666. "building reference to field in C?");
  2667. // These can't have reference type in well-formed programs, but
  2668. // for internal consistency we do this anyway.
  2669. type = type.getNonReferenceType();
  2670. valueKind = VK_LValue;
  2671. break;
  2672. // Non-type template parameters are either l-values or r-values
  2673. // depending on the type.
  2674. case Decl::NonTypeTemplateParm: {
  2675. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2676. type = reftype->getPointeeType();
  2677. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2678. break;
  2679. }
  2680. // For non-references, we need to strip qualifiers just in case
  2681. // the template parameter was declared as 'const int' or whatever.
  2682. valueKind = VK_RValue;
  2683. type = type.getUnqualifiedType();
  2684. break;
  2685. }
  2686. case Decl::Var:
  2687. case Decl::VarTemplateSpecialization:
  2688. case Decl::VarTemplatePartialSpecialization:
  2689. case Decl::Decomposition:
  2690. case Decl::OMPCapturedExpr:
  2691. // In C, "extern void blah;" is valid and is an r-value.
  2692. if (!getLangOpts().CPlusPlus &&
  2693. !type.hasQualifiers() &&
  2694. type->isVoidType()) {
  2695. valueKind = VK_RValue;
  2696. break;
  2697. }
  2698. LLVM_FALLTHROUGH;
  2699. case Decl::ImplicitParam:
  2700. case Decl::ParmVar: {
  2701. // These are always l-values.
  2702. valueKind = VK_LValue;
  2703. type = type.getNonReferenceType();
  2704. // FIXME: Does the addition of const really only apply in
  2705. // potentially-evaluated contexts? Since the variable isn't actually
  2706. // captured in an unevaluated context, it seems that the answer is no.
  2707. if (!isUnevaluatedContext()) {
  2708. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2709. if (!CapturedType.isNull())
  2710. type = CapturedType;
  2711. }
  2712. break;
  2713. }
  2714. case Decl::Binding: {
  2715. // These are always lvalues.
  2716. valueKind = VK_LValue;
  2717. type = type.getNonReferenceType();
  2718. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2719. // decides how that's supposed to work.
  2720. auto *BD = cast<BindingDecl>(VD);
  2721. if (BD->getDeclContext() != CurContext) {
  2722. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2723. if (DD && DD->hasLocalStorage())
  2724. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2725. }
  2726. break;
  2727. }
  2728. case Decl::Function: {
  2729. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2730. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2731. type = Context.BuiltinFnTy;
  2732. valueKind = VK_RValue;
  2733. break;
  2734. }
  2735. }
  2736. const FunctionType *fty = type->castAs<FunctionType>();
  2737. // If we're referring to a function with an __unknown_anytype
  2738. // result type, make the entire expression __unknown_anytype.
  2739. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2740. type = Context.UnknownAnyTy;
  2741. valueKind = VK_RValue;
  2742. break;
  2743. }
  2744. // Functions are l-values in C++.
  2745. if (getLangOpts().CPlusPlus) {
  2746. valueKind = VK_LValue;
  2747. break;
  2748. }
  2749. // C99 DR 316 says that, if a function type comes from a
  2750. // function definition (without a prototype), that type is only
  2751. // used for checking compatibility. Therefore, when referencing
  2752. // the function, we pretend that we don't have the full function
  2753. // type.
  2754. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2755. isa<FunctionProtoType>(fty))
  2756. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2757. fty->getExtInfo());
  2758. // Functions are r-values in C.
  2759. valueKind = VK_RValue;
  2760. break;
  2761. }
  2762. case Decl::CXXDeductionGuide:
  2763. llvm_unreachable("building reference to deduction guide");
  2764. case Decl::MSProperty:
  2765. valueKind = VK_LValue;
  2766. break;
  2767. case Decl::CXXMethod:
  2768. // If we're referring to a method with an __unknown_anytype
  2769. // result type, make the entire expression __unknown_anytype.
  2770. // This should only be possible with a type written directly.
  2771. if (const FunctionProtoType *proto
  2772. = dyn_cast<FunctionProtoType>(VD->getType()))
  2773. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2774. type = Context.UnknownAnyTy;
  2775. valueKind = VK_RValue;
  2776. break;
  2777. }
  2778. // C++ methods are l-values if static, r-values if non-static.
  2779. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2780. valueKind = VK_LValue;
  2781. break;
  2782. }
  2783. LLVM_FALLTHROUGH;
  2784. case Decl::CXXConversion:
  2785. case Decl::CXXDestructor:
  2786. case Decl::CXXConstructor:
  2787. valueKind = VK_RValue;
  2788. break;
  2789. }
  2790. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2791. /*FIXME: TemplateKWLoc*/ SourceLocation(),
  2792. TemplateArgs);
  2793. }
  2794. }
  2795. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2796. SmallString<32> &Target) {
  2797. Target.resize(CharByteWidth * (Source.size() + 1));
  2798. char *ResultPtr = &Target[0];
  2799. const llvm::UTF8 *ErrorPtr;
  2800. bool success =
  2801. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2802. (void)success;
  2803. assert(success);
  2804. Target.resize(ResultPtr - &Target[0]);
  2805. }
  2806. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2807. PredefinedExpr::IdentKind IK) {
  2808. // Pick the current block, lambda, captured statement or function.
  2809. Decl *currentDecl = nullptr;
  2810. if (const BlockScopeInfo *BSI = getCurBlock())
  2811. currentDecl = BSI->TheDecl;
  2812. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2813. currentDecl = LSI->CallOperator;
  2814. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2815. currentDecl = CSI->TheCapturedDecl;
  2816. else
  2817. currentDecl = getCurFunctionOrMethodDecl();
  2818. if (!currentDecl) {
  2819. Diag(Loc, diag::ext_predef_outside_function);
  2820. currentDecl = Context.getTranslationUnitDecl();
  2821. }
  2822. QualType ResTy;
  2823. StringLiteral *SL = nullptr;
  2824. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2825. ResTy = Context.DependentTy;
  2826. else {
  2827. // Pre-defined identifiers are of type char[x], where x is the length of
  2828. // the string.
  2829. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2830. unsigned Length = Str.length();
  2831. llvm::APInt LengthI(32, Length + 1);
  2832. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2833. ResTy =
  2834. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2835. SmallString<32> RawChars;
  2836. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2837. Str, RawChars);
  2838. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  2839. ArrayType::Normal,
  2840. /*IndexTypeQuals*/ 0);
  2841. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2842. /*Pascal*/ false, ResTy, Loc);
  2843. } else {
  2844. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2845. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  2846. ArrayType::Normal,
  2847. /*IndexTypeQuals*/ 0);
  2848. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2849. /*Pascal*/ false, ResTy, Loc);
  2850. }
  2851. }
  2852. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2853. }
  2854. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2855. PredefinedExpr::IdentKind IK;
  2856. switch (Kind) {
  2857. default: llvm_unreachable("Unknown simple primary expr!");
  2858. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2859. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2860. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2861. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2862. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2863. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2864. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2865. }
  2866. return BuildPredefinedExpr(Loc, IK);
  2867. }
  2868. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2869. SmallString<16> CharBuffer;
  2870. bool Invalid = false;
  2871. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2872. if (Invalid)
  2873. return ExprError();
  2874. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2875. PP, Tok.getKind());
  2876. if (Literal.hadError())
  2877. return ExprError();
  2878. QualType Ty;
  2879. if (Literal.isWide())
  2880. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2881. else if (Literal.isUTF8() && getLangOpts().Char8)
  2882. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2883. else if (Literal.isUTF16())
  2884. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2885. else if (Literal.isUTF32())
  2886. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2887. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2888. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2889. else
  2890. Ty = Context.CharTy; // 'x' -> char in C++
  2891. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2892. if (Literal.isWide())
  2893. Kind = CharacterLiteral::Wide;
  2894. else if (Literal.isUTF16())
  2895. Kind = CharacterLiteral::UTF16;
  2896. else if (Literal.isUTF32())
  2897. Kind = CharacterLiteral::UTF32;
  2898. else if (Literal.isUTF8())
  2899. Kind = CharacterLiteral::UTF8;
  2900. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2901. Tok.getLocation());
  2902. if (Literal.getUDSuffix().empty())
  2903. return Lit;
  2904. // We're building a user-defined literal.
  2905. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2906. SourceLocation UDSuffixLoc =
  2907. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2908. // Make sure we're allowed user-defined literals here.
  2909. if (!UDLScope)
  2910. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2911. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2912. // operator "" X (ch)
  2913. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2914. Lit, Tok.getLocation());
  2915. }
  2916. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2917. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2918. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2919. Context.IntTy, Loc);
  2920. }
  2921. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2922. QualType Ty, SourceLocation Loc) {
  2923. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2924. using llvm::APFloat;
  2925. APFloat Val(Format);
  2926. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2927. // Overflow is always an error, but underflow is only an error if
  2928. // we underflowed to zero (APFloat reports denormals as underflow).
  2929. if ((result & APFloat::opOverflow) ||
  2930. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2931. unsigned diagnostic;
  2932. SmallString<20> buffer;
  2933. if (result & APFloat::opOverflow) {
  2934. diagnostic = diag::warn_float_overflow;
  2935. APFloat::getLargest(Format).toString(buffer);
  2936. } else {
  2937. diagnostic = diag::warn_float_underflow;
  2938. APFloat::getSmallest(Format).toString(buffer);
  2939. }
  2940. S.Diag(Loc, diagnostic)
  2941. << Ty
  2942. << StringRef(buffer.data(), buffer.size());
  2943. }
  2944. bool isExact = (result == APFloat::opOK);
  2945. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2946. }
  2947. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2948. assert(E && "Invalid expression");
  2949. if (E->isValueDependent())
  2950. return false;
  2951. QualType QT = E->getType();
  2952. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2953. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2954. return true;
  2955. }
  2956. llvm::APSInt ValueAPS;
  2957. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2958. if (R.isInvalid())
  2959. return true;
  2960. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2961. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2962. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2963. << ValueAPS.toString(10) << ValueIsPositive;
  2964. return true;
  2965. }
  2966. return false;
  2967. }
  2968. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2969. // Fast path for a single digit (which is quite common). A single digit
  2970. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2971. if (Tok.getLength() == 1) {
  2972. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2973. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2974. }
  2975. SmallString<128> SpellingBuffer;
  2976. // NumericLiteralParser wants to overread by one character. Add padding to
  2977. // the buffer in case the token is copied to the buffer. If getSpelling()
  2978. // returns a StringRef to the memory buffer, it should have a null char at
  2979. // the EOF, so it is also safe.
  2980. SpellingBuffer.resize(Tok.getLength() + 1);
  2981. // Get the spelling of the token, which eliminates trigraphs, etc.
  2982. bool Invalid = false;
  2983. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2984. if (Invalid)
  2985. return ExprError();
  2986. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2987. if (Literal.hadError)
  2988. return ExprError();
  2989. if (Literal.hasUDSuffix()) {
  2990. // We're building a user-defined literal.
  2991. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2992. SourceLocation UDSuffixLoc =
  2993. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2994. // Make sure we're allowed user-defined literals here.
  2995. if (!UDLScope)
  2996. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2997. QualType CookedTy;
  2998. if (Literal.isFloatingLiteral()) {
  2999. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  3000. // long double, the literal is treated as a call of the form
  3001. // operator "" X (f L)
  3002. CookedTy = Context.LongDoubleTy;
  3003. } else {
  3004. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  3005. // unsigned long long, the literal is treated as a call of the form
  3006. // operator "" X (n ULL)
  3007. CookedTy = Context.UnsignedLongLongTy;
  3008. }
  3009. DeclarationName OpName =
  3010. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  3011. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  3012. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  3013. SourceLocation TokLoc = Tok.getLocation();
  3014. // Perform literal operator lookup to determine if we're building a raw
  3015. // literal or a cooked one.
  3016. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  3017. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  3018. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3019. /*AllowStringTemplate*/ false,
  3020. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3021. case LOLR_ErrorNoDiagnostic:
  3022. // Lookup failure for imaginary constants isn't fatal, there's still the
  3023. // GNU extension producing _Complex types.
  3024. break;
  3025. case LOLR_Error:
  3026. return ExprError();
  3027. case LOLR_Cooked: {
  3028. Expr *Lit;
  3029. if (Literal.isFloatingLiteral()) {
  3030. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3031. } else {
  3032. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3033. if (Literal.GetIntegerValue(ResultVal))
  3034. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3035. << /* Unsigned */ 1;
  3036. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3037. Tok.getLocation());
  3038. }
  3039. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3040. }
  3041. case LOLR_Raw: {
  3042. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3043. // literal is treated as a call of the form
  3044. // operator "" X ("n")
  3045. unsigned Length = Literal.getUDSuffixOffset();
  3046. QualType StrTy = Context.getConstantArrayType(
  3047. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3048. llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
  3049. Expr *Lit = StringLiteral::Create(
  3050. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3051. /*Pascal*/false, StrTy, &TokLoc, 1);
  3052. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3053. }
  3054. case LOLR_Template: {
  3055. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3056. // template), L is treated as a call fo the form
  3057. // operator "" X <'c1', 'c2', ... 'ck'>()
  3058. // where n is the source character sequence c1 c2 ... ck.
  3059. TemplateArgumentListInfo ExplicitArgs;
  3060. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3061. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3062. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3063. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3064. Value = TokSpelling[I];
  3065. TemplateArgument Arg(Context, Value, Context.CharTy);
  3066. TemplateArgumentLocInfo ArgInfo;
  3067. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3068. }
  3069. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3070. &ExplicitArgs);
  3071. }
  3072. case LOLR_StringTemplate:
  3073. llvm_unreachable("unexpected literal operator lookup result");
  3074. }
  3075. }
  3076. Expr *Res;
  3077. if (Literal.isFixedPointLiteral()) {
  3078. QualType Ty;
  3079. if (Literal.isAccum) {
  3080. if (Literal.isHalf) {
  3081. Ty = Context.ShortAccumTy;
  3082. } else if (Literal.isLong) {
  3083. Ty = Context.LongAccumTy;
  3084. } else {
  3085. Ty = Context.AccumTy;
  3086. }
  3087. } else if (Literal.isFract) {
  3088. if (Literal.isHalf) {
  3089. Ty = Context.ShortFractTy;
  3090. } else if (Literal.isLong) {
  3091. Ty = Context.LongFractTy;
  3092. } else {
  3093. Ty = Context.FractTy;
  3094. }
  3095. }
  3096. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3097. bool isSigned = !Literal.isUnsigned;
  3098. unsigned scale = Context.getFixedPointScale(Ty);
  3099. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3100. llvm::APInt Val(bit_width, 0, isSigned);
  3101. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3102. bool ValIsZero = Val.isNullValue() && !Overflowed;
  3103. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3104. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3105. // Clause 6.4.4 - The value of a constant shall be in the range of
  3106. // representable values for its type, with exception for constants of a
  3107. // fract type with a value of exactly 1; such a constant shall denote
  3108. // the maximal value for the type.
  3109. --Val;
  3110. else if (Val.ugt(MaxVal) || Overflowed)
  3111. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3112. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3113. Tok.getLocation(), scale);
  3114. } else if (Literal.isFloatingLiteral()) {
  3115. QualType Ty;
  3116. if (Literal.isHalf){
  3117. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  3118. Ty = Context.HalfTy;
  3119. else {
  3120. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3121. return ExprError();
  3122. }
  3123. } else if (Literal.isFloat)
  3124. Ty = Context.FloatTy;
  3125. else if (Literal.isLong)
  3126. Ty = Context.LongDoubleTy;
  3127. else if (Literal.isFloat16)
  3128. Ty = Context.Float16Ty;
  3129. else if (Literal.isFloat128)
  3130. Ty = Context.Float128Ty;
  3131. else
  3132. Ty = Context.DoubleTy;
  3133. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3134. if (Ty == Context.DoubleTy) {
  3135. if (getLangOpts().SinglePrecisionConstants) {
  3136. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  3137. if (BTy->getKind() != BuiltinType::Float) {
  3138. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3139. }
  3140. } else if (getLangOpts().OpenCL &&
  3141. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  3142. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3143. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3144. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3145. }
  3146. }
  3147. } else if (!Literal.isIntegerLiteral()) {
  3148. return ExprError();
  3149. } else {
  3150. QualType Ty;
  3151. // 'long long' is a C99 or C++11 feature.
  3152. if (!getLangOpts().C99 && Literal.isLongLong) {
  3153. if (getLangOpts().CPlusPlus)
  3154. Diag(Tok.getLocation(),
  3155. getLangOpts().CPlusPlus11 ?
  3156. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3157. else
  3158. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3159. }
  3160. // Get the value in the widest-possible width.
  3161. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3162. llvm::APInt ResultVal(MaxWidth, 0);
  3163. if (Literal.GetIntegerValue(ResultVal)) {
  3164. // If this value didn't fit into uintmax_t, error and force to ull.
  3165. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3166. << /* Unsigned */ 1;
  3167. Ty = Context.UnsignedLongLongTy;
  3168. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3169. "long long is not intmax_t?");
  3170. } else {
  3171. // If this value fits into a ULL, try to figure out what else it fits into
  3172. // according to the rules of C99 6.4.4.1p5.
  3173. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3174. // be an unsigned int.
  3175. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3176. // Check from smallest to largest, picking the smallest type we can.
  3177. unsigned Width = 0;
  3178. // Microsoft specific integer suffixes are explicitly sized.
  3179. if (Literal.MicrosoftInteger) {
  3180. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3181. Width = 8;
  3182. Ty = Context.CharTy;
  3183. } else {
  3184. Width = Literal.MicrosoftInteger;
  3185. Ty = Context.getIntTypeForBitwidth(Width,
  3186. /*Signed=*/!Literal.isUnsigned);
  3187. }
  3188. }
  3189. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3190. // Are int/unsigned possibilities?
  3191. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3192. // Does it fit in a unsigned int?
  3193. if (ResultVal.isIntN(IntSize)) {
  3194. // Does it fit in a signed int?
  3195. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3196. Ty = Context.IntTy;
  3197. else if (AllowUnsigned)
  3198. Ty = Context.UnsignedIntTy;
  3199. Width = IntSize;
  3200. }
  3201. }
  3202. // Are long/unsigned long possibilities?
  3203. if (Ty.isNull() && !Literal.isLongLong) {
  3204. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3205. // Does it fit in a unsigned long?
  3206. if (ResultVal.isIntN(LongSize)) {
  3207. // Does it fit in a signed long?
  3208. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3209. Ty = Context.LongTy;
  3210. else if (AllowUnsigned)
  3211. Ty = Context.UnsignedLongTy;
  3212. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3213. // is compatible.
  3214. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3215. const unsigned LongLongSize =
  3216. Context.getTargetInfo().getLongLongWidth();
  3217. Diag(Tok.getLocation(),
  3218. getLangOpts().CPlusPlus
  3219. ? Literal.isLong
  3220. ? diag::warn_old_implicitly_unsigned_long_cxx
  3221. : /*C++98 UB*/ diag::
  3222. ext_old_implicitly_unsigned_long_cxx
  3223. : diag::warn_old_implicitly_unsigned_long)
  3224. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3225. : /*will be ill-formed*/ 1);
  3226. Ty = Context.UnsignedLongTy;
  3227. }
  3228. Width = LongSize;
  3229. }
  3230. }
  3231. // Check long long if needed.
  3232. if (Ty.isNull()) {
  3233. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3234. // Does it fit in a unsigned long long?
  3235. if (ResultVal.isIntN(LongLongSize)) {
  3236. // Does it fit in a signed long long?
  3237. // To be compatible with MSVC, hex integer literals ending with the
  3238. // LL or i64 suffix are always signed in Microsoft mode.
  3239. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3240. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3241. Ty = Context.LongLongTy;
  3242. else if (AllowUnsigned)
  3243. Ty = Context.UnsignedLongLongTy;
  3244. Width = LongLongSize;
  3245. }
  3246. }
  3247. // If we still couldn't decide a type, we probably have something that
  3248. // does not fit in a signed long long, but has no U suffix.
  3249. if (Ty.isNull()) {
  3250. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3251. Ty = Context.UnsignedLongLongTy;
  3252. Width = Context.getTargetInfo().getLongLongWidth();
  3253. }
  3254. if (ResultVal.getBitWidth() != Width)
  3255. ResultVal = ResultVal.trunc(Width);
  3256. }
  3257. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3258. }
  3259. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3260. if (Literal.isImaginary) {
  3261. Res = new (Context) ImaginaryLiteral(Res,
  3262. Context.getComplexType(Res->getType()));
  3263. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3264. }
  3265. return Res;
  3266. }
  3267. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3268. assert(E && "ActOnParenExpr() missing expr");
  3269. return new (Context) ParenExpr(L, R, E);
  3270. }
  3271. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3272. SourceLocation Loc,
  3273. SourceRange ArgRange) {
  3274. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3275. // scalar or vector data type argument..."
  3276. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3277. // type (C99 6.2.5p18) or void.
  3278. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3279. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3280. << T << ArgRange;
  3281. return true;
  3282. }
  3283. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3284. "Scalar types should always be complete");
  3285. return false;
  3286. }
  3287. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3288. SourceLocation Loc,
  3289. SourceRange ArgRange,
  3290. UnaryExprOrTypeTrait TraitKind) {
  3291. // Invalid types must be hard errors for SFINAE in C++.
  3292. if (S.LangOpts.CPlusPlus)
  3293. return true;
  3294. // C99 6.5.3.4p1:
  3295. if (T->isFunctionType() &&
  3296. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3297. TraitKind == UETT_PreferredAlignOf)) {
  3298. // sizeof(function)/alignof(function) is allowed as an extension.
  3299. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3300. << TraitKind << ArgRange;
  3301. return false;
  3302. }
  3303. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3304. // this is an error (OpenCL v1.1 s6.3.k)
  3305. if (T->isVoidType()) {
  3306. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3307. : diag::ext_sizeof_alignof_void_type;
  3308. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3309. return false;
  3310. }
  3311. return true;
  3312. }
  3313. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3314. SourceLocation Loc,
  3315. SourceRange ArgRange,
  3316. UnaryExprOrTypeTrait TraitKind) {
  3317. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3318. // runtime doesn't allow it.
  3319. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3320. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3321. << T << (TraitKind == UETT_SizeOf)
  3322. << ArgRange;
  3323. return true;
  3324. }
  3325. return false;
  3326. }
  3327. /// Check whether E is a pointer from a decayed array type (the decayed
  3328. /// pointer type is equal to T) and emit a warning if it is.
  3329. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3330. Expr *E) {
  3331. // Don't warn if the operation changed the type.
  3332. if (T != E->getType())
  3333. return;
  3334. // Now look for array decays.
  3335. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3336. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3337. return;
  3338. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3339. << ICE->getType()
  3340. << ICE->getSubExpr()->getType();
  3341. }
  3342. /// Check the constraints on expression operands to unary type expression
  3343. /// and type traits.
  3344. ///
  3345. /// Completes any types necessary and validates the constraints on the operand
  3346. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3347. /// the expression as it completes the type for that expression through template
  3348. /// instantiation, etc.
  3349. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3350. UnaryExprOrTypeTrait ExprKind) {
  3351. QualType ExprTy = E->getType();
  3352. assert(!ExprTy->isReferenceType());
  3353. bool IsUnevaluatedOperand =
  3354. (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3355. ExprKind == UETT_PreferredAlignOf);
  3356. if (IsUnevaluatedOperand) {
  3357. ExprResult Result = CheckUnevaluatedOperand(E);
  3358. if (Result.isInvalid())
  3359. return true;
  3360. E = Result.get();
  3361. }
  3362. if (ExprKind == UETT_VecStep)
  3363. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3364. E->getSourceRange());
  3365. // Whitelist some types as extensions
  3366. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3367. E->getSourceRange(), ExprKind))
  3368. return false;
  3369. // 'alignof' applied to an expression only requires the base element type of
  3370. // the expression to be complete. 'sizeof' requires the expression's type to
  3371. // be complete (and will attempt to complete it if it's an array of unknown
  3372. // bound).
  3373. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3374. if (RequireCompleteType(E->getExprLoc(),
  3375. Context.getBaseElementType(E->getType()),
  3376. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3377. E->getSourceRange()))
  3378. return true;
  3379. } else {
  3380. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3381. ExprKind, E->getSourceRange()))
  3382. return true;
  3383. }
  3384. // Completing the expression's type may have changed it.
  3385. ExprTy = E->getType();
  3386. assert(!ExprTy->isReferenceType());
  3387. if (ExprTy->isFunctionType()) {
  3388. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3389. << ExprKind << E->getSourceRange();
  3390. return true;
  3391. }
  3392. // The operand for sizeof and alignof is in an unevaluated expression context,
  3393. // so side effects could result in unintended consequences.
  3394. if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
  3395. E->HasSideEffects(Context, false))
  3396. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3397. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3398. E->getSourceRange(), ExprKind))
  3399. return true;
  3400. if (ExprKind == UETT_SizeOf) {
  3401. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3402. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3403. QualType OType = PVD->getOriginalType();
  3404. QualType Type = PVD->getType();
  3405. if (Type->isPointerType() && OType->isArrayType()) {
  3406. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3407. << Type << OType;
  3408. Diag(PVD->getLocation(), diag::note_declared_at);
  3409. }
  3410. }
  3411. }
  3412. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3413. // decays into a pointer and returns an unintended result. This is most
  3414. // likely a typo for "sizeof(array) op x".
  3415. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3416. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3417. BO->getLHS());
  3418. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3419. BO->getRHS());
  3420. }
  3421. }
  3422. return false;
  3423. }
  3424. /// Check the constraints on operands to unary expression and type
  3425. /// traits.
  3426. ///
  3427. /// This will complete any types necessary, and validate the various constraints
  3428. /// on those operands.
  3429. ///
  3430. /// The UsualUnaryConversions() function is *not* called by this routine.
  3431. /// C99 6.3.2.1p[2-4] all state:
  3432. /// Except when it is the operand of the sizeof operator ...
  3433. ///
  3434. /// C++ [expr.sizeof]p4
  3435. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3436. /// standard conversions are not applied to the operand of sizeof.
  3437. ///
  3438. /// This policy is followed for all of the unary trait expressions.
  3439. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3440. SourceLocation OpLoc,
  3441. SourceRange ExprRange,
  3442. UnaryExprOrTypeTrait ExprKind) {
  3443. if (ExprType->isDependentType())
  3444. return false;
  3445. // C++ [expr.sizeof]p2:
  3446. // When applied to a reference or a reference type, the result
  3447. // is the size of the referenced type.
  3448. // C++11 [expr.alignof]p3:
  3449. // When alignof is applied to a reference type, the result
  3450. // shall be the alignment of the referenced type.
  3451. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3452. ExprType = Ref->getPointeeType();
  3453. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3454. // When alignof or _Alignof is applied to an array type, the result
  3455. // is the alignment of the element type.
  3456. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3457. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3458. ExprType = Context.getBaseElementType(ExprType);
  3459. if (ExprKind == UETT_VecStep)
  3460. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3461. // Whitelist some types as extensions
  3462. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3463. ExprKind))
  3464. return false;
  3465. if (RequireCompleteType(OpLoc, ExprType,
  3466. diag::err_sizeof_alignof_incomplete_type,
  3467. ExprKind, ExprRange))
  3468. return true;
  3469. if (ExprType->isFunctionType()) {
  3470. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3471. << ExprKind << ExprRange;
  3472. return true;
  3473. }
  3474. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3475. ExprKind))
  3476. return true;
  3477. return false;
  3478. }
  3479. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3480. // Cannot know anything else if the expression is dependent.
  3481. if (E->isTypeDependent())
  3482. return false;
  3483. if (E->getObjectKind() == OK_BitField) {
  3484. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3485. << 1 << E->getSourceRange();
  3486. return true;
  3487. }
  3488. ValueDecl *D = nullptr;
  3489. Expr *Inner = E->IgnoreParens();
  3490. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
  3491. D = DRE->getDecl();
  3492. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
  3493. D = ME->getMemberDecl();
  3494. }
  3495. // If it's a field, require the containing struct to have a
  3496. // complete definition so that we can compute the layout.
  3497. //
  3498. // This can happen in C++11 onwards, either by naming the member
  3499. // in a way that is not transformed into a member access expression
  3500. // (in an unevaluated operand, for instance), or by naming the member
  3501. // in a trailing-return-type.
  3502. //
  3503. // For the record, since __alignof__ on expressions is a GCC
  3504. // extension, GCC seems to permit this but always gives the
  3505. // nonsensical answer 0.
  3506. //
  3507. // We don't really need the layout here --- we could instead just
  3508. // directly check for all the appropriate alignment-lowing
  3509. // attributes --- but that would require duplicating a lot of
  3510. // logic that just isn't worth duplicating for such a marginal
  3511. // use-case.
  3512. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3513. // Fast path this check, since we at least know the record has a
  3514. // definition if we can find a member of it.
  3515. if (!FD->getParent()->isCompleteDefinition()) {
  3516. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3517. << E->getSourceRange();
  3518. return true;
  3519. }
  3520. // Otherwise, if it's a field, and the field doesn't have
  3521. // reference type, then it must have a complete type (or be a
  3522. // flexible array member, which we explicitly want to
  3523. // white-list anyway), which makes the following checks trivial.
  3524. if (!FD->getType()->isReferenceType())
  3525. return false;
  3526. }
  3527. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3528. }
  3529. bool Sema::CheckVecStepExpr(Expr *E) {
  3530. E = E->IgnoreParens();
  3531. // Cannot know anything else if the expression is dependent.
  3532. if (E->isTypeDependent())
  3533. return false;
  3534. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3535. }
  3536. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3537. CapturingScopeInfo *CSI) {
  3538. assert(T->isVariablyModifiedType());
  3539. assert(CSI != nullptr);
  3540. // We're going to walk down into the type and look for VLA expressions.
  3541. do {
  3542. const Type *Ty = T.getTypePtr();
  3543. switch (Ty->getTypeClass()) {
  3544. #define TYPE(Class, Base)
  3545. #define ABSTRACT_TYPE(Class, Base)
  3546. #define NON_CANONICAL_TYPE(Class, Base)
  3547. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3548. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3549. #include "clang/AST/TypeNodes.inc"
  3550. T = QualType();
  3551. break;
  3552. // These types are never variably-modified.
  3553. case Type::Builtin:
  3554. case Type::Complex:
  3555. case Type::Vector:
  3556. case Type::ExtVector:
  3557. case Type::Record:
  3558. case Type::Enum:
  3559. case Type::Elaborated:
  3560. case Type::TemplateSpecialization:
  3561. case Type::ObjCObject:
  3562. case Type::ObjCInterface:
  3563. case Type::ObjCObjectPointer:
  3564. case Type::ObjCTypeParam:
  3565. case Type::Pipe:
  3566. llvm_unreachable("type class is never variably-modified!");
  3567. case Type::Adjusted:
  3568. T = cast<AdjustedType>(Ty)->getOriginalType();
  3569. break;
  3570. case Type::Decayed:
  3571. T = cast<DecayedType>(Ty)->getPointeeType();
  3572. break;
  3573. case Type::Pointer:
  3574. T = cast<PointerType>(Ty)->getPointeeType();
  3575. break;
  3576. case Type::BlockPointer:
  3577. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3578. break;
  3579. case Type::LValueReference:
  3580. case Type::RValueReference:
  3581. T = cast<ReferenceType>(Ty)->getPointeeType();
  3582. break;
  3583. case Type::MemberPointer:
  3584. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3585. break;
  3586. case Type::ConstantArray:
  3587. case Type::IncompleteArray:
  3588. // Losing element qualification here is fine.
  3589. T = cast<ArrayType>(Ty)->getElementType();
  3590. break;
  3591. case Type::VariableArray: {
  3592. // Losing element qualification here is fine.
  3593. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3594. // Unknown size indication requires no size computation.
  3595. // Otherwise, evaluate and record it.
  3596. auto Size = VAT->getSizeExpr();
  3597. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3598. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3599. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3600. T = VAT->getElementType();
  3601. break;
  3602. }
  3603. case Type::FunctionProto:
  3604. case Type::FunctionNoProto:
  3605. T = cast<FunctionType>(Ty)->getReturnType();
  3606. break;
  3607. case Type::Paren:
  3608. case Type::TypeOf:
  3609. case Type::UnaryTransform:
  3610. case Type::Attributed:
  3611. case Type::SubstTemplateTypeParm:
  3612. case Type::PackExpansion:
  3613. case Type::MacroQualified:
  3614. // Keep walking after single level desugaring.
  3615. T = T.getSingleStepDesugaredType(Context);
  3616. break;
  3617. case Type::Typedef:
  3618. T = cast<TypedefType>(Ty)->desugar();
  3619. break;
  3620. case Type::Decltype:
  3621. T = cast<DecltypeType>(Ty)->desugar();
  3622. break;
  3623. case Type::Auto:
  3624. case Type::DeducedTemplateSpecialization:
  3625. T = cast<DeducedType>(Ty)->getDeducedType();
  3626. break;
  3627. case Type::TypeOfExpr:
  3628. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3629. break;
  3630. case Type::Atomic:
  3631. T = cast<AtomicType>(Ty)->getValueType();
  3632. break;
  3633. }
  3634. } while (!T.isNull() && T->isVariablyModifiedType());
  3635. }
  3636. /// Build a sizeof or alignof expression given a type operand.
  3637. ExprResult
  3638. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3639. SourceLocation OpLoc,
  3640. UnaryExprOrTypeTrait ExprKind,
  3641. SourceRange R) {
  3642. if (!TInfo)
  3643. return ExprError();
  3644. QualType T = TInfo->getType();
  3645. if (!T->isDependentType() &&
  3646. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3647. return ExprError();
  3648. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3649. if (auto *TT = T->getAs<TypedefType>()) {
  3650. for (auto I = FunctionScopes.rbegin(),
  3651. E = std::prev(FunctionScopes.rend());
  3652. I != E; ++I) {
  3653. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3654. if (CSI == nullptr)
  3655. break;
  3656. DeclContext *DC = nullptr;
  3657. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3658. DC = LSI->CallOperator;
  3659. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3660. DC = CRSI->TheCapturedDecl;
  3661. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3662. DC = BSI->TheDecl;
  3663. if (DC) {
  3664. if (DC->containsDecl(TT->getDecl()))
  3665. break;
  3666. captureVariablyModifiedType(Context, T, CSI);
  3667. }
  3668. }
  3669. }
  3670. }
  3671. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3672. return new (Context) UnaryExprOrTypeTraitExpr(
  3673. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3674. }
  3675. /// Build a sizeof or alignof expression given an expression
  3676. /// operand.
  3677. ExprResult
  3678. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3679. UnaryExprOrTypeTrait ExprKind) {
  3680. ExprResult PE = CheckPlaceholderExpr(E);
  3681. if (PE.isInvalid())
  3682. return ExprError();
  3683. E = PE.get();
  3684. // Verify that the operand is valid.
  3685. bool isInvalid = false;
  3686. if (E->isTypeDependent()) {
  3687. // Delay type-checking for type-dependent expressions.
  3688. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3689. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3690. } else if (ExprKind == UETT_VecStep) {
  3691. isInvalid = CheckVecStepExpr(E);
  3692. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3693. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3694. isInvalid = true;
  3695. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3696. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3697. isInvalid = true;
  3698. } else {
  3699. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3700. }
  3701. if (isInvalid)
  3702. return ExprError();
  3703. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3704. PE = TransformToPotentiallyEvaluated(E);
  3705. if (PE.isInvalid()) return ExprError();
  3706. E = PE.get();
  3707. }
  3708. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3709. return new (Context) UnaryExprOrTypeTraitExpr(
  3710. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3711. }
  3712. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3713. /// expr and the same for @c alignof and @c __alignof
  3714. /// Note that the ArgRange is invalid if isType is false.
  3715. ExprResult
  3716. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3717. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3718. void *TyOrEx, SourceRange ArgRange) {
  3719. // If error parsing type, ignore.
  3720. if (!TyOrEx) return ExprError();
  3721. if (IsType) {
  3722. TypeSourceInfo *TInfo;
  3723. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3724. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3725. }
  3726. Expr *ArgEx = (Expr *)TyOrEx;
  3727. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3728. return Result;
  3729. }
  3730. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3731. bool IsReal) {
  3732. if (V.get()->isTypeDependent())
  3733. return S.Context.DependentTy;
  3734. // _Real and _Imag are only l-values for normal l-values.
  3735. if (V.get()->getObjectKind() != OK_Ordinary) {
  3736. V = S.DefaultLvalueConversion(V.get());
  3737. if (V.isInvalid())
  3738. return QualType();
  3739. }
  3740. // These operators return the element type of a complex type.
  3741. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3742. return CT->getElementType();
  3743. // Otherwise they pass through real integer and floating point types here.
  3744. if (V.get()->getType()->isArithmeticType())
  3745. return V.get()->getType();
  3746. // Test for placeholders.
  3747. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3748. if (PR.isInvalid()) return QualType();
  3749. if (PR.get() != V.get()) {
  3750. V = PR;
  3751. return CheckRealImagOperand(S, V, Loc, IsReal);
  3752. }
  3753. // Reject anything else.
  3754. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3755. << (IsReal ? "__real" : "__imag");
  3756. return QualType();
  3757. }
  3758. ExprResult
  3759. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3760. tok::TokenKind Kind, Expr *Input) {
  3761. UnaryOperatorKind Opc;
  3762. switch (Kind) {
  3763. default: llvm_unreachable("Unknown unary op!");
  3764. case tok::plusplus: Opc = UO_PostInc; break;
  3765. case tok::minusminus: Opc = UO_PostDec; break;
  3766. }
  3767. // Since this might is a postfix expression, get rid of ParenListExprs.
  3768. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3769. if (Result.isInvalid()) return ExprError();
  3770. Input = Result.get();
  3771. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3772. }
  3773. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3774. ///
  3775. /// \return true on error
  3776. static bool checkArithmeticOnObjCPointer(Sema &S,
  3777. SourceLocation opLoc,
  3778. Expr *op) {
  3779. assert(op->getType()->isObjCObjectPointerType());
  3780. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3781. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3782. return false;
  3783. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3784. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3785. << op->getSourceRange();
  3786. return true;
  3787. }
  3788. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3789. auto *BaseNoParens = Base->IgnoreParens();
  3790. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3791. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3792. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3793. }
  3794. ExprResult
  3795. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3796. Expr *idx, SourceLocation rbLoc) {
  3797. if (base && !base->getType().isNull() &&
  3798. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3799. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3800. /*Length=*/nullptr, rbLoc);
  3801. // Since this might be a postfix expression, get rid of ParenListExprs.
  3802. if (isa<ParenListExpr>(base)) {
  3803. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3804. if (result.isInvalid()) return ExprError();
  3805. base = result.get();
  3806. }
  3807. // A comma-expression as the index is deprecated in C++2a onwards.
  3808. if (getLangOpts().CPlusPlus2a &&
  3809. ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
  3810. (isa<CXXOperatorCallExpr>(idx) &&
  3811. cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
  3812. Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
  3813. << SourceRange(base->getBeginLoc(), rbLoc);
  3814. }
  3815. // Handle any non-overload placeholder types in the base and index
  3816. // expressions. We can't handle overloads here because the other
  3817. // operand might be an overloadable type, in which case the overload
  3818. // resolution for the operator overload should get the first crack
  3819. // at the overload.
  3820. bool IsMSPropertySubscript = false;
  3821. if (base->getType()->isNonOverloadPlaceholderType()) {
  3822. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3823. if (!IsMSPropertySubscript) {
  3824. ExprResult result = CheckPlaceholderExpr(base);
  3825. if (result.isInvalid())
  3826. return ExprError();
  3827. base = result.get();
  3828. }
  3829. }
  3830. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3831. ExprResult result = CheckPlaceholderExpr(idx);
  3832. if (result.isInvalid()) return ExprError();
  3833. idx = result.get();
  3834. }
  3835. // Build an unanalyzed expression if either operand is type-dependent.
  3836. if (getLangOpts().CPlusPlus &&
  3837. (base->isTypeDependent() || idx->isTypeDependent())) {
  3838. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3839. VK_LValue, OK_Ordinary, rbLoc);
  3840. }
  3841. // MSDN, property (C++)
  3842. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3843. // This attribute can also be used in the declaration of an empty array in a
  3844. // class or structure definition. For example:
  3845. // __declspec(property(get=GetX, put=PutX)) int x[];
  3846. // The above statement indicates that x[] can be used with one or more array
  3847. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3848. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3849. if (IsMSPropertySubscript) {
  3850. // Build MS property subscript expression if base is MS property reference
  3851. // or MS property subscript.
  3852. return new (Context) MSPropertySubscriptExpr(
  3853. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3854. }
  3855. // Use C++ overloaded-operator rules if either operand has record
  3856. // type. The spec says to do this if either type is *overloadable*,
  3857. // but enum types can't declare subscript operators or conversion
  3858. // operators, so there's nothing interesting for overload resolution
  3859. // to do if there aren't any record types involved.
  3860. //
  3861. // ObjC pointers have their own subscripting logic that is not tied
  3862. // to overload resolution and so should not take this path.
  3863. if (getLangOpts().CPlusPlus &&
  3864. (base->getType()->isRecordType() ||
  3865. (!base->getType()->isObjCObjectPointerType() &&
  3866. idx->getType()->isRecordType()))) {
  3867. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3868. }
  3869. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3870. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  3871. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  3872. return Res;
  3873. }
  3874. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  3875. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3876. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  3877. // For expressions like `&(*s).b`, the base is recorded and what should be
  3878. // checked.
  3879. const MemberExpr *Member = nullptr;
  3880. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  3881. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  3882. LastRecord.PossibleDerefs.erase(StrippedExpr);
  3883. }
  3884. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  3885. QualType ResultTy = E->getType();
  3886. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3887. // Bail if the element is an array since it is not memory access.
  3888. if (isa<ArrayType>(ResultTy))
  3889. return;
  3890. if (ResultTy->hasAttr(attr::NoDeref)) {
  3891. LastRecord.PossibleDerefs.insert(E);
  3892. return;
  3893. }
  3894. // Check if the base type is a pointer to a member access of a struct
  3895. // marked with noderef.
  3896. const Expr *Base = E->getBase();
  3897. QualType BaseTy = Base->getType();
  3898. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  3899. // Not a pointer access
  3900. return;
  3901. const MemberExpr *Member = nullptr;
  3902. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  3903. Member->isArrow())
  3904. Base = Member->getBase();
  3905. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  3906. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  3907. LastRecord.PossibleDerefs.insert(E);
  3908. }
  3909. }
  3910. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3911. Expr *LowerBound,
  3912. SourceLocation ColonLoc, Expr *Length,
  3913. SourceLocation RBLoc) {
  3914. if (Base->getType()->isPlaceholderType() &&
  3915. !Base->getType()->isSpecificPlaceholderType(
  3916. BuiltinType::OMPArraySection)) {
  3917. ExprResult Result = CheckPlaceholderExpr(Base);
  3918. if (Result.isInvalid())
  3919. return ExprError();
  3920. Base = Result.get();
  3921. }
  3922. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3923. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3924. if (Result.isInvalid())
  3925. return ExprError();
  3926. Result = DefaultLvalueConversion(Result.get());
  3927. if (Result.isInvalid())
  3928. return ExprError();
  3929. LowerBound = Result.get();
  3930. }
  3931. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3932. ExprResult Result = CheckPlaceholderExpr(Length);
  3933. if (Result.isInvalid())
  3934. return ExprError();
  3935. Result = DefaultLvalueConversion(Result.get());
  3936. if (Result.isInvalid())
  3937. return ExprError();
  3938. Length = Result.get();
  3939. }
  3940. // Build an unanalyzed expression if either operand is type-dependent.
  3941. if (Base->isTypeDependent() ||
  3942. (LowerBound &&
  3943. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3944. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3945. return new (Context)
  3946. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3947. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3948. }
  3949. // Perform default conversions.
  3950. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3951. QualType ResultTy;
  3952. if (OriginalTy->isAnyPointerType()) {
  3953. ResultTy = OriginalTy->getPointeeType();
  3954. } else if (OriginalTy->isArrayType()) {
  3955. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3956. } else {
  3957. return ExprError(
  3958. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3959. << Base->getSourceRange());
  3960. }
  3961. // C99 6.5.2.1p1
  3962. if (LowerBound) {
  3963. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3964. LowerBound);
  3965. if (Res.isInvalid())
  3966. return ExprError(Diag(LowerBound->getExprLoc(),
  3967. diag::err_omp_typecheck_section_not_integer)
  3968. << 0 << LowerBound->getSourceRange());
  3969. LowerBound = Res.get();
  3970. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3971. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3972. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3973. << 0 << LowerBound->getSourceRange();
  3974. }
  3975. if (Length) {
  3976. auto Res =
  3977. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3978. if (Res.isInvalid())
  3979. return ExprError(Diag(Length->getExprLoc(),
  3980. diag::err_omp_typecheck_section_not_integer)
  3981. << 1 << Length->getSourceRange());
  3982. Length = Res.get();
  3983. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3984. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3985. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3986. << 1 << Length->getSourceRange();
  3987. }
  3988. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3989. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3990. // type. Note that functions are not objects, and that (in C99 parlance)
  3991. // incomplete types are not object types.
  3992. if (ResultTy->isFunctionType()) {
  3993. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3994. << ResultTy << Base->getSourceRange();
  3995. return ExprError();
  3996. }
  3997. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3998. diag::err_omp_section_incomplete_type, Base))
  3999. return ExprError();
  4000. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  4001. Expr::EvalResult Result;
  4002. if (LowerBound->EvaluateAsInt(Result, Context)) {
  4003. // OpenMP 4.5, [2.4 Array Sections]
  4004. // The array section must be a subset of the original array.
  4005. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  4006. if (LowerBoundValue.isNegative()) {
  4007. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  4008. << LowerBound->getSourceRange();
  4009. return ExprError();
  4010. }
  4011. }
  4012. }
  4013. if (Length) {
  4014. Expr::EvalResult Result;
  4015. if (Length->EvaluateAsInt(Result, Context)) {
  4016. // OpenMP 4.5, [2.4 Array Sections]
  4017. // The length must evaluate to non-negative integers.
  4018. llvm::APSInt LengthValue = Result.Val.getInt();
  4019. if (LengthValue.isNegative()) {
  4020. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  4021. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  4022. << Length->getSourceRange();
  4023. return ExprError();
  4024. }
  4025. }
  4026. } else if (ColonLoc.isValid() &&
  4027. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4028. !OriginalTy->isVariableArrayType()))) {
  4029. // OpenMP 4.5, [2.4 Array Sections]
  4030. // When the size of the array dimension is not known, the length must be
  4031. // specified explicitly.
  4032. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  4033. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4034. return ExprError();
  4035. }
  4036. if (!Base->getType()->isSpecificPlaceholderType(
  4037. BuiltinType::OMPArraySection)) {
  4038. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4039. if (Result.isInvalid())
  4040. return ExprError();
  4041. Base = Result.get();
  4042. }
  4043. return new (Context)
  4044. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  4045. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  4046. }
  4047. ExprResult
  4048. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4049. Expr *Idx, SourceLocation RLoc) {
  4050. Expr *LHSExp = Base;
  4051. Expr *RHSExp = Idx;
  4052. ExprValueKind VK = VK_LValue;
  4053. ExprObjectKind OK = OK_Ordinary;
  4054. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4055. // a non-lvalue array, and an lvalue otherwise.
  4056. if (getLangOpts().CPlusPlus11) {
  4057. for (auto *Op : {LHSExp, RHSExp}) {
  4058. Op = Op->IgnoreImplicit();
  4059. if (Op->getType()->isArrayType() && !Op->isLValue())
  4060. VK = VK_XValue;
  4061. }
  4062. }
  4063. // Perform default conversions.
  4064. if (!LHSExp->getType()->getAs<VectorType>()) {
  4065. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4066. if (Result.isInvalid())
  4067. return ExprError();
  4068. LHSExp = Result.get();
  4069. }
  4070. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4071. if (Result.isInvalid())
  4072. return ExprError();
  4073. RHSExp = Result.get();
  4074. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4075. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4076. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4077. // in the subscript position. As a result, we need to derive the array base
  4078. // and index from the expression types.
  4079. Expr *BaseExpr, *IndexExpr;
  4080. QualType ResultType;
  4081. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4082. BaseExpr = LHSExp;
  4083. IndexExpr = RHSExp;
  4084. ResultType = Context.DependentTy;
  4085. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4086. BaseExpr = LHSExp;
  4087. IndexExpr = RHSExp;
  4088. ResultType = PTy->getPointeeType();
  4089. } else if (const ObjCObjectPointerType *PTy =
  4090. LHSTy->getAs<ObjCObjectPointerType>()) {
  4091. BaseExpr = LHSExp;
  4092. IndexExpr = RHSExp;
  4093. // Use custom logic if this should be the pseudo-object subscript
  4094. // expression.
  4095. if (!LangOpts.isSubscriptPointerArithmetic())
  4096. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4097. nullptr);
  4098. ResultType = PTy->getPointeeType();
  4099. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4100. // Handle the uncommon case of "123[Ptr]".
  4101. BaseExpr = RHSExp;
  4102. IndexExpr = LHSExp;
  4103. ResultType = PTy->getPointeeType();
  4104. } else if (const ObjCObjectPointerType *PTy =
  4105. RHSTy->getAs<ObjCObjectPointerType>()) {
  4106. // Handle the uncommon case of "123[Ptr]".
  4107. BaseExpr = RHSExp;
  4108. IndexExpr = LHSExp;
  4109. ResultType = PTy->getPointeeType();
  4110. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4111. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4112. << ResultType << BaseExpr->getSourceRange();
  4113. return ExprError();
  4114. }
  4115. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4116. BaseExpr = LHSExp; // vectors: V[123]
  4117. IndexExpr = RHSExp;
  4118. // We apply C++ DR1213 to vector subscripting too.
  4119. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  4120. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4121. if (Materialized.isInvalid())
  4122. return ExprError();
  4123. LHSExp = Materialized.get();
  4124. }
  4125. VK = LHSExp->getValueKind();
  4126. if (VK != VK_RValue)
  4127. OK = OK_VectorComponent;
  4128. ResultType = VTy->getElementType();
  4129. QualType BaseType = BaseExpr->getType();
  4130. Qualifiers BaseQuals = BaseType.getQualifiers();
  4131. Qualifiers MemberQuals = ResultType.getQualifiers();
  4132. Qualifiers Combined = BaseQuals + MemberQuals;
  4133. if (Combined != MemberQuals)
  4134. ResultType = Context.getQualifiedType(ResultType, Combined);
  4135. } else if (LHSTy->isArrayType()) {
  4136. // If we see an array that wasn't promoted by
  4137. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4138. // wasn't promoted because of the C90 rule that doesn't
  4139. // allow promoting non-lvalue arrays. Warn, then
  4140. // force the promotion here.
  4141. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4142. << LHSExp->getSourceRange();
  4143. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4144. CK_ArrayToPointerDecay).get();
  4145. LHSTy = LHSExp->getType();
  4146. BaseExpr = LHSExp;
  4147. IndexExpr = RHSExp;
  4148. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  4149. } else if (RHSTy->isArrayType()) {
  4150. // Same as previous, except for 123[f().a] case
  4151. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4152. << RHSExp->getSourceRange();
  4153. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4154. CK_ArrayToPointerDecay).get();
  4155. RHSTy = RHSExp->getType();
  4156. BaseExpr = RHSExp;
  4157. IndexExpr = LHSExp;
  4158. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  4159. } else {
  4160. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4161. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4162. }
  4163. // C99 6.5.2.1p1
  4164. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4165. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4166. << IndexExpr->getSourceRange());
  4167. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4168. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4169. && !IndexExpr->isTypeDependent())
  4170. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4171. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4172. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4173. // type. Note that Functions are not objects, and that (in C99 parlance)
  4174. // incomplete types are not object types.
  4175. if (ResultType->isFunctionType()) {
  4176. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4177. << ResultType << BaseExpr->getSourceRange();
  4178. return ExprError();
  4179. }
  4180. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  4181. // GNU extension: subscripting on pointer to void
  4182. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4183. << BaseExpr->getSourceRange();
  4184. // C forbids expressions of unqualified void type from being l-values.
  4185. // See IsCForbiddenLValueType.
  4186. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4187. } else if (!ResultType->isDependentType() &&
  4188. RequireCompleteType(LLoc, ResultType,
  4189. diag::err_subscript_incomplete_type, BaseExpr))
  4190. return ExprError();
  4191. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4192. !ResultType.isCForbiddenLValueType());
  4193. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  4194. FunctionScopes.size() > 1) {
  4195. if (auto *TT =
  4196. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  4197. for (auto I = FunctionScopes.rbegin(),
  4198. E = std::prev(FunctionScopes.rend());
  4199. I != E; ++I) {
  4200. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  4201. if (CSI == nullptr)
  4202. break;
  4203. DeclContext *DC = nullptr;
  4204. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  4205. DC = LSI->CallOperator;
  4206. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  4207. DC = CRSI->TheCapturedDecl;
  4208. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  4209. DC = BSI->TheDecl;
  4210. if (DC) {
  4211. if (DC->containsDecl(TT->getDecl()))
  4212. break;
  4213. captureVariablyModifiedType(
  4214. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  4215. }
  4216. }
  4217. }
  4218. }
  4219. return new (Context)
  4220. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4221. }
  4222. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4223. ParmVarDecl *Param) {
  4224. if (Param->hasUnparsedDefaultArg()) {
  4225. Diag(CallLoc,
  4226. diag::err_use_of_default_argument_to_function_declared_later) <<
  4227. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4228. Diag(UnparsedDefaultArgLocs[Param],
  4229. diag::note_default_argument_declared_here);
  4230. return true;
  4231. }
  4232. if (Param->hasUninstantiatedDefaultArg()) {
  4233. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4234. EnterExpressionEvaluationContext EvalContext(
  4235. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4236. // Instantiate the expression.
  4237. //
  4238. // FIXME: Pass in a correct Pattern argument, otherwise
  4239. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4240. //
  4241. // template<typename T>
  4242. // struct A {
  4243. // static int FooImpl();
  4244. //
  4245. // template<typename Tp>
  4246. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4247. // // template argument list [[T], [Tp]], should be [[Tp]].
  4248. // friend A<Tp> Foo(int a);
  4249. // };
  4250. //
  4251. // template<typename T>
  4252. // A<T> Foo(int a = A<T>::FooImpl());
  4253. MultiLevelTemplateArgumentList MutiLevelArgList
  4254. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4255. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4256. MutiLevelArgList.getInnermost());
  4257. if (Inst.isInvalid())
  4258. return true;
  4259. if (Inst.isAlreadyInstantiating()) {
  4260. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4261. Param->setInvalidDecl();
  4262. return true;
  4263. }
  4264. ExprResult Result;
  4265. {
  4266. // C++ [dcl.fct.default]p5:
  4267. // The names in the [default argument] expression are bound, and
  4268. // the semantic constraints are checked, at the point where the
  4269. // default argument expression appears.
  4270. ContextRAII SavedContext(*this, FD);
  4271. LocalInstantiationScope Local(*this);
  4272. runWithSufficientStackSpace(CallLoc, [&] {
  4273. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4274. /*DirectInit*/false);
  4275. });
  4276. }
  4277. if (Result.isInvalid())
  4278. return true;
  4279. // Check the expression as an initializer for the parameter.
  4280. InitializedEntity Entity
  4281. = InitializedEntity::InitializeParameter(Context, Param);
  4282. InitializationKind Kind = InitializationKind::CreateCopy(
  4283. Param->getLocation(),
  4284. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4285. Expr *ResultE = Result.getAs<Expr>();
  4286. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4287. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4288. if (Result.isInvalid())
  4289. return true;
  4290. Result =
  4291. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  4292. /*DiscardedValue*/ false);
  4293. if (Result.isInvalid())
  4294. return true;
  4295. // Remember the instantiated default argument.
  4296. Param->setDefaultArg(Result.getAs<Expr>());
  4297. if (ASTMutationListener *L = getASTMutationListener()) {
  4298. L->DefaultArgumentInstantiated(Param);
  4299. }
  4300. }
  4301. // If the default argument expression is not set yet, we are building it now.
  4302. if (!Param->hasInit()) {
  4303. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4304. Param->setInvalidDecl();
  4305. return true;
  4306. }
  4307. // If the default expression creates temporaries, we need to
  4308. // push them to the current stack of expression temporaries so they'll
  4309. // be properly destroyed.
  4310. // FIXME: We should really be rebuilding the default argument with new
  4311. // bound temporaries; see the comment in PR5810.
  4312. // We don't need to do that with block decls, though, because
  4313. // blocks in default argument expression can never capture anything.
  4314. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4315. // Set the "needs cleanups" bit regardless of whether there are
  4316. // any explicit objects.
  4317. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4318. // Append all the objects to the cleanup list. Right now, this
  4319. // should always be a no-op, because blocks in default argument
  4320. // expressions should never be able to capture anything.
  4321. assert(!Init->getNumObjects() &&
  4322. "default argument expression has capturing blocks?");
  4323. }
  4324. // We already type-checked the argument, so we know it works.
  4325. // Just mark all of the declarations in this potentially-evaluated expression
  4326. // as being "referenced".
  4327. EnterExpressionEvaluationContext EvalContext(
  4328. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4329. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4330. /*SkipLocalVariables=*/true);
  4331. return false;
  4332. }
  4333. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4334. FunctionDecl *FD, ParmVarDecl *Param) {
  4335. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4336. return ExprError();
  4337. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  4338. }
  4339. Sema::VariadicCallType
  4340. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4341. Expr *Fn) {
  4342. if (Proto && Proto->isVariadic()) {
  4343. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4344. return VariadicConstructor;
  4345. else if (Fn && Fn->getType()->isBlockPointerType())
  4346. return VariadicBlock;
  4347. else if (FDecl) {
  4348. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4349. if (Method->isInstance())
  4350. return VariadicMethod;
  4351. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4352. return VariadicMethod;
  4353. return VariadicFunction;
  4354. }
  4355. return VariadicDoesNotApply;
  4356. }
  4357. namespace {
  4358. class FunctionCallCCC final : public FunctionCallFilterCCC {
  4359. public:
  4360. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4361. unsigned NumArgs, MemberExpr *ME)
  4362. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4363. FunctionName(FuncName) {}
  4364. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4365. if (!candidate.getCorrectionSpecifier() ||
  4366. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4367. return false;
  4368. }
  4369. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4370. }
  4371. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  4372. return std::make_unique<FunctionCallCCC>(*this);
  4373. }
  4374. private:
  4375. const IdentifierInfo *const FunctionName;
  4376. };
  4377. }
  4378. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4379. FunctionDecl *FDecl,
  4380. ArrayRef<Expr *> Args) {
  4381. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4382. DeclarationName FuncName = FDecl->getDeclName();
  4383. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4384. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  4385. if (TypoCorrection Corrected = S.CorrectTypo(
  4386. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4387. S.getScopeForContext(S.CurContext), nullptr, CCC,
  4388. Sema::CTK_ErrorRecovery)) {
  4389. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4390. if (Corrected.isOverloaded()) {
  4391. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4392. OverloadCandidateSet::iterator Best;
  4393. for (NamedDecl *CD : Corrected) {
  4394. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4395. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4396. OCS);
  4397. }
  4398. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4399. case OR_Success:
  4400. ND = Best->FoundDecl;
  4401. Corrected.setCorrectionDecl(ND);
  4402. break;
  4403. default:
  4404. break;
  4405. }
  4406. }
  4407. ND = ND->getUnderlyingDecl();
  4408. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4409. return Corrected;
  4410. }
  4411. }
  4412. return TypoCorrection();
  4413. }
  4414. /// ConvertArgumentsForCall - Converts the arguments specified in
  4415. /// Args/NumArgs to the parameter types of the function FDecl with
  4416. /// function prototype Proto. Call is the call expression itself, and
  4417. /// Fn is the function expression. For a C++ member function, this
  4418. /// routine does not attempt to convert the object argument. Returns
  4419. /// true if the call is ill-formed.
  4420. bool
  4421. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4422. FunctionDecl *FDecl,
  4423. const FunctionProtoType *Proto,
  4424. ArrayRef<Expr *> Args,
  4425. SourceLocation RParenLoc,
  4426. bool IsExecConfig) {
  4427. // Bail out early if calling a builtin with custom typechecking.
  4428. if (FDecl)
  4429. if (unsigned ID = FDecl->getBuiltinID())
  4430. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4431. return false;
  4432. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4433. // assignment, to the types of the corresponding parameter, ...
  4434. unsigned NumParams = Proto->getNumParams();
  4435. bool Invalid = false;
  4436. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4437. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4438. ? 1 /* block */
  4439. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4440. : 0 /* function */);
  4441. // If too few arguments are available (and we don't have default
  4442. // arguments for the remaining parameters), don't make the call.
  4443. if (Args.size() < NumParams) {
  4444. if (Args.size() < MinArgs) {
  4445. TypoCorrection TC;
  4446. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4447. unsigned diag_id =
  4448. MinArgs == NumParams && !Proto->isVariadic()
  4449. ? diag::err_typecheck_call_too_few_args_suggest
  4450. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4451. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4452. << static_cast<unsigned>(Args.size())
  4453. << TC.getCorrectionRange());
  4454. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4455. Diag(RParenLoc,
  4456. MinArgs == NumParams && !Proto->isVariadic()
  4457. ? diag::err_typecheck_call_too_few_args_one
  4458. : diag::err_typecheck_call_too_few_args_at_least_one)
  4459. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4460. else
  4461. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4462. ? diag::err_typecheck_call_too_few_args
  4463. : diag::err_typecheck_call_too_few_args_at_least)
  4464. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4465. << Fn->getSourceRange();
  4466. // Emit the location of the prototype.
  4467. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4468. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4469. return true;
  4470. }
  4471. // We reserve space for the default arguments when we create
  4472. // the call expression, before calling ConvertArgumentsForCall.
  4473. assert((Call->getNumArgs() == NumParams) &&
  4474. "We should have reserved space for the default arguments before!");
  4475. }
  4476. // If too many are passed and not variadic, error on the extras and drop
  4477. // them.
  4478. if (Args.size() > NumParams) {
  4479. if (!Proto->isVariadic()) {
  4480. TypoCorrection TC;
  4481. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4482. unsigned diag_id =
  4483. MinArgs == NumParams && !Proto->isVariadic()
  4484. ? diag::err_typecheck_call_too_many_args_suggest
  4485. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4486. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4487. << static_cast<unsigned>(Args.size())
  4488. << TC.getCorrectionRange());
  4489. } else if (NumParams == 1 && FDecl &&
  4490. FDecl->getParamDecl(0)->getDeclName())
  4491. Diag(Args[NumParams]->getBeginLoc(),
  4492. MinArgs == NumParams
  4493. ? diag::err_typecheck_call_too_many_args_one
  4494. : diag::err_typecheck_call_too_many_args_at_most_one)
  4495. << FnKind << FDecl->getParamDecl(0)
  4496. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4497. << SourceRange(Args[NumParams]->getBeginLoc(),
  4498. Args.back()->getEndLoc());
  4499. else
  4500. Diag(Args[NumParams]->getBeginLoc(),
  4501. MinArgs == NumParams
  4502. ? diag::err_typecheck_call_too_many_args
  4503. : diag::err_typecheck_call_too_many_args_at_most)
  4504. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4505. << Fn->getSourceRange()
  4506. << SourceRange(Args[NumParams]->getBeginLoc(),
  4507. Args.back()->getEndLoc());
  4508. // Emit the location of the prototype.
  4509. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4510. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4511. // This deletes the extra arguments.
  4512. Call->shrinkNumArgs(NumParams);
  4513. return true;
  4514. }
  4515. }
  4516. SmallVector<Expr *, 8> AllArgs;
  4517. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4518. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4519. AllArgs, CallType);
  4520. if (Invalid)
  4521. return true;
  4522. unsigned TotalNumArgs = AllArgs.size();
  4523. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4524. Call->setArg(i, AllArgs[i]);
  4525. return false;
  4526. }
  4527. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4528. const FunctionProtoType *Proto,
  4529. unsigned FirstParam, ArrayRef<Expr *> Args,
  4530. SmallVectorImpl<Expr *> &AllArgs,
  4531. VariadicCallType CallType, bool AllowExplicit,
  4532. bool IsListInitialization) {
  4533. unsigned NumParams = Proto->getNumParams();
  4534. bool Invalid = false;
  4535. size_t ArgIx = 0;
  4536. // Continue to check argument types (even if we have too few/many args).
  4537. for (unsigned i = FirstParam; i < NumParams; i++) {
  4538. QualType ProtoArgType = Proto->getParamType(i);
  4539. Expr *Arg;
  4540. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4541. if (ArgIx < Args.size()) {
  4542. Arg = Args[ArgIx++];
  4543. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4544. diag::err_call_incomplete_argument, Arg))
  4545. return true;
  4546. // Strip the unbridged-cast placeholder expression off, if applicable.
  4547. bool CFAudited = false;
  4548. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4549. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4550. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4551. Arg = stripARCUnbridgedCast(Arg);
  4552. else if (getLangOpts().ObjCAutoRefCount &&
  4553. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4554. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4555. CFAudited = true;
  4556. if (Proto->getExtParameterInfo(i).isNoEscape())
  4557. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4558. BE->getBlockDecl()->setDoesNotEscape();
  4559. InitializedEntity Entity =
  4560. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4561. ProtoArgType)
  4562. : InitializedEntity::InitializeParameter(
  4563. Context, ProtoArgType, Proto->isParamConsumed(i));
  4564. // Remember that parameter belongs to a CF audited API.
  4565. if (CFAudited)
  4566. Entity.setParameterCFAudited();
  4567. ExprResult ArgE = PerformCopyInitialization(
  4568. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4569. if (ArgE.isInvalid())
  4570. return true;
  4571. Arg = ArgE.getAs<Expr>();
  4572. } else {
  4573. assert(Param && "can't use default arguments without a known callee");
  4574. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4575. if (ArgExpr.isInvalid())
  4576. return true;
  4577. Arg = ArgExpr.getAs<Expr>();
  4578. }
  4579. // Check for array bounds violations for each argument to the call. This
  4580. // check only triggers warnings when the argument isn't a more complex Expr
  4581. // with its own checking, such as a BinaryOperator.
  4582. CheckArrayAccess(Arg);
  4583. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4584. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4585. AllArgs.push_back(Arg);
  4586. }
  4587. // If this is a variadic call, handle args passed through "...".
  4588. if (CallType != VariadicDoesNotApply) {
  4589. // Assume that extern "C" functions with variadic arguments that
  4590. // return __unknown_anytype aren't *really* variadic.
  4591. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4592. FDecl->isExternC()) {
  4593. for (Expr *A : Args.slice(ArgIx)) {
  4594. QualType paramType; // ignored
  4595. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4596. Invalid |= arg.isInvalid();
  4597. AllArgs.push_back(arg.get());
  4598. }
  4599. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4600. } else {
  4601. for (Expr *A : Args.slice(ArgIx)) {
  4602. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4603. Invalid |= Arg.isInvalid();
  4604. AllArgs.push_back(Arg.get());
  4605. }
  4606. }
  4607. // Check for array bounds violations.
  4608. for (Expr *A : Args.slice(ArgIx))
  4609. CheckArrayAccess(A);
  4610. }
  4611. return Invalid;
  4612. }
  4613. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4614. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4615. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4616. TL = DTL.getOriginalLoc();
  4617. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4618. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4619. << ATL.getLocalSourceRange();
  4620. }
  4621. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4622. /// array parameter, check that it is non-null, and that if it is formed by
  4623. /// array-to-pointer decay, the underlying array is sufficiently large.
  4624. ///
  4625. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4626. /// array type derivation, then for each call to the function, the value of the
  4627. /// corresponding actual argument shall provide access to the first element of
  4628. /// an array with at least as many elements as specified by the size expression.
  4629. void
  4630. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4631. ParmVarDecl *Param,
  4632. const Expr *ArgExpr) {
  4633. // Static array parameters are not supported in C++.
  4634. if (!Param || getLangOpts().CPlusPlus)
  4635. return;
  4636. QualType OrigTy = Param->getOriginalType();
  4637. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4638. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4639. return;
  4640. if (ArgExpr->isNullPointerConstant(Context,
  4641. Expr::NPC_NeverValueDependent)) {
  4642. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4643. DiagnoseCalleeStaticArrayParam(*this, Param);
  4644. return;
  4645. }
  4646. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4647. if (!CAT)
  4648. return;
  4649. const ConstantArrayType *ArgCAT =
  4650. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  4651. if (!ArgCAT)
  4652. return;
  4653. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  4654. ArgCAT->getElementType())) {
  4655. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4656. Diag(CallLoc, diag::warn_static_array_too_small)
  4657. << ArgExpr->getSourceRange()
  4658. << (unsigned)ArgCAT->getSize().getZExtValue()
  4659. << (unsigned)CAT->getSize().getZExtValue() << 0;
  4660. DiagnoseCalleeStaticArrayParam(*this, Param);
  4661. }
  4662. return;
  4663. }
  4664. Optional<CharUnits> ArgSize =
  4665. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  4666. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  4667. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  4668. Diag(CallLoc, diag::warn_static_array_too_small)
  4669. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  4670. << (unsigned)ParmSize->getQuantity() << 1;
  4671. DiagnoseCalleeStaticArrayParam(*this, Param);
  4672. }
  4673. }
  4674. /// Given a function expression of unknown-any type, try to rebuild it
  4675. /// to have a function type.
  4676. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4677. /// Is the given type a placeholder that we need to lower out
  4678. /// immediately during argument processing?
  4679. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4680. // Placeholders are never sugared.
  4681. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4682. if (!placeholder) return false;
  4683. switch (placeholder->getKind()) {
  4684. // Ignore all the non-placeholder types.
  4685. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4686. case BuiltinType::Id:
  4687. #include "clang/Basic/OpenCLImageTypes.def"
  4688. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4689. case BuiltinType::Id:
  4690. #include "clang/Basic/OpenCLExtensionTypes.def"
  4691. // In practice we'll never use this, since all SVE types are sugared
  4692. // via TypedefTypes rather than exposed directly as BuiltinTypes.
  4693. #define SVE_TYPE(Name, Id, SingletonId) \
  4694. case BuiltinType::Id:
  4695. #include "clang/Basic/AArch64SVEACLETypes.def"
  4696. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4697. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4698. #include "clang/AST/BuiltinTypes.def"
  4699. return false;
  4700. // We cannot lower out overload sets; they might validly be resolved
  4701. // by the call machinery.
  4702. case BuiltinType::Overload:
  4703. return false;
  4704. // Unbridged casts in ARC can be handled in some call positions and
  4705. // should be left in place.
  4706. case BuiltinType::ARCUnbridgedCast:
  4707. return false;
  4708. // Pseudo-objects should be converted as soon as possible.
  4709. case BuiltinType::PseudoObject:
  4710. return true;
  4711. // The debugger mode could theoretically but currently does not try
  4712. // to resolve unknown-typed arguments based on known parameter types.
  4713. case BuiltinType::UnknownAny:
  4714. return true;
  4715. // These are always invalid as call arguments and should be reported.
  4716. case BuiltinType::BoundMember:
  4717. case BuiltinType::BuiltinFn:
  4718. case BuiltinType::OMPArraySection:
  4719. return true;
  4720. }
  4721. llvm_unreachable("bad builtin type kind");
  4722. }
  4723. /// Check an argument list for placeholders that we won't try to
  4724. /// handle later.
  4725. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4726. // Apply this processing to all the arguments at once instead of
  4727. // dying at the first failure.
  4728. bool hasInvalid = false;
  4729. for (size_t i = 0, e = args.size(); i != e; i++) {
  4730. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4731. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4732. if (result.isInvalid()) hasInvalid = true;
  4733. else args[i] = result.get();
  4734. } else if (hasInvalid) {
  4735. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4736. }
  4737. }
  4738. return hasInvalid;
  4739. }
  4740. /// If a builtin function has a pointer argument with no explicit address
  4741. /// space, then it should be able to accept a pointer to any address
  4742. /// space as input. In order to do this, we need to replace the
  4743. /// standard builtin declaration with one that uses the same address space
  4744. /// as the call.
  4745. ///
  4746. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4747. /// it does not contain any pointer arguments without
  4748. /// an address space qualifer. Otherwise the rewritten
  4749. /// FunctionDecl is returned.
  4750. /// TODO: Handle pointer return types.
  4751. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4752. FunctionDecl *FDecl,
  4753. MultiExprArg ArgExprs) {
  4754. QualType DeclType = FDecl->getType();
  4755. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4756. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
  4757. ArgExprs.size() < FT->getNumParams())
  4758. return nullptr;
  4759. bool NeedsNewDecl = false;
  4760. unsigned i = 0;
  4761. SmallVector<QualType, 8> OverloadParams;
  4762. for (QualType ParamType : FT->param_types()) {
  4763. // Convert array arguments to pointer to simplify type lookup.
  4764. ExprResult ArgRes =
  4765. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4766. if (ArgRes.isInvalid())
  4767. return nullptr;
  4768. Expr *Arg = ArgRes.get();
  4769. QualType ArgType = Arg->getType();
  4770. if (!ParamType->isPointerType() ||
  4771. ParamType.getQualifiers().hasAddressSpace() ||
  4772. !ArgType->isPointerType() ||
  4773. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4774. OverloadParams.push_back(ParamType);
  4775. continue;
  4776. }
  4777. QualType PointeeType = ParamType->getPointeeType();
  4778. if (PointeeType.getQualifiers().hasAddressSpace())
  4779. continue;
  4780. NeedsNewDecl = true;
  4781. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4782. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4783. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4784. }
  4785. if (!NeedsNewDecl)
  4786. return nullptr;
  4787. FunctionProtoType::ExtProtoInfo EPI;
  4788. EPI.Variadic = FT->isVariadic();
  4789. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4790. OverloadParams, EPI);
  4791. DeclContext *Parent = FDecl->getParent();
  4792. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4793. FDecl->getLocation(),
  4794. FDecl->getLocation(),
  4795. FDecl->getIdentifier(),
  4796. OverloadTy,
  4797. /*TInfo=*/nullptr,
  4798. SC_Extern, false,
  4799. /*hasPrototype=*/true);
  4800. SmallVector<ParmVarDecl*, 16> Params;
  4801. FT = cast<FunctionProtoType>(OverloadTy);
  4802. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4803. QualType ParamType = FT->getParamType(i);
  4804. ParmVarDecl *Parm =
  4805. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4806. SourceLocation(), nullptr, ParamType,
  4807. /*TInfo=*/nullptr, SC_None, nullptr);
  4808. Parm->setScopeInfo(0, i);
  4809. Params.push_back(Parm);
  4810. }
  4811. OverloadDecl->setParams(Params);
  4812. return OverloadDecl;
  4813. }
  4814. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4815. FunctionDecl *Callee,
  4816. MultiExprArg ArgExprs) {
  4817. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4818. // similar attributes) really don't like it when functions are called with an
  4819. // invalid number of args.
  4820. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4821. /*PartialOverloading=*/false) &&
  4822. !Callee->isVariadic())
  4823. return;
  4824. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4825. return;
  4826. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4827. S.Diag(Fn->getBeginLoc(),
  4828. isa<CXXMethodDecl>(Callee)
  4829. ? diag::err_ovl_no_viable_member_function_in_call
  4830. : diag::err_ovl_no_viable_function_in_call)
  4831. << Callee << Callee->getSourceRange();
  4832. S.Diag(Callee->getLocation(),
  4833. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4834. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4835. return;
  4836. }
  4837. }
  4838. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4839. const UnresolvedMemberExpr *const UME, Sema &S) {
  4840. const auto GetFunctionLevelDCIfCXXClass =
  4841. [](Sema &S) -> const CXXRecordDecl * {
  4842. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4843. if (!DC || !DC->getParent())
  4844. return nullptr;
  4845. // If the call to some member function was made from within a member
  4846. // function body 'M' return return 'M's parent.
  4847. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4848. return MD->getParent()->getCanonicalDecl();
  4849. // else the call was made from within a default member initializer of a
  4850. // class, so return the class.
  4851. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4852. return RD->getCanonicalDecl();
  4853. return nullptr;
  4854. };
  4855. // If our DeclContext is neither a member function nor a class (in the
  4856. // case of a lambda in a default member initializer), we can't have an
  4857. // enclosing 'this'.
  4858. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4859. if (!CurParentClass)
  4860. return false;
  4861. // The naming class for implicit member functions call is the class in which
  4862. // name lookup starts.
  4863. const CXXRecordDecl *const NamingClass =
  4864. UME->getNamingClass()->getCanonicalDecl();
  4865. assert(NamingClass && "Must have naming class even for implicit access");
  4866. // If the unresolved member functions were found in a 'naming class' that is
  4867. // related (either the same or derived from) to the class that contains the
  4868. // member function that itself contained the implicit member access.
  4869. return CurParentClass == NamingClass ||
  4870. CurParentClass->isDerivedFrom(NamingClass);
  4871. }
  4872. static void
  4873. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4874. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4875. if (!UME)
  4876. return;
  4877. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4878. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4879. // already been captured, or if this is an implicit member function call (if
  4880. // it isn't, an attempt to capture 'this' should already have been made).
  4881. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4882. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4883. return;
  4884. // Check if the naming class in which the unresolved members were found is
  4885. // related (same as or is a base of) to the enclosing class.
  4886. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4887. return;
  4888. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4889. // If the enclosing function is not dependent, then this lambda is
  4890. // capture ready, so if we can capture this, do so.
  4891. if (!EnclosingFunctionCtx->isDependentContext()) {
  4892. // If the current lambda and all enclosing lambdas can capture 'this' -
  4893. // then go ahead and capture 'this' (since our unresolved overload set
  4894. // contains at least one non-static member function).
  4895. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4896. S.CheckCXXThisCapture(CallLoc);
  4897. } else if (S.CurContext->isDependentContext()) {
  4898. // ... since this is an implicit member reference, that might potentially
  4899. // involve a 'this' capture, mark 'this' for potential capture in
  4900. // enclosing lambdas.
  4901. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4902. CurLSI->addPotentialThisCapture(CallLoc);
  4903. }
  4904. }
  4905. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4906. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4907. Expr *ExecConfig) {
  4908. ExprResult Call =
  4909. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
  4910. if (Call.isInvalid())
  4911. return Call;
  4912. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  4913. // language modes.
  4914. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  4915. if (ULE->hasExplicitTemplateArgs() &&
  4916. ULE->decls_begin() == ULE->decls_end()) {
  4917. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
  4918. ? diag::warn_cxx17_compat_adl_only_template_id
  4919. : diag::ext_adl_only_template_id)
  4920. << ULE->getName();
  4921. }
  4922. }
  4923. return Call;
  4924. }
  4925. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  4926. /// This provides the location of the left/right parens and a list of comma
  4927. /// locations.
  4928. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4929. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4930. Expr *ExecConfig, bool IsExecConfig) {
  4931. // Since this might be a postfix expression, get rid of ParenListExprs.
  4932. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4933. if (Result.isInvalid()) return ExprError();
  4934. Fn = Result.get();
  4935. if (checkArgsForPlaceholders(*this, ArgExprs))
  4936. return ExprError();
  4937. if (getLangOpts().CPlusPlus) {
  4938. // If this is a pseudo-destructor expression, build the call immediately.
  4939. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4940. if (!ArgExprs.empty()) {
  4941. // Pseudo-destructor calls should not have any arguments.
  4942. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4943. << FixItHint::CreateRemoval(
  4944. SourceRange(ArgExprs.front()->getBeginLoc(),
  4945. ArgExprs.back()->getEndLoc()));
  4946. }
  4947. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  4948. VK_RValue, RParenLoc);
  4949. }
  4950. if (Fn->getType() == Context.PseudoObjectTy) {
  4951. ExprResult result = CheckPlaceholderExpr(Fn);
  4952. if (result.isInvalid()) return ExprError();
  4953. Fn = result.get();
  4954. }
  4955. // Determine whether this is a dependent call inside a C++ template,
  4956. // in which case we won't do any semantic analysis now.
  4957. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4958. if (ExecConfig) {
  4959. return CUDAKernelCallExpr::Create(
  4960. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4961. Context.DependentTy, VK_RValue, RParenLoc);
  4962. } else {
  4963. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4964. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4965. Fn->getBeginLoc());
  4966. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4967. VK_RValue, RParenLoc);
  4968. }
  4969. }
  4970. // Determine whether this is a call to an object (C++ [over.call.object]).
  4971. if (Fn->getType()->isRecordType())
  4972. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4973. RParenLoc);
  4974. if (Fn->getType() == Context.UnknownAnyTy) {
  4975. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4976. if (result.isInvalid()) return ExprError();
  4977. Fn = result.get();
  4978. }
  4979. if (Fn->getType() == Context.BoundMemberTy) {
  4980. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4981. RParenLoc);
  4982. }
  4983. }
  4984. // Check for overloaded calls. This can happen even in C due to extensions.
  4985. if (Fn->getType() == Context.OverloadTy) {
  4986. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4987. // We aren't supposed to apply this logic if there's an '&' involved.
  4988. if (!find.HasFormOfMemberPointer) {
  4989. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4990. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4991. VK_RValue, RParenLoc);
  4992. OverloadExpr *ovl = find.Expression;
  4993. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4994. return BuildOverloadedCallExpr(
  4995. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4996. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4997. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4998. RParenLoc);
  4999. }
  5000. }
  5001. // If we're directly calling a function, get the appropriate declaration.
  5002. if (Fn->getType() == Context.UnknownAnyTy) {
  5003. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  5004. if (result.isInvalid()) return ExprError();
  5005. Fn = result.get();
  5006. }
  5007. Expr *NakedFn = Fn->IgnoreParens();
  5008. bool CallingNDeclIndirectly = false;
  5009. NamedDecl *NDecl = nullptr;
  5010. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  5011. if (UnOp->getOpcode() == UO_AddrOf) {
  5012. CallingNDeclIndirectly = true;
  5013. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  5014. }
  5015. }
  5016. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  5017. NDecl = DRE->getDecl();
  5018. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  5019. if (FDecl && FDecl->getBuiltinID()) {
  5020. // Rewrite the function decl for this builtin by replacing parameters
  5021. // with no explicit address space with the address space of the arguments
  5022. // in ArgExprs.
  5023. if ((FDecl =
  5024. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  5025. NDecl = FDecl;
  5026. Fn = DeclRefExpr::Create(
  5027. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  5028. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  5029. nullptr, DRE->isNonOdrUse());
  5030. }
  5031. }
  5032. } else if (isa<MemberExpr>(NakedFn))
  5033. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  5034. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  5035. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  5036. FD, /*Complain=*/true, Fn->getBeginLoc()))
  5037. return ExprError();
  5038. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  5039. return ExprError();
  5040. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  5041. }
  5042. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  5043. ExecConfig, IsExecConfig);
  5044. }
  5045. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  5046. ///
  5047. /// __builtin_astype( value, dst type )
  5048. ///
  5049. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  5050. SourceLocation BuiltinLoc,
  5051. SourceLocation RParenLoc) {
  5052. ExprValueKind VK = VK_RValue;
  5053. ExprObjectKind OK = OK_Ordinary;
  5054. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  5055. QualType SrcTy = E->getType();
  5056. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  5057. return ExprError(Diag(BuiltinLoc,
  5058. diag::err_invalid_astype_of_different_size)
  5059. << DstTy
  5060. << SrcTy
  5061. << E->getSourceRange());
  5062. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5063. }
  5064. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  5065. /// provided arguments.
  5066. ///
  5067. /// __builtin_convertvector( value, dst type )
  5068. ///
  5069. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  5070. SourceLocation BuiltinLoc,
  5071. SourceLocation RParenLoc) {
  5072. TypeSourceInfo *TInfo;
  5073. GetTypeFromParser(ParsedDestTy, &TInfo);
  5074. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  5075. }
  5076. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  5077. /// i.e. an expression not of \p OverloadTy. The expression should
  5078. /// unary-convert to an expression of function-pointer or
  5079. /// block-pointer type.
  5080. ///
  5081. /// \param NDecl the declaration being called, if available
  5082. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  5083. SourceLocation LParenLoc,
  5084. ArrayRef<Expr *> Args,
  5085. SourceLocation RParenLoc, Expr *Config,
  5086. bool IsExecConfig, ADLCallKind UsesADL) {
  5087. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5088. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5089. // Functions with 'interrupt' attribute cannot be called directly.
  5090. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5091. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5092. return ExprError();
  5093. }
  5094. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5095. // so there's some risk when calling out to non-interrupt handler functions
  5096. // that the callee might not preserve them. This is easy to diagnose here,
  5097. // but can be very challenging to debug.
  5098. if (auto *Caller = getCurFunctionDecl())
  5099. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5100. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5101. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  5102. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5103. }
  5104. // Promote the function operand.
  5105. // We special-case function promotion here because we only allow promoting
  5106. // builtin functions to function pointers in the callee of a call.
  5107. ExprResult Result;
  5108. QualType ResultTy;
  5109. if (BuiltinID &&
  5110. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5111. // Extract the return type from the (builtin) function pointer type.
  5112. // FIXME Several builtins still have setType in
  5113. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5114. // Builtins.def to ensure they are correct before removing setType calls.
  5115. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5116. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5117. ResultTy = FDecl->getCallResultType();
  5118. } else {
  5119. Result = CallExprUnaryConversions(Fn);
  5120. ResultTy = Context.BoolTy;
  5121. }
  5122. if (Result.isInvalid())
  5123. return ExprError();
  5124. Fn = Result.get();
  5125. // Check for a valid function type, but only if it is not a builtin which
  5126. // requires custom type checking. These will be handled by
  5127. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5128. const FunctionType *FuncT = nullptr;
  5129. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  5130. retry:
  5131. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  5132. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  5133. // have type pointer to function".
  5134. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  5135. if (!FuncT)
  5136. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5137. << Fn->getType() << Fn->getSourceRange());
  5138. } else if (const BlockPointerType *BPT =
  5139. Fn->getType()->getAs<BlockPointerType>()) {
  5140. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  5141. } else {
  5142. // Handle calls to expressions of unknown-any type.
  5143. if (Fn->getType() == Context.UnknownAnyTy) {
  5144. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  5145. if (rewrite.isInvalid())
  5146. return ExprError();
  5147. Fn = rewrite.get();
  5148. goto retry;
  5149. }
  5150. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5151. << Fn->getType() << Fn->getSourceRange());
  5152. }
  5153. }
  5154. // Get the number of parameters in the function prototype, if any.
  5155. // We will allocate space for max(Args.size(), NumParams) arguments
  5156. // in the call expression.
  5157. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  5158. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  5159. CallExpr *TheCall;
  5160. if (Config) {
  5161. assert(UsesADL == ADLCallKind::NotADL &&
  5162. "CUDAKernelCallExpr should not use ADL");
  5163. TheCall =
  5164. CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
  5165. ResultTy, VK_RValue, RParenLoc, NumParams);
  5166. } else {
  5167. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5168. RParenLoc, NumParams, UsesADL);
  5169. }
  5170. if (!getLangOpts().CPlusPlus) {
  5171. // Forget about the nulled arguments since typo correction
  5172. // do not handle them well.
  5173. TheCall->shrinkNumArgs(Args.size());
  5174. // C cannot always handle TypoExpr nodes in builtin calls and direct
  5175. // function calls as their argument checking don't necessarily handle
  5176. // dependent types properly, so make sure any TypoExprs have been
  5177. // dealt with.
  5178. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  5179. if (!Result.isUsable()) return ExprError();
  5180. CallExpr *TheOldCall = TheCall;
  5181. TheCall = dyn_cast<CallExpr>(Result.get());
  5182. bool CorrectedTypos = TheCall != TheOldCall;
  5183. if (!TheCall) return Result;
  5184. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  5185. // A new call expression node was created if some typos were corrected.
  5186. // However it may not have been constructed with enough storage. In this
  5187. // case, rebuild the node with enough storage. The waste of space is
  5188. // immaterial since this only happens when some typos were corrected.
  5189. if (CorrectedTypos && Args.size() < NumParams) {
  5190. if (Config)
  5191. TheCall = CUDAKernelCallExpr::Create(
  5192. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
  5193. RParenLoc, NumParams);
  5194. else
  5195. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5196. RParenLoc, NumParams, UsesADL);
  5197. }
  5198. // We can now handle the nulled arguments for the default arguments.
  5199. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  5200. }
  5201. // Bail out early if calling a builtin with custom type checking.
  5202. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  5203. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5204. if (getLangOpts().CUDA) {
  5205. if (Config) {
  5206. // CUDA: Kernel calls must be to global functions
  5207. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  5208. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  5209. << FDecl << Fn->getSourceRange());
  5210. // CUDA: Kernel function must have 'void' return type
  5211. if (!FuncT->getReturnType()->isVoidType() &&
  5212. !FuncT->getReturnType()->getAs<AutoType>() &&
  5213. !FuncT->getReturnType()->isInstantiationDependentType())
  5214. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  5215. << Fn->getType() << Fn->getSourceRange());
  5216. } else {
  5217. // CUDA: Calls to global functions must be configured
  5218. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  5219. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  5220. << FDecl << Fn->getSourceRange());
  5221. }
  5222. }
  5223. // Check for a valid return type
  5224. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  5225. FDecl))
  5226. return ExprError();
  5227. // We know the result type of the call, set it.
  5228. TheCall->setType(FuncT->getCallResultType(Context));
  5229. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  5230. if (Proto) {
  5231. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  5232. IsExecConfig))
  5233. return ExprError();
  5234. } else {
  5235. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  5236. if (FDecl) {
  5237. // Check if we have too few/too many template arguments, based
  5238. // on our knowledge of the function definition.
  5239. const FunctionDecl *Def = nullptr;
  5240. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  5241. Proto = Def->getType()->getAs<FunctionProtoType>();
  5242. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  5243. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  5244. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  5245. }
  5246. // If the function we're calling isn't a function prototype, but we have
  5247. // a function prototype from a prior declaratiom, use that prototype.
  5248. if (!FDecl->hasPrototype())
  5249. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  5250. }
  5251. // Promote the arguments (C99 6.5.2.2p6).
  5252. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  5253. Expr *Arg = Args[i];
  5254. if (Proto && i < Proto->getNumParams()) {
  5255. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5256. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  5257. ExprResult ArgE =
  5258. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5259. if (ArgE.isInvalid())
  5260. return true;
  5261. Arg = ArgE.getAs<Expr>();
  5262. } else {
  5263. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  5264. if (ArgE.isInvalid())
  5265. return true;
  5266. Arg = ArgE.getAs<Expr>();
  5267. }
  5268. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  5269. diag::err_call_incomplete_argument, Arg))
  5270. return ExprError();
  5271. TheCall->setArg(i, Arg);
  5272. }
  5273. }
  5274. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5275. if (!Method->isStatic())
  5276. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  5277. << Fn->getSourceRange());
  5278. // Check for sentinels
  5279. if (NDecl)
  5280. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  5281. // Do special checking on direct calls to functions.
  5282. if (FDecl) {
  5283. if (CheckFunctionCall(FDecl, TheCall, Proto))
  5284. return ExprError();
  5285. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  5286. if (BuiltinID)
  5287. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5288. } else if (NDecl) {
  5289. if (CheckPointerCall(NDecl, TheCall, Proto))
  5290. return ExprError();
  5291. } else {
  5292. if (CheckOtherCall(TheCall, Proto))
  5293. return ExprError();
  5294. }
  5295. return MaybeBindToTemporary(TheCall);
  5296. }
  5297. ExprResult
  5298. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5299. SourceLocation RParenLoc, Expr *InitExpr) {
  5300. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5301. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5302. TypeSourceInfo *TInfo;
  5303. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5304. if (!TInfo)
  5305. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5306. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5307. }
  5308. ExprResult
  5309. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5310. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5311. QualType literalType = TInfo->getType();
  5312. if (literalType->isArrayType()) {
  5313. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5314. diag::err_illegal_decl_array_incomplete_type,
  5315. SourceRange(LParenLoc,
  5316. LiteralExpr->getSourceRange().getEnd())))
  5317. return ExprError();
  5318. if (literalType->isVariableArrayType())
  5319. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5320. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5321. } else if (!literalType->isDependentType() &&
  5322. RequireCompleteType(LParenLoc, literalType,
  5323. diag::err_typecheck_decl_incomplete_type,
  5324. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5325. return ExprError();
  5326. InitializedEntity Entity
  5327. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5328. InitializationKind Kind
  5329. = InitializationKind::CreateCStyleCast(LParenLoc,
  5330. SourceRange(LParenLoc, RParenLoc),
  5331. /*InitList=*/true);
  5332. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5333. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5334. &literalType);
  5335. if (Result.isInvalid())
  5336. return ExprError();
  5337. LiteralExpr = Result.get();
  5338. bool isFileScope = !CurContext->isFunctionOrMethod();
  5339. // In C, compound literals are l-values for some reason.
  5340. // For GCC compatibility, in C++, file-scope array compound literals with
  5341. // constant initializers are also l-values, and compound literals are
  5342. // otherwise prvalues.
  5343. //
  5344. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5345. // constant initializers as l-values, but that's non-conforming, so we don't
  5346. // follow it there.)
  5347. //
  5348. // FIXME: It would be better to handle the lvalue cases as materializing and
  5349. // lifetime-extending a temporary object, but our materialized temporaries
  5350. // representation only supports lifetime extension from a variable, not "out
  5351. // of thin air".
  5352. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5353. // is bound to the result of applying array-to-pointer decay to the compound
  5354. // literal.
  5355. // FIXME: GCC supports compound literals of reference type, which should
  5356. // obviously have a value kind derived from the kind of reference involved.
  5357. ExprValueKind VK =
  5358. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5359. ? VK_RValue
  5360. : VK_LValue;
  5361. if (isFileScope)
  5362. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  5363. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  5364. Expr *Init = ILE->getInit(i);
  5365. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  5366. }
  5367. auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5368. VK, LiteralExpr, isFileScope);
  5369. if (isFileScope) {
  5370. if (!LiteralExpr->isTypeDependent() &&
  5371. !LiteralExpr->isValueDependent() &&
  5372. !literalType->isDependentType()) // C99 6.5.2.5p3
  5373. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5374. return ExprError();
  5375. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5376. literalType.getAddressSpace() != LangAS::Default) {
  5377. // Embedded-C extensions to C99 6.5.2.5:
  5378. // "If the compound literal occurs inside the body of a function, the
  5379. // type name shall not be qualified by an address-space qualifier."
  5380. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5381. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5382. return ExprError();
  5383. }
  5384. // Compound literals that have automatic storage duration are destroyed at
  5385. // the end of the scope. Emit diagnostics if it is or contains a C union type
  5386. // that is non-trivial to destruct.
  5387. if (!isFileScope)
  5388. if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
  5389. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  5390. NTCUC_CompoundLiteral, NTCUK_Destruct);
  5391. if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  5392. E->getType().hasNonTrivialToPrimitiveCopyCUnion())
  5393. checkNonTrivialCUnionInInitializer(E->getInitializer(),
  5394. E->getInitializer()->getExprLoc());
  5395. return MaybeBindToTemporary(E);
  5396. }
  5397. ExprResult
  5398. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5399. SourceLocation RBraceLoc) {
  5400. // Only produce each kind of designated initialization diagnostic once.
  5401. SourceLocation FirstDesignator;
  5402. bool DiagnosedArrayDesignator = false;
  5403. bool DiagnosedNestedDesignator = false;
  5404. bool DiagnosedMixedDesignator = false;
  5405. // Check that any designated initializers are syntactically valid in the
  5406. // current language mode.
  5407. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5408. if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
  5409. if (FirstDesignator.isInvalid())
  5410. FirstDesignator = DIE->getBeginLoc();
  5411. if (!getLangOpts().CPlusPlus)
  5412. break;
  5413. if (!DiagnosedNestedDesignator && DIE->size() > 1) {
  5414. DiagnosedNestedDesignator = true;
  5415. Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
  5416. << DIE->getDesignatorsSourceRange();
  5417. }
  5418. for (auto &Desig : DIE->designators()) {
  5419. if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
  5420. DiagnosedArrayDesignator = true;
  5421. Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
  5422. << Desig.getSourceRange();
  5423. }
  5424. }
  5425. if (!DiagnosedMixedDesignator &&
  5426. !isa<DesignatedInitExpr>(InitArgList[0])) {
  5427. DiagnosedMixedDesignator = true;
  5428. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5429. << DIE->getSourceRange();
  5430. Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
  5431. << InitArgList[0]->getSourceRange();
  5432. }
  5433. } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
  5434. isa<DesignatedInitExpr>(InitArgList[0])) {
  5435. DiagnosedMixedDesignator = true;
  5436. auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
  5437. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5438. << DIE->getSourceRange();
  5439. Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
  5440. << InitArgList[I]->getSourceRange();
  5441. }
  5442. }
  5443. if (FirstDesignator.isValid()) {
  5444. // Only diagnose designated initiaization as a C++20 extension if we didn't
  5445. // already diagnose use of (non-C++20) C99 designator syntax.
  5446. if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
  5447. !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
  5448. Diag(FirstDesignator, getLangOpts().CPlusPlus2a
  5449. ? diag::warn_cxx17_compat_designated_init
  5450. : diag::ext_cxx_designated_init);
  5451. } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
  5452. Diag(FirstDesignator, diag::ext_designated_init);
  5453. }
  5454. }
  5455. return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
  5456. }
  5457. ExprResult
  5458. Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5459. SourceLocation RBraceLoc) {
  5460. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5461. // CheckInitializer() - it requires knowledge of the object being initialized.
  5462. // Immediately handle non-overload placeholders. Overloads can be
  5463. // resolved contextually, but everything else here can't.
  5464. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5465. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5466. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5467. // Ignore failures; dropping the entire initializer list because
  5468. // of one failure would be terrible for indexing/etc.
  5469. if (result.isInvalid()) continue;
  5470. InitArgList[I] = result.get();
  5471. }
  5472. }
  5473. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5474. RBraceLoc);
  5475. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5476. return E;
  5477. }
  5478. /// Do an explicit extend of the given block pointer if we're in ARC.
  5479. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5480. assert(E.get()->getType()->isBlockPointerType());
  5481. assert(E.get()->isRValue());
  5482. // Only do this in an r-value context.
  5483. if (!getLangOpts().ObjCAutoRefCount) return;
  5484. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5485. CK_ARCExtendBlockObject, E.get(),
  5486. /*base path*/ nullptr, VK_RValue);
  5487. Cleanup.setExprNeedsCleanups(true);
  5488. }
  5489. /// Prepare a conversion of the given expression to an ObjC object
  5490. /// pointer type.
  5491. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5492. QualType type = E.get()->getType();
  5493. if (type->isObjCObjectPointerType()) {
  5494. return CK_BitCast;
  5495. } else if (type->isBlockPointerType()) {
  5496. maybeExtendBlockObject(E);
  5497. return CK_BlockPointerToObjCPointerCast;
  5498. } else {
  5499. assert(type->isPointerType());
  5500. return CK_CPointerToObjCPointerCast;
  5501. }
  5502. }
  5503. /// Prepares for a scalar cast, performing all the necessary stages
  5504. /// except the final cast and returning the kind required.
  5505. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5506. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5507. // Also, callers should have filtered out the invalid cases with
  5508. // pointers. Everything else should be possible.
  5509. QualType SrcTy = Src.get()->getType();
  5510. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5511. return CK_NoOp;
  5512. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5513. case Type::STK_MemberPointer:
  5514. llvm_unreachable("member pointer type in C");
  5515. case Type::STK_CPointer:
  5516. case Type::STK_BlockPointer:
  5517. case Type::STK_ObjCObjectPointer:
  5518. switch (DestTy->getScalarTypeKind()) {
  5519. case Type::STK_CPointer: {
  5520. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5521. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5522. if (SrcAS != DestAS)
  5523. return CK_AddressSpaceConversion;
  5524. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5525. return CK_NoOp;
  5526. return CK_BitCast;
  5527. }
  5528. case Type::STK_BlockPointer:
  5529. return (SrcKind == Type::STK_BlockPointer
  5530. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5531. case Type::STK_ObjCObjectPointer:
  5532. if (SrcKind == Type::STK_ObjCObjectPointer)
  5533. return CK_BitCast;
  5534. if (SrcKind == Type::STK_CPointer)
  5535. return CK_CPointerToObjCPointerCast;
  5536. maybeExtendBlockObject(Src);
  5537. return CK_BlockPointerToObjCPointerCast;
  5538. case Type::STK_Bool:
  5539. return CK_PointerToBoolean;
  5540. case Type::STK_Integral:
  5541. return CK_PointerToIntegral;
  5542. case Type::STK_Floating:
  5543. case Type::STK_FloatingComplex:
  5544. case Type::STK_IntegralComplex:
  5545. case Type::STK_MemberPointer:
  5546. case Type::STK_FixedPoint:
  5547. llvm_unreachable("illegal cast from pointer");
  5548. }
  5549. llvm_unreachable("Should have returned before this");
  5550. case Type::STK_FixedPoint:
  5551. switch (DestTy->getScalarTypeKind()) {
  5552. case Type::STK_FixedPoint:
  5553. return CK_FixedPointCast;
  5554. case Type::STK_Bool:
  5555. return CK_FixedPointToBoolean;
  5556. case Type::STK_Integral:
  5557. return CK_FixedPointToIntegral;
  5558. case Type::STK_Floating:
  5559. case Type::STK_IntegralComplex:
  5560. case Type::STK_FloatingComplex:
  5561. Diag(Src.get()->getExprLoc(),
  5562. diag::err_unimplemented_conversion_with_fixed_point_type)
  5563. << DestTy;
  5564. return CK_IntegralCast;
  5565. case Type::STK_CPointer:
  5566. case Type::STK_ObjCObjectPointer:
  5567. case Type::STK_BlockPointer:
  5568. case Type::STK_MemberPointer:
  5569. llvm_unreachable("illegal cast to pointer type");
  5570. }
  5571. llvm_unreachable("Should have returned before this");
  5572. case Type::STK_Bool: // casting from bool is like casting from an integer
  5573. case Type::STK_Integral:
  5574. switch (DestTy->getScalarTypeKind()) {
  5575. case Type::STK_CPointer:
  5576. case Type::STK_ObjCObjectPointer:
  5577. case Type::STK_BlockPointer:
  5578. if (Src.get()->isNullPointerConstant(Context,
  5579. Expr::NPC_ValueDependentIsNull))
  5580. return CK_NullToPointer;
  5581. return CK_IntegralToPointer;
  5582. case Type::STK_Bool:
  5583. return CK_IntegralToBoolean;
  5584. case Type::STK_Integral:
  5585. return CK_IntegralCast;
  5586. case Type::STK_Floating:
  5587. return CK_IntegralToFloating;
  5588. case Type::STK_IntegralComplex:
  5589. Src = ImpCastExprToType(Src.get(),
  5590. DestTy->castAs<ComplexType>()->getElementType(),
  5591. CK_IntegralCast);
  5592. return CK_IntegralRealToComplex;
  5593. case Type::STK_FloatingComplex:
  5594. Src = ImpCastExprToType(Src.get(),
  5595. DestTy->castAs<ComplexType>()->getElementType(),
  5596. CK_IntegralToFloating);
  5597. return CK_FloatingRealToComplex;
  5598. case Type::STK_MemberPointer:
  5599. llvm_unreachable("member pointer type in C");
  5600. case Type::STK_FixedPoint:
  5601. return CK_IntegralToFixedPoint;
  5602. }
  5603. llvm_unreachable("Should have returned before this");
  5604. case Type::STK_Floating:
  5605. switch (DestTy->getScalarTypeKind()) {
  5606. case Type::STK_Floating:
  5607. return CK_FloatingCast;
  5608. case Type::STK_Bool:
  5609. return CK_FloatingToBoolean;
  5610. case Type::STK_Integral:
  5611. return CK_FloatingToIntegral;
  5612. case Type::STK_FloatingComplex:
  5613. Src = ImpCastExprToType(Src.get(),
  5614. DestTy->castAs<ComplexType>()->getElementType(),
  5615. CK_FloatingCast);
  5616. return CK_FloatingRealToComplex;
  5617. case Type::STK_IntegralComplex:
  5618. Src = ImpCastExprToType(Src.get(),
  5619. DestTy->castAs<ComplexType>()->getElementType(),
  5620. CK_FloatingToIntegral);
  5621. return CK_IntegralRealToComplex;
  5622. case Type::STK_CPointer:
  5623. case Type::STK_ObjCObjectPointer:
  5624. case Type::STK_BlockPointer:
  5625. llvm_unreachable("valid float->pointer cast?");
  5626. case Type::STK_MemberPointer:
  5627. llvm_unreachable("member pointer type in C");
  5628. case Type::STK_FixedPoint:
  5629. Diag(Src.get()->getExprLoc(),
  5630. diag::err_unimplemented_conversion_with_fixed_point_type)
  5631. << SrcTy;
  5632. return CK_IntegralCast;
  5633. }
  5634. llvm_unreachable("Should have returned before this");
  5635. case Type::STK_FloatingComplex:
  5636. switch (DestTy->getScalarTypeKind()) {
  5637. case Type::STK_FloatingComplex:
  5638. return CK_FloatingComplexCast;
  5639. case Type::STK_IntegralComplex:
  5640. return CK_FloatingComplexToIntegralComplex;
  5641. case Type::STK_Floating: {
  5642. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5643. if (Context.hasSameType(ET, DestTy))
  5644. return CK_FloatingComplexToReal;
  5645. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5646. return CK_FloatingCast;
  5647. }
  5648. case Type::STK_Bool:
  5649. return CK_FloatingComplexToBoolean;
  5650. case Type::STK_Integral:
  5651. Src = ImpCastExprToType(Src.get(),
  5652. SrcTy->castAs<ComplexType>()->getElementType(),
  5653. CK_FloatingComplexToReal);
  5654. return CK_FloatingToIntegral;
  5655. case Type::STK_CPointer:
  5656. case Type::STK_ObjCObjectPointer:
  5657. case Type::STK_BlockPointer:
  5658. llvm_unreachable("valid complex float->pointer cast?");
  5659. case Type::STK_MemberPointer:
  5660. llvm_unreachable("member pointer type in C");
  5661. case Type::STK_FixedPoint:
  5662. Diag(Src.get()->getExprLoc(),
  5663. diag::err_unimplemented_conversion_with_fixed_point_type)
  5664. << SrcTy;
  5665. return CK_IntegralCast;
  5666. }
  5667. llvm_unreachable("Should have returned before this");
  5668. case Type::STK_IntegralComplex:
  5669. switch (DestTy->getScalarTypeKind()) {
  5670. case Type::STK_FloatingComplex:
  5671. return CK_IntegralComplexToFloatingComplex;
  5672. case Type::STK_IntegralComplex:
  5673. return CK_IntegralComplexCast;
  5674. case Type::STK_Integral: {
  5675. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5676. if (Context.hasSameType(ET, DestTy))
  5677. return CK_IntegralComplexToReal;
  5678. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5679. return CK_IntegralCast;
  5680. }
  5681. case Type::STK_Bool:
  5682. return CK_IntegralComplexToBoolean;
  5683. case Type::STK_Floating:
  5684. Src = ImpCastExprToType(Src.get(),
  5685. SrcTy->castAs<ComplexType>()->getElementType(),
  5686. CK_IntegralComplexToReal);
  5687. return CK_IntegralToFloating;
  5688. case Type::STK_CPointer:
  5689. case Type::STK_ObjCObjectPointer:
  5690. case Type::STK_BlockPointer:
  5691. llvm_unreachable("valid complex int->pointer cast?");
  5692. case Type::STK_MemberPointer:
  5693. llvm_unreachable("member pointer type in C");
  5694. case Type::STK_FixedPoint:
  5695. Diag(Src.get()->getExprLoc(),
  5696. diag::err_unimplemented_conversion_with_fixed_point_type)
  5697. << SrcTy;
  5698. return CK_IntegralCast;
  5699. }
  5700. llvm_unreachable("Should have returned before this");
  5701. }
  5702. llvm_unreachable("Unhandled scalar cast");
  5703. }
  5704. static bool breakDownVectorType(QualType type, uint64_t &len,
  5705. QualType &eltType) {
  5706. // Vectors are simple.
  5707. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5708. len = vecType->getNumElements();
  5709. eltType = vecType->getElementType();
  5710. assert(eltType->isScalarType());
  5711. return true;
  5712. }
  5713. // We allow lax conversion to and from non-vector types, but only if
  5714. // they're real types (i.e. non-complex, non-pointer scalar types).
  5715. if (!type->isRealType()) return false;
  5716. len = 1;
  5717. eltType = type;
  5718. return true;
  5719. }
  5720. /// Are the two types lax-compatible vector types? That is, given
  5721. /// that one of them is a vector, do they have equal storage sizes,
  5722. /// where the storage size is the number of elements times the element
  5723. /// size?
  5724. ///
  5725. /// This will also return false if either of the types is neither a
  5726. /// vector nor a real type.
  5727. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5728. assert(destTy->isVectorType() || srcTy->isVectorType());
  5729. // Disallow lax conversions between scalars and ExtVectors (these
  5730. // conversions are allowed for other vector types because common headers
  5731. // depend on them). Most scalar OP ExtVector cases are handled by the
  5732. // splat path anyway, which does what we want (convert, not bitcast).
  5733. // What this rules out for ExtVectors is crazy things like char4*float.
  5734. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5735. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5736. uint64_t srcLen, destLen;
  5737. QualType srcEltTy, destEltTy;
  5738. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5739. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5740. // ASTContext::getTypeSize will return the size rounded up to a
  5741. // power of 2, so instead of using that, we need to use the raw
  5742. // element size multiplied by the element count.
  5743. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5744. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5745. return (srcLen * srcEltSize == destLen * destEltSize);
  5746. }
  5747. /// Is this a legal conversion between two types, one of which is
  5748. /// known to be a vector type?
  5749. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5750. assert(destTy->isVectorType() || srcTy->isVectorType());
  5751. switch (Context.getLangOpts().getLaxVectorConversions()) {
  5752. case LangOptions::LaxVectorConversionKind::None:
  5753. return false;
  5754. case LangOptions::LaxVectorConversionKind::Integer:
  5755. if (!srcTy->isIntegralOrEnumerationType()) {
  5756. auto *Vec = srcTy->getAs<VectorType>();
  5757. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  5758. return false;
  5759. }
  5760. if (!destTy->isIntegralOrEnumerationType()) {
  5761. auto *Vec = destTy->getAs<VectorType>();
  5762. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  5763. return false;
  5764. }
  5765. // OK, integer (vector) -> integer (vector) bitcast.
  5766. break;
  5767. case LangOptions::LaxVectorConversionKind::All:
  5768. break;
  5769. }
  5770. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5771. }
  5772. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5773. CastKind &Kind) {
  5774. assert(VectorTy->isVectorType() && "Not a vector type!");
  5775. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5776. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5777. return Diag(R.getBegin(),
  5778. Ty->isVectorType() ?
  5779. diag::err_invalid_conversion_between_vectors :
  5780. diag::err_invalid_conversion_between_vector_and_integer)
  5781. << VectorTy << Ty << R;
  5782. } else
  5783. return Diag(R.getBegin(),
  5784. diag::err_invalid_conversion_between_vector_and_scalar)
  5785. << VectorTy << Ty << R;
  5786. Kind = CK_BitCast;
  5787. return false;
  5788. }
  5789. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5790. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5791. if (DestElemTy == SplattedExpr->getType())
  5792. return SplattedExpr;
  5793. assert(DestElemTy->isFloatingType() ||
  5794. DestElemTy->isIntegralOrEnumerationType());
  5795. CastKind CK;
  5796. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5797. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5798. // only when splatting vectors.
  5799. if (DestElemTy->isFloatingType()) {
  5800. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5801. // in two steps: boolean to signed integral, then to floating.
  5802. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5803. CK_BooleanToSignedIntegral);
  5804. SplattedExpr = CastExprRes.get();
  5805. CK = CK_IntegralToFloating;
  5806. } else {
  5807. CK = CK_BooleanToSignedIntegral;
  5808. }
  5809. } else {
  5810. ExprResult CastExprRes = SplattedExpr;
  5811. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5812. if (CastExprRes.isInvalid())
  5813. return ExprError();
  5814. SplattedExpr = CastExprRes.get();
  5815. }
  5816. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5817. }
  5818. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5819. Expr *CastExpr, CastKind &Kind) {
  5820. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5821. QualType SrcTy = CastExpr->getType();
  5822. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5823. // an ExtVectorType.
  5824. // In OpenCL, casts between vectors of different types are not allowed.
  5825. // (See OpenCL 6.2).
  5826. if (SrcTy->isVectorType()) {
  5827. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5828. (getLangOpts().OpenCL &&
  5829. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5830. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5831. << DestTy << SrcTy << R;
  5832. return ExprError();
  5833. }
  5834. Kind = CK_BitCast;
  5835. return CastExpr;
  5836. }
  5837. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5838. // conversion will take place first from scalar to elt type, and then
  5839. // splat from elt type to vector.
  5840. if (SrcTy->isPointerType())
  5841. return Diag(R.getBegin(),
  5842. diag::err_invalid_conversion_between_vector_and_scalar)
  5843. << DestTy << SrcTy << R;
  5844. Kind = CK_VectorSplat;
  5845. return prepareVectorSplat(DestTy, CastExpr);
  5846. }
  5847. ExprResult
  5848. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5849. Declarator &D, ParsedType &Ty,
  5850. SourceLocation RParenLoc, Expr *CastExpr) {
  5851. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5852. "ActOnCastExpr(): missing type or expr");
  5853. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5854. if (D.isInvalidType())
  5855. return ExprError();
  5856. if (getLangOpts().CPlusPlus) {
  5857. // Check that there are no default arguments (C++ only).
  5858. CheckExtraCXXDefaultArguments(D);
  5859. } else {
  5860. // Make sure any TypoExprs have been dealt with.
  5861. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5862. if (!Res.isUsable())
  5863. return ExprError();
  5864. CastExpr = Res.get();
  5865. }
  5866. checkUnusedDeclAttributes(D);
  5867. QualType castType = castTInfo->getType();
  5868. Ty = CreateParsedType(castType, castTInfo);
  5869. bool isVectorLiteral = false;
  5870. // Check for an altivec or OpenCL literal,
  5871. // i.e. all the elements are integer constants.
  5872. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5873. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5874. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5875. && castType->isVectorType() && (PE || PLE)) {
  5876. if (PLE && PLE->getNumExprs() == 0) {
  5877. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5878. return ExprError();
  5879. }
  5880. if (PE || PLE->getNumExprs() == 1) {
  5881. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5882. if (!E->getType()->isVectorType())
  5883. isVectorLiteral = true;
  5884. }
  5885. else
  5886. isVectorLiteral = true;
  5887. }
  5888. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5889. // then handle it as such.
  5890. if (isVectorLiteral)
  5891. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5892. // If the Expr being casted is a ParenListExpr, handle it specially.
  5893. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5894. // sequence of BinOp comma operators.
  5895. if (isa<ParenListExpr>(CastExpr)) {
  5896. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5897. if (Result.isInvalid()) return ExprError();
  5898. CastExpr = Result.get();
  5899. }
  5900. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5901. !getSourceManager().isInSystemMacro(LParenLoc))
  5902. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5903. CheckTollFreeBridgeCast(castType, CastExpr);
  5904. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5905. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5906. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5907. }
  5908. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5909. SourceLocation RParenLoc, Expr *E,
  5910. TypeSourceInfo *TInfo) {
  5911. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5912. "Expected paren or paren list expression");
  5913. Expr **exprs;
  5914. unsigned numExprs;
  5915. Expr *subExpr;
  5916. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5917. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5918. LiteralLParenLoc = PE->getLParenLoc();
  5919. LiteralRParenLoc = PE->getRParenLoc();
  5920. exprs = PE->getExprs();
  5921. numExprs = PE->getNumExprs();
  5922. } else { // isa<ParenExpr> by assertion at function entrance
  5923. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5924. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5925. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5926. exprs = &subExpr;
  5927. numExprs = 1;
  5928. }
  5929. QualType Ty = TInfo->getType();
  5930. assert(Ty->isVectorType() && "Expected vector type");
  5931. SmallVector<Expr *, 8> initExprs;
  5932. const VectorType *VTy = Ty->castAs<VectorType>();
  5933. unsigned numElems = VTy->getNumElements();
  5934. // '(...)' form of vector initialization in AltiVec: the number of
  5935. // initializers must be one or must match the size of the vector.
  5936. // If a single value is specified in the initializer then it will be
  5937. // replicated to all the components of the vector
  5938. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5939. // The number of initializers must be one or must match the size of the
  5940. // vector. If a single value is specified in the initializer then it will
  5941. // be replicated to all the components of the vector
  5942. if (numExprs == 1) {
  5943. QualType ElemTy = VTy->getElementType();
  5944. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5945. if (Literal.isInvalid())
  5946. return ExprError();
  5947. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5948. PrepareScalarCast(Literal, ElemTy));
  5949. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5950. }
  5951. else if (numExprs < numElems) {
  5952. Diag(E->getExprLoc(),
  5953. diag::err_incorrect_number_of_vector_initializers);
  5954. return ExprError();
  5955. }
  5956. else
  5957. initExprs.append(exprs, exprs + numExprs);
  5958. }
  5959. else {
  5960. // For OpenCL, when the number of initializers is a single value,
  5961. // it will be replicated to all components of the vector.
  5962. if (getLangOpts().OpenCL &&
  5963. VTy->getVectorKind() == VectorType::GenericVector &&
  5964. numExprs == 1) {
  5965. QualType ElemTy = VTy->getElementType();
  5966. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5967. if (Literal.isInvalid())
  5968. return ExprError();
  5969. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5970. PrepareScalarCast(Literal, ElemTy));
  5971. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5972. }
  5973. initExprs.append(exprs, exprs + numExprs);
  5974. }
  5975. // FIXME: This means that pretty-printing the final AST will produce curly
  5976. // braces instead of the original commas.
  5977. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5978. initExprs, LiteralRParenLoc);
  5979. initE->setType(Ty);
  5980. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5981. }
  5982. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5983. /// the ParenListExpr into a sequence of comma binary operators.
  5984. ExprResult
  5985. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5986. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5987. if (!E)
  5988. return OrigExpr;
  5989. ExprResult Result(E->getExpr(0));
  5990. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5991. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5992. E->getExpr(i));
  5993. if (Result.isInvalid()) return ExprError();
  5994. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5995. }
  5996. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5997. SourceLocation R,
  5998. MultiExprArg Val) {
  5999. return ParenListExpr::Create(Context, L, Val, R);
  6000. }
  6001. /// Emit a specialized diagnostic when one expression is a null pointer
  6002. /// constant and the other is not a pointer. Returns true if a diagnostic is
  6003. /// emitted.
  6004. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  6005. SourceLocation QuestionLoc) {
  6006. Expr *NullExpr = LHSExpr;
  6007. Expr *NonPointerExpr = RHSExpr;
  6008. Expr::NullPointerConstantKind NullKind =
  6009. NullExpr->isNullPointerConstant(Context,
  6010. Expr::NPC_ValueDependentIsNotNull);
  6011. if (NullKind == Expr::NPCK_NotNull) {
  6012. NullExpr = RHSExpr;
  6013. NonPointerExpr = LHSExpr;
  6014. NullKind =
  6015. NullExpr->isNullPointerConstant(Context,
  6016. Expr::NPC_ValueDependentIsNotNull);
  6017. }
  6018. if (NullKind == Expr::NPCK_NotNull)
  6019. return false;
  6020. if (NullKind == Expr::NPCK_ZeroExpression)
  6021. return false;
  6022. if (NullKind == Expr::NPCK_ZeroLiteral) {
  6023. // In this case, check to make sure that we got here from a "NULL"
  6024. // string in the source code.
  6025. NullExpr = NullExpr->IgnoreParenImpCasts();
  6026. SourceLocation loc = NullExpr->getExprLoc();
  6027. if (!findMacroSpelling(loc, "NULL"))
  6028. return false;
  6029. }
  6030. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  6031. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  6032. << NonPointerExpr->getType() << DiagType
  6033. << NonPointerExpr->getSourceRange();
  6034. return true;
  6035. }
  6036. /// Return false if the condition expression is valid, true otherwise.
  6037. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  6038. QualType CondTy = Cond->getType();
  6039. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  6040. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  6041. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6042. << CondTy << Cond->getSourceRange();
  6043. return true;
  6044. }
  6045. // C99 6.5.15p2
  6046. if (CondTy->isScalarType()) return false;
  6047. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  6048. << CondTy << Cond->getSourceRange();
  6049. return true;
  6050. }
  6051. /// Handle when one or both operands are void type.
  6052. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  6053. ExprResult &RHS) {
  6054. Expr *LHSExpr = LHS.get();
  6055. Expr *RHSExpr = RHS.get();
  6056. if (!LHSExpr->getType()->isVoidType())
  6057. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6058. << RHSExpr->getSourceRange();
  6059. if (!RHSExpr->getType()->isVoidType())
  6060. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6061. << LHSExpr->getSourceRange();
  6062. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  6063. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  6064. return S.Context.VoidTy;
  6065. }
  6066. /// Return false if the NullExpr can be promoted to PointerTy,
  6067. /// true otherwise.
  6068. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  6069. QualType PointerTy) {
  6070. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  6071. !NullExpr.get()->isNullPointerConstant(S.Context,
  6072. Expr::NPC_ValueDependentIsNull))
  6073. return true;
  6074. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  6075. return false;
  6076. }
  6077. /// Checks compatibility between two pointers and return the resulting
  6078. /// type.
  6079. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  6080. ExprResult &RHS,
  6081. SourceLocation Loc) {
  6082. QualType LHSTy = LHS.get()->getType();
  6083. QualType RHSTy = RHS.get()->getType();
  6084. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  6085. // Two identical pointers types are always compatible.
  6086. return LHSTy;
  6087. }
  6088. QualType lhptee, rhptee;
  6089. // Get the pointee types.
  6090. bool IsBlockPointer = false;
  6091. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  6092. lhptee = LHSBTy->getPointeeType();
  6093. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  6094. IsBlockPointer = true;
  6095. } else {
  6096. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  6097. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  6098. }
  6099. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  6100. // differently qualified versions of compatible types, the result type is
  6101. // a pointer to an appropriately qualified version of the composite
  6102. // type.
  6103. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  6104. // clause doesn't make sense for our extensions. E.g. address space 2 should
  6105. // be incompatible with address space 3: they may live on different devices or
  6106. // anything.
  6107. Qualifiers lhQual = lhptee.getQualifiers();
  6108. Qualifiers rhQual = rhptee.getQualifiers();
  6109. LangAS ResultAddrSpace = LangAS::Default;
  6110. LangAS LAddrSpace = lhQual.getAddressSpace();
  6111. LangAS RAddrSpace = rhQual.getAddressSpace();
  6112. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  6113. // spaces is disallowed.
  6114. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  6115. ResultAddrSpace = LAddrSpace;
  6116. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  6117. ResultAddrSpace = RAddrSpace;
  6118. else {
  6119. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6120. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  6121. << RHS.get()->getSourceRange();
  6122. return QualType();
  6123. }
  6124. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  6125. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  6126. lhQual.removeCVRQualifiers();
  6127. rhQual.removeCVRQualifiers();
  6128. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  6129. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  6130. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  6131. // qual types are compatible iff
  6132. // * corresponded types are compatible
  6133. // * CVR qualifiers are equal
  6134. // * address spaces are equal
  6135. // Thus for conditional operator we merge CVR and address space unqualified
  6136. // pointees and if there is a composite type we return a pointer to it with
  6137. // merged qualifiers.
  6138. LHSCastKind =
  6139. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6140. RHSCastKind =
  6141. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6142. lhQual.removeAddressSpace();
  6143. rhQual.removeAddressSpace();
  6144. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  6145. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  6146. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  6147. if (CompositeTy.isNull()) {
  6148. // In this situation, we assume void* type. No especially good
  6149. // reason, but this is what gcc does, and we do have to pick
  6150. // to get a consistent AST.
  6151. QualType incompatTy;
  6152. incompatTy = S.Context.getPointerType(
  6153. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  6154. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  6155. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  6156. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  6157. // for casts between types with incompatible address space qualifiers.
  6158. // For the following code the compiler produces casts between global and
  6159. // local address spaces of the corresponded innermost pointees:
  6160. // local int *global *a;
  6161. // global int *global *b;
  6162. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  6163. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  6164. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6165. << RHS.get()->getSourceRange();
  6166. return incompatTy;
  6167. }
  6168. // The pointer types are compatible.
  6169. // In case of OpenCL ResultTy should have the address space qualifier
  6170. // which is a superset of address spaces of both the 2nd and the 3rd
  6171. // operands of the conditional operator.
  6172. QualType ResultTy = [&, ResultAddrSpace]() {
  6173. if (S.getLangOpts().OpenCL) {
  6174. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  6175. CompositeQuals.setAddressSpace(ResultAddrSpace);
  6176. return S.Context
  6177. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  6178. .withCVRQualifiers(MergedCVRQual);
  6179. }
  6180. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  6181. }();
  6182. if (IsBlockPointer)
  6183. ResultTy = S.Context.getBlockPointerType(ResultTy);
  6184. else
  6185. ResultTy = S.Context.getPointerType(ResultTy);
  6186. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  6187. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  6188. return ResultTy;
  6189. }
  6190. /// Return the resulting type when the operands are both block pointers.
  6191. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  6192. ExprResult &LHS,
  6193. ExprResult &RHS,
  6194. SourceLocation Loc) {
  6195. QualType LHSTy = LHS.get()->getType();
  6196. QualType RHSTy = RHS.get()->getType();
  6197. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  6198. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  6199. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  6200. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6201. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6202. return destType;
  6203. }
  6204. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  6205. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6206. << RHS.get()->getSourceRange();
  6207. return QualType();
  6208. }
  6209. // We have 2 block pointer types.
  6210. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6211. }
  6212. /// Return the resulting type when the operands are both pointers.
  6213. static QualType
  6214. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  6215. ExprResult &RHS,
  6216. SourceLocation Loc) {
  6217. // get the pointer types
  6218. QualType LHSTy = LHS.get()->getType();
  6219. QualType RHSTy = RHS.get()->getType();
  6220. // get the "pointed to" types
  6221. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  6222. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  6223. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  6224. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  6225. // Figure out necessary qualifiers (C99 6.5.15p6)
  6226. QualType destPointee
  6227. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6228. QualType destType = S.Context.getPointerType(destPointee);
  6229. // Add qualifiers if necessary.
  6230. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6231. // Promote to void*.
  6232. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6233. return destType;
  6234. }
  6235. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  6236. QualType destPointee
  6237. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6238. QualType destType = S.Context.getPointerType(destPointee);
  6239. // Add qualifiers if necessary.
  6240. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6241. // Promote to void*.
  6242. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6243. return destType;
  6244. }
  6245. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6246. }
  6247. /// Return false if the first expression is not an integer and the second
  6248. /// expression is not a pointer, true otherwise.
  6249. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  6250. Expr* PointerExpr, SourceLocation Loc,
  6251. bool IsIntFirstExpr) {
  6252. if (!PointerExpr->getType()->isPointerType() ||
  6253. !Int.get()->getType()->isIntegerType())
  6254. return false;
  6255. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  6256. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  6257. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  6258. << Expr1->getType() << Expr2->getType()
  6259. << Expr1->getSourceRange() << Expr2->getSourceRange();
  6260. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  6261. CK_IntegralToPointer);
  6262. return true;
  6263. }
  6264. /// Simple conversion between integer and floating point types.
  6265. ///
  6266. /// Used when handling the OpenCL conditional operator where the
  6267. /// condition is a vector while the other operands are scalar.
  6268. ///
  6269. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  6270. /// types are either integer or floating type. Between the two
  6271. /// operands, the type with the higher rank is defined as the "result
  6272. /// type". The other operand needs to be promoted to the same type. No
  6273. /// other type promotion is allowed. We cannot use
  6274. /// UsualArithmeticConversions() for this purpose, since it always
  6275. /// promotes promotable types.
  6276. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  6277. ExprResult &RHS,
  6278. SourceLocation QuestionLoc) {
  6279. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  6280. if (LHS.isInvalid())
  6281. return QualType();
  6282. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  6283. if (RHS.isInvalid())
  6284. return QualType();
  6285. // For conversion purposes, we ignore any qualifiers.
  6286. // For example, "const float" and "float" are equivalent.
  6287. QualType LHSType =
  6288. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  6289. QualType RHSType =
  6290. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  6291. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  6292. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6293. << LHSType << LHS.get()->getSourceRange();
  6294. return QualType();
  6295. }
  6296. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  6297. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6298. << RHSType << RHS.get()->getSourceRange();
  6299. return QualType();
  6300. }
  6301. // If both types are identical, no conversion is needed.
  6302. if (LHSType == RHSType)
  6303. return LHSType;
  6304. // Now handle "real" floating types (i.e. float, double, long double).
  6305. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  6306. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  6307. /*IsCompAssign = */ false);
  6308. // Finally, we have two differing integer types.
  6309. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  6310. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  6311. }
  6312. /// Convert scalar operands to a vector that matches the
  6313. /// condition in length.
  6314. ///
  6315. /// Used when handling the OpenCL conditional operator where the
  6316. /// condition is a vector while the other operands are scalar.
  6317. ///
  6318. /// We first compute the "result type" for the scalar operands
  6319. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  6320. /// into a vector of that type where the length matches the condition
  6321. /// vector type. s6.11.6 requires that the element types of the result
  6322. /// and the condition must have the same number of bits.
  6323. static QualType
  6324. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6325. QualType CondTy, SourceLocation QuestionLoc) {
  6326. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  6327. if (ResTy.isNull()) return QualType();
  6328. const VectorType *CV = CondTy->getAs<VectorType>();
  6329. assert(CV);
  6330. // Determine the vector result type
  6331. unsigned NumElements = CV->getNumElements();
  6332. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  6333. // Ensure that all types have the same number of bits
  6334. if (S.Context.getTypeSize(CV->getElementType())
  6335. != S.Context.getTypeSize(ResTy)) {
  6336. // Since VectorTy is created internally, it does not pretty print
  6337. // with an OpenCL name. Instead, we just print a description.
  6338. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  6339. SmallString<64> Str;
  6340. llvm::raw_svector_ostream OS(Str);
  6341. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  6342. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6343. << CondTy << OS.str();
  6344. return QualType();
  6345. }
  6346. // Convert operands to the vector result type
  6347. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  6348. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  6349. return VectorTy;
  6350. }
  6351. /// Return false if this is a valid OpenCL condition vector
  6352. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  6353. SourceLocation QuestionLoc) {
  6354. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  6355. // integral type.
  6356. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  6357. assert(CondTy);
  6358. QualType EleTy = CondTy->getElementType();
  6359. if (EleTy->isIntegerType()) return false;
  6360. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6361. << Cond->getType() << Cond->getSourceRange();
  6362. return true;
  6363. }
  6364. /// Return false if the vector condition type and the vector
  6365. /// result type are compatible.
  6366. ///
  6367. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  6368. /// number of elements, and their element types have the same number
  6369. /// of bits.
  6370. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  6371. SourceLocation QuestionLoc) {
  6372. const VectorType *CV = CondTy->getAs<VectorType>();
  6373. const VectorType *RV = VecResTy->getAs<VectorType>();
  6374. assert(CV && RV);
  6375. if (CV->getNumElements() != RV->getNumElements()) {
  6376. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  6377. << CondTy << VecResTy;
  6378. return true;
  6379. }
  6380. QualType CVE = CV->getElementType();
  6381. QualType RVE = RV->getElementType();
  6382. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  6383. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6384. << CondTy << VecResTy;
  6385. return true;
  6386. }
  6387. return false;
  6388. }
  6389. /// Return the resulting type for the conditional operator in
  6390. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6391. /// s6.3.i) when the condition is a vector type.
  6392. static QualType
  6393. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6394. ExprResult &LHS, ExprResult &RHS,
  6395. SourceLocation QuestionLoc) {
  6396. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6397. if (Cond.isInvalid())
  6398. return QualType();
  6399. QualType CondTy = Cond.get()->getType();
  6400. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6401. return QualType();
  6402. // If either operand is a vector then find the vector type of the
  6403. // result as specified in OpenCL v1.1 s6.3.i.
  6404. if (LHS.get()->getType()->isVectorType() ||
  6405. RHS.get()->getType()->isVectorType()) {
  6406. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6407. /*isCompAssign*/false,
  6408. /*AllowBothBool*/true,
  6409. /*AllowBoolConversions*/false);
  6410. if (VecResTy.isNull()) return QualType();
  6411. // The result type must match the condition type as specified in
  6412. // OpenCL v1.1 s6.11.6.
  6413. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6414. return QualType();
  6415. return VecResTy;
  6416. }
  6417. // Both operands are scalar.
  6418. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6419. }
  6420. /// Return true if the Expr is block type
  6421. static bool checkBlockType(Sema &S, const Expr *E) {
  6422. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6423. QualType Ty = CE->getCallee()->getType();
  6424. if (Ty->isBlockPointerType()) {
  6425. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6426. return true;
  6427. }
  6428. }
  6429. return false;
  6430. }
  6431. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6432. /// In that case, LHS = cond.
  6433. /// C99 6.5.15
  6434. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6435. ExprResult &RHS, ExprValueKind &VK,
  6436. ExprObjectKind &OK,
  6437. SourceLocation QuestionLoc) {
  6438. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6439. if (!LHSResult.isUsable()) return QualType();
  6440. LHS = LHSResult;
  6441. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6442. if (!RHSResult.isUsable()) return QualType();
  6443. RHS = RHSResult;
  6444. // C++ is sufficiently different to merit its own checker.
  6445. if (getLangOpts().CPlusPlus)
  6446. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6447. VK = VK_RValue;
  6448. OK = OK_Ordinary;
  6449. // The OpenCL operator with a vector condition is sufficiently
  6450. // different to merit its own checker.
  6451. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6452. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6453. // First, check the condition.
  6454. Cond = UsualUnaryConversions(Cond.get());
  6455. if (Cond.isInvalid())
  6456. return QualType();
  6457. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6458. return QualType();
  6459. // Now check the two expressions.
  6460. if (LHS.get()->getType()->isVectorType() ||
  6461. RHS.get()->getType()->isVectorType())
  6462. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6463. /*AllowBothBool*/true,
  6464. /*AllowBoolConversions*/false);
  6465. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6466. if (LHS.isInvalid() || RHS.isInvalid())
  6467. return QualType();
  6468. QualType LHSTy = LHS.get()->getType();
  6469. QualType RHSTy = RHS.get()->getType();
  6470. // Diagnose attempts to convert between __float128 and long double where
  6471. // such conversions currently can't be handled.
  6472. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6473. Diag(QuestionLoc,
  6474. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6475. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6476. return QualType();
  6477. }
  6478. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6479. // selection operator (?:).
  6480. if (getLangOpts().OpenCL &&
  6481. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6482. return QualType();
  6483. }
  6484. // If both operands have arithmetic type, do the usual arithmetic conversions
  6485. // to find a common type: C99 6.5.15p3,5.
  6486. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6487. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6488. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6489. return ResTy;
  6490. }
  6491. // If both operands are the same structure or union type, the result is that
  6492. // type.
  6493. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6494. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6495. if (LHSRT->getDecl() == RHSRT->getDecl())
  6496. // "If both the operands have structure or union type, the result has
  6497. // that type." This implies that CV qualifiers are dropped.
  6498. return LHSTy.getUnqualifiedType();
  6499. // FIXME: Type of conditional expression must be complete in C mode.
  6500. }
  6501. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6502. // The following || allows only one side to be void (a GCC-ism).
  6503. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6504. return checkConditionalVoidType(*this, LHS, RHS);
  6505. }
  6506. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6507. // the type of the other operand."
  6508. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6509. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6510. // All objective-c pointer type analysis is done here.
  6511. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6512. QuestionLoc);
  6513. if (LHS.isInvalid() || RHS.isInvalid())
  6514. return QualType();
  6515. if (!compositeType.isNull())
  6516. return compositeType;
  6517. // Handle block pointer types.
  6518. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6519. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6520. QuestionLoc);
  6521. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6522. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6523. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6524. QuestionLoc);
  6525. // GCC compatibility: soften pointer/integer mismatch. Note that
  6526. // null pointers have been filtered out by this point.
  6527. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6528. /*IsIntFirstExpr=*/true))
  6529. return RHSTy;
  6530. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6531. /*IsIntFirstExpr=*/false))
  6532. return LHSTy;
  6533. // Emit a better diagnostic if one of the expressions is a null pointer
  6534. // constant and the other is not a pointer type. In this case, the user most
  6535. // likely forgot to take the address of the other expression.
  6536. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6537. return QualType();
  6538. // Otherwise, the operands are not compatible.
  6539. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6540. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6541. << RHS.get()->getSourceRange();
  6542. return QualType();
  6543. }
  6544. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6545. /// two objective-c pointer types of the two input expressions.
  6546. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6547. SourceLocation QuestionLoc) {
  6548. QualType LHSTy = LHS.get()->getType();
  6549. QualType RHSTy = RHS.get()->getType();
  6550. // Handle things like Class and struct objc_class*. Here we case the result
  6551. // to the pseudo-builtin, because that will be implicitly cast back to the
  6552. // redefinition type if an attempt is made to access its fields.
  6553. if (LHSTy->isObjCClassType() &&
  6554. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6555. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6556. return LHSTy;
  6557. }
  6558. if (RHSTy->isObjCClassType() &&
  6559. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6560. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6561. return RHSTy;
  6562. }
  6563. // And the same for struct objc_object* / id
  6564. if (LHSTy->isObjCIdType() &&
  6565. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6566. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6567. return LHSTy;
  6568. }
  6569. if (RHSTy->isObjCIdType() &&
  6570. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6571. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6572. return RHSTy;
  6573. }
  6574. // And the same for struct objc_selector* / SEL
  6575. if (Context.isObjCSelType(LHSTy) &&
  6576. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6577. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6578. return LHSTy;
  6579. }
  6580. if (Context.isObjCSelType(RHSTy) &&
  6581. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6582. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6583. return RHSTy;
  6584. }
  6585. // Check constraints for Objective-C object pointers types.
  6586. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6587. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6588. // Two identical object pointer types are always compatible.
  6589. return LHSTy;
  6590. }
  6591. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6592. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6593. QualType compositeType = LHSTy;
  6594. // If both operands are interfaces and either operand can be
  6595. // assigned to the other, use that type as the composite
  6596. // type. This allows
  6597. // xxx ? (A*) a : (B*) b
  6598. // where B is a subclass of A.
  6599. //
  6600. // Additionally, as for assignment, if either type is 'id'
  6601. // allow silent coercion. Finally, if the types are
  6602. // incompatible then make sure to use 'id' as the composite
  6603. // type so the result is acceptable for sending messages to.
  6604. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6605. // It could return the composite type.
  6606. if (!(compositeType =
  6607. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6608. // Nothing more to do.
  6609. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6610. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6611. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6612. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6613. } else if ((LHSOPT->isObjCQualifiedIdType() ||
  6614. RHSOPT->isObjCQualifiedIdType()) &&
  6615. Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
  6616. true)) {
  6617. // Need to handle "id<xx>" explicitly.
  6618. // GCC allows qualified id and any Objective-C type to devolve to
  6619. // id. Currently localizing to here until clear this should be
  6620. // part of ObjCQualifiedIdTypesAreCompatible.
  6621. compositeType = Context.getObjCIdType();
  6622. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6623. compositeType = Context.getObjCIdType();
  6624. } else {
  6625. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6626. << LHSTy << RHSTy
  6627. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6628. QualType incompatTy = Context.getObjCIdType();
  6629. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6630. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6631. return incompatTy;
  6632. }
  6633. // The object pointer types are compatible.
  6634. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6635. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6636. return compositeType;
  6637. }
  6638. // Check Objective-C object pointer types and 'void *'
  6639. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6640. if (getLangOpts().ObjCAutoRefCount) {
  6641. // ARC forbids the implicit conversion of object pointers to 'void *',
  6642. // so these types are not compatible.
  6643. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6644. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6645. LHS = RHS = true;
  6646. return QualType();
  6647. }
  6648. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  6649. QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  6650. QualType destPointee
  6651. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6652. QualType destType = Context.getPointerType(destPointee);
  6653. // Add qualifiers if necessary.
  6654. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6655. // Promote to void*.
  6656. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6657. return destType;
  6658. }
  6659. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6660. if (getLangOpts().ObjCAutoRefCount) {
  6661. // ARC forbids the implicit conversion of object pointers to 'void *',
  6662. // so these types are not compatible.
  6663. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6664. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6665. LHS = RHS = true;
  6666. return QualType();
  6667. }
  6668. QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  6669. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  6670. QualType destPointee
  6671. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6672. QualType destType = Context.getPointerType(destPointee);
  6673. // Add qualifiers if necessary.
  6674. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6675. // Promote to void*.
  6676. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6677. return destType;
  6678. }
  6679. return QualType();
  6680. }
  6681. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6682. /// ParenRange in parentheses.
  6683. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6684. const PartialDiagnostic &Note,
  6685. SourceRange ParenRange) {
  6686. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6687. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6688. EndLoc.isValid()) {
  6689. Self.Diag(Loc, Note)
  6690. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6691. << FixItHint::CreateInsertion(EndLoc, ")");
  6692. } else {
  6693. // We can't display the parentheses, so just show the bare note.
  6694. Self.Diag(Loc, Note) << ParenRange;
  6695. }
  6696. }
  6697. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6698. return BinaryOperator::isAdditiveOp(Opc) ||
  6699. BinaryOperator::isMultiplicativeOp(Opc) ||
  6700. BinaryOperator::isShiftOp(Opc);
  6701. }
  6702. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6703. /// expression, either using a built-in or overloaded operator,
  6704. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6705. /// expression.
  6706. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6707. Expr **RHSExprs) {
  6708. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6709. E = E->IgnoreImpCasts();
  6710. E = E->IgnoreConversionOperator();
  6711. E = E->IgnoreImpCasts();
  6712. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6713. E = MTE->GetTemporaryExpr();
  6714. E = E->IgnoreImpCasts();
  6715. }
  6716. // Built-in binary operator.
  6717. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6718. if (IsArithmeticOp(OP->getOpcode())) {
  6719. *Opcode = OP->getOpcode();
  6720. *RHSExprs = OP->getRHS();
  6721. return true;
  6722. }
  6723. }
  6724. // Overloaded operator.
  6725. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6726. if (Call->getNumArgs() != 2)
  6727. return false;
  6728. // Make sure this is really a binary operator that is safe to pass into
  6729. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6730. OverloadedOperatorKind OO = Call->getOperator();
  6731. if (OO < OO_Plus || OO > OO_Arrow ||
  6732. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6733. return false;
  6734. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6735. if (IsArithmeticOp(OpKind)) {
  6736. *Opcode = OpKind;
  6737. *RHSExprs = Call->getArg(1);
  6738. return true;
  6739. }
  6740. }
  6741. return false;
  6742. }
  6743. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6744. /// or is a logical expression such as (x==y) which has int type, but is
  6745. /// commonly interpreted as boolean.
  6746. static bool ExprLooksBoolean(Expr *E) {
  6747. E = E->IgnoreParenImpCasts();
  6748. if (E->getType()->isBooleanType())
  6749. return true;
  6750. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6751. return OP->isComparisonOp() || OP->isLogicalOp();
  6752. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6753. return OP->getOpcode() == UO_LNot;
  6754. if (E->getType()->isPointerType())
  6755. return true;
  6756. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6757. // type"s (commonly pointer-to-members)?
  6758. return false;
  6759. }
  6760. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6761. /// and binary operator are mixed in a way that suggests the programmer assumed
  6762. /// the conditional operator has higher precedence, for example:
  6763. /// "int x = a + someBinaryCondition ? 1 : 2".
  6764. static void DiagnoseConditionalPrecedence(Sema &Self,
  6765. SourceLocation OpLoc,
  6766. Expr *Condition,
  6767. Expr *LHSExpr,
  6768. Expr *RHSExpr) {
  6769. BinaryOperatorKind CondOpcode;
  6770. Expr *CondRHS;
  6771. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6772. return;
  6773. if (!ExprLooksBoolean(CondRHS))
  6774. return;
  6775. // The condition is an arithmetic binary expression, with a right-
  6776. // hand side that looks boolean, so warn.
  6777. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6778. << Condition->getSourceRange()
  6779. << BinaryOperator::getOpcodeStr(CondOpcode);
  6780. SuggestParentheses(
  6781. Self, OpLoc,
  6782. Self.PDiag(diag::note_precedence_silence)
  6783. << BinaryOperator::getOpcodeStr(CondOpcode),
  6784. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6785. SuggestParentheses(Self, OpLoc,
  6786. Self.PDiag(diag::note_precedence_conditional_first),
  6787. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6788. }
  6789. /// Compute the nullability of a conditional expression.
  6790. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6791. QualType LHSTy, QualType RHSTy,
  6792. ASTContext &Ctx) {
  6793. if (!ResTy->isAnyPointerType())
  6794. return ResTy;
  6795. auto GetNullability = [&Ctx](QualType Ty) {
  6796. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6797. if (Kind)
  6798. return *Kind;
  6799. return NullabilityKind::Unspecified;
  6800. };
  6801. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6802. NullabilityKind MergedKind;
  6803. // Compute nullability of a binary conditional expression.
  6804. if (IsBin) {
  6805. if (LHSKind == NullabilityKind::NonNull)
  6806. MergedKind = NullabilityKind::NonNull;
  6807. else
  6808. MergedKind = RHSKind;
  6809. // Compute nullability of a normal conditional expression.
  6810. } else {
  6811. if (LHSKind == NullabilityKind::Nullable ||
  6812. RHSKind == NullabilityKind::Nullable)
  6813. MergedKind = NullabilityKind::Nullable;
  6814. else if (LHSKind == NullabilityKind::NonNull)
  6815. MergedKind = RHSKind;
  6816. else if (RHSKind == NullabilityKind::NonNull)
  6817. MergedKind = LHSKind;
  6818. else
  6819. MergedKind = NullabilityKind::Unspecified;
  6820. }
  6821. // Return if ResTy already has the correct nullability.
  6822. if (GetNullability(ResTy) == MergedKind)
  6823. return ResTy;
  6824. // Strip all nullability from ResTy.
  6825. while (ResTy->getNullability(Ctx))
  6826. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6827. // Create a new AttributedType with the new nullability kind.
  6828. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6829. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6830. }
  6831. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6832. /// in the case of a the GNU conditional expr extension.
  6833. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6834. SourceLocation ColonLoc,
  6835. Expr *CondExpr, Expr *LHSExpr,
  6836. Expr *RHSExpr) {
  6837. if (!getLangOpts().CPlusPlus) {
  6838. // C cannot handle TypoExpr nodes in the condition because it
  6839. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6840. // been dealt with before checking the operands.
  6841. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6842. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6843. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6844. if (!CondResult.isUsable())
  6845. return ExprError();
  6846. if (LHSExpr) {
  6847. if (!LHSResult.isUsable())
  6848. return ExprError();
  6849. }
  6850. if (!RHSResult.isUsable())
  6851. return ExprError();
  6852. CondExpr = CondResult.get();
  6853. LHSExpr = LHSResult.get();
  6854. RHSExpr = RHSResult.get();
  6855. }
  6856. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6857. // was the condition.
  6858. OpaqueValueExpr *opaqueValue = nullptr;
  6859. Expr *commonExpr = nullptr;
  6860. if (!LHSExpr) {
  6861. commonExpr = CondExpr;
  6862. // Lower out placeholder types first. This is important so that we don't
  6863. // try to capture a placeholder. This happens in few cases in C++; such
  6864. // as Objective-C++'s dictionary subscripting syntax.
  6865. if (commonExpr->hasPlaceholderType()) {
  6866. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6867. if (!result.isUsable()) return ExprError();
  6868. commonExpr = result.get();
  6869. }
  6870. // We usually want to apply unary conversions *before* saving, except
  6871. // in the special case of a C++ l-value conditional.
  6872. if (!(getLangOpts().CPlusPlus
  6873. && !commonExpr->isTypeDependent()
  6874. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6875. && commonExpr->isGLValue()
  6876. && commonExpr->isOrdinaryOrBitFieldObject()
  6877. && RHSExpr->isOrdinaryOrBitFieldObject()
  6878. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6879. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6880. if (commonRes.isInvalid())
  6881. return ExprError();
  6882. commonExpr = commonRes.get();
  6883. }
  6884. // If the common expression is a class or array prvalue, materialize it
  6885. // so that we can safely refer to it multiple times.
  6886. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6887. commonExpr->getType()->isArrayType())) {
  6888. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6889. if (MatExpr.isInvalid())
  6890. return ExprError();
  6891. commonExpr = MatExpr.get();
  6892. }
  6893. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6894. commonExpr->getType(),
  6895. commonExpr->getValueKind(),
  6896. commonExpr->getObjectKind(),
  6897. commonExpr);
  6898. LHSExpr = CondExpr = opaqueValue;
  6899. }
  6900. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6901. ExprValueKind VK = VK_RValue;
  6902. ExprObjectKind OK = OK_Ordinary;
  6903. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6904. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6905. VK, OK, QuestionLoc);
  6906. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6907. RHS.isInvalid())
  6908. return ExprError();
  6909. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6910. RHS.get());
  6911. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6912. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6913. Context);
  6914. if (!commonExpr)
  6915. return new (Context)
  6916. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6917. RHS.get(), result, VK, OK);
  6918. return new (Context) BinaryConditionalOperator(
  6919. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6920. ColonLoc, result, VK, OK);
  6921. }
  6922. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6923. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6924. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6925. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6926. // FIXME: add a couple examples in this comment.
  6927. static Sema::AssignConvertType
  6928. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6929. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6930. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6931. // get the "pointed to" type (ignoring qualifiers at the top level)
  6932. const Type *lhptee, *rhptee;
  6933. Qualifiers lhq, rhq;
  6934. std::tie(lhptee, lhq) =
  6935. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6936. std::tie(rhptee, rhq) =
  6937. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6938. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6939. // C99 6.5.16.1p1: This following citation is common to constraints
  6940. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6941. // qualifiers of the type *pointed to* by the right;
  6942. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6943. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6944. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6945. // Ignore lifetime for further calculation.
  6946. lhq.removeObjCLifetime();
  6947. rhq.removeObjCLifetime();
  6948. }
  6949. if (!lhq.compatiblyIncludes(rhq)) {
  6950. // Treat address-space mismatches as fatal.
  6951. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6952. return Sema::IncompatiblePointerDiscardsQualifiers;
  6953. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6954. // and from void*.
  6955. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6956. .compatiblyIncludes(
  6957. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6958. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6959. ; // keep old
  6960. // Treat lifetime mismatches as fatal.
  6961. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6962. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6963. // For GCC/MS compatibility, other qualifier mismatches are treated
  6964. // as still compatible in C.
  6965. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6966. }
  6967. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6968. // incomplete type and the other is a pointer to a qualified or unqualified
  6969. // version of void...
  6970. if (lhptee->isVoidType()) {
  6971. if (rhptee->isIncompleteOrObjectType())
  6972. return ConvTy;
  6973. // As an extension, we allow cast to/from void* to function pointer.
  6974. assert(rhptee->isFunctionType());
  6975. return Sema::FunctionVoidPointer;
  6976. }
  6977. if (rhptee->isVoidType()) {
  6978. if (lhptee->isIncompleteOrObjectType())
  6979. return ConvTy;
  6980. // As an extension, we allow cast to/from void* to function pointer.
  6981. assert(lhptee->isFunctionType());
  6982. return Sema::FunctionVoidPointer;
  6983. }
  6984. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6985. // unqualified versions of compatible types, ...
  6986. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6987. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6988. // Check if the pointee types are compatible ignoring the sign.
  6989. // We explicitly check for char so that we catch "char" vs
  6990. // "unsigned char" on systems where "char" is unsigned.
  6991. if (lhptee->isCharType())
  6992. ltrans = S.Context.UnsignedCharTy;
  6993. else if (lhptee->hasSignedIntegerRepresentation())
  6994. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6995. if (rhptee->isCharType())
  6996. rtrans = S.Context.UnsignedCharTy;
  6997. else if (rhptee->hasSignedIntegerRepresentation())
  6998. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6999. if (ltrans == rtrans) {
  7000. // Types are compatible ignoring the sign. Qualifier incompatibility
  7001. // takes priority over sign incompatibility because the sign
  7002. // warning can be disabled.
  7003. if (ConvTy != Sema::Compatible)
  7004. return ConvTy;
  7005. return Sema::IncompatiblePointerSign;
  7006. }
  7007. // If we are a multi-level pointer, it's possible that our issue is simply
  7008. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  7009. // the eventual target type is the same and the pointers have the same
  7010. // level of indirection, this must be the issue.
  7011. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  7012. do {
  7013. std::tie(lhptee, lhq) =
  7014. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  7015. std::tie(rhptee, rhq) =
  7016. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  7017. // Inconsistent address spaces at this point is invalid, even if the
  7018. // address spaces would be compatible.
  7019. // FIXME: This doesn't catch address space mismatches for pointers of
  7020. // different nesting levels, like:
  7021. // __local int *** a;
  7022. // int ** b = a;
  7023. // It's not clear how to actually determine when such pointers are
  7024. // invalidly incompatible.
  7025. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  7026. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  7027. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  7028. if (lhptee == rhptee)
  7029. return Sema::IncompatibleNestedPointerQualifiers;
  7030. }
  7031. // General pointer incompatibility takes priority over qualifiers.
  7032. return Sema::IncompatiblePointer;
  7033. }
  7034. if (!S.getLangOpts().CPlusPlus &&
  7035. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  7036. return Sema::IncompatiblePointer;
  7037. return ConvTy;
  7038. }
  7039. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  7040. /// block pointer types are compatible or whether a block and normal pointer
  7041. /// are compatible. It is more restrict than comparing two function pointer
  7042. // types.
  7043. static Sema::AssignConvertType
  7044. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  7045. QualType RHSType) {
  7046. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  7047. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  7048. QualType lhptee, rhptee;
  7049. // get the "pointed to" type (ignoring qualifiers at the top level)
  7050. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  7051. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  7052. // In C++, the types have to match exactly.
  7053. if (S.getLangOpts().CPlusPlus)
  7054. return Sema::IncompatibleBlockPointer;
  7055. Sema::AssignConvertType ConvTy = Sema::Compatible;
  7056. // For blocks we enforce that qualifiers are identical.
  7057. Qualifiers LQuals = lhptee.getLocalQualifiers();
  7058. Qualifiers RQuals = rhptee.getLocalQualifiers();
  7059. if (S.getLangOpts().OpenCL) {
  7060. LQuals.removeAddressSpace();
  7061. RQuals.removeAddressSpace();
  7062. }
  7063. if (LQuals != RQuals)
  7064. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  7065. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  7066. // assignment.
  7067. // The current behavior is similar to C++ lambdas. A block might be
  7068. // assigned to a variable iff its return type and parameters are compatible
  7069. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  7070. // an assignment. Presumably it should behave in way that a function pointer
  7071. // assignment does in C, so for each parameter and return type:
  7072. // * CVR and address space of LHS should be a superset of CVR and address
  7073. // space of RHS.
  7074. // * unqualified types should be compatible.
  7075. if (S.getLangOpts().OpenCL) {
  7076. if (!S.Context.typesAreBlockPointerCompatible(
  7077. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  7078. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  7079. return Sema::IncompatibleBlockPointer;
  7080. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  7081. return Sema::IncompatibleBlockPointer;
  7082. return ConvTy;
  7083. }
  7084. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  7085. /// for assignment compatibility.
  7086. static Sema::AssignConvertType
  7087. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  7088. QualType RHSType) {
  7089. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  7090. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  7091. if (LHSType->isObjCBuiltinType()) {
  7092. // Class is not compatible with ObjC object pointers.
  7093. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  7094. !RHSType->isObjCQualifiedClassType())
  7095. return Sema::IncompatiblePointer;
  7096. return Sema::Compatible;
  7097. }
  7098. if (RHSType->isObjCBuiltinType()) {
  7099. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  7100. !LHSType->isObjCQualifiedClassType())
  7101. return Sema::IncompatiblePointer;
  7102. return Sema::Compatible;
  7103. }
  7104. QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  7105. QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  7106. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  7107. // make an exception for id<P>
  7108. !LHSType->isObjCQualifiedIdType())
  7109. return Sema::CompatiblePointerDiscardsQualifiers;
  7110. if (S.Context.typesAreCompatible(LHSType, RHSType))
  7111. return Sema::Compatible;
  7112. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  7113. return Sema::IncompatibleObjCQualifiedId;
  7114. return Sema::IncompatiblePointer;
  7115. }
  7116. Sema::AssignConvertType
  7117. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  7118. QualType LHSType, QualType RHSType) {
  7119. // Fake up an opaque expression. We don't actually care about what
  7120. // cast operations are required, so if CheckAssignmentConstraints
  7121. // adds casts to this they'll be wasted, but fortunately that doesn't
  7122. // usually happen on valid code.
  7123. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  7124. ExprResult RHSPtr = &RHSExpr;
  7125. CastKind K;
  7126. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  7127. }
  7128. /// This helper function returns true if QT is a vector type that has element
  7129. /// type ElementType.
  7130. static bool isVector(QualType QT, QualType ElementType) {
  7131. if (const VectorType *VT = QT->getAs<VectorType>())
  7132. return VT->getElementType() == ElementType;
  7133. return false;
  7134. }
  7135. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  7136. /// has code to accommodate several GCC extensions when type checking
  7137. /// pointers. Here are some objectionable examples that GCC considers warnings:
  7138. ///
  7139. /// int a, *pint;
  7140. /// short *pshort;
  7141. /// struct foo *pfoo;
  7142. ///
  7143. /// pint = pshort; // warning: assignment from incompatible pointer type
  7144. /// a = pint; // warning: assignment makes integer from pointer without a cast
  7145. /// pint = a; // warning: assignment makes pointer from integer without a cast
  7146. /// pint = pfoo; // warning: assignment from incompatible pointer type
  7147. ///
  7148. /// As a result, the code for dealing with pointers is more complex than the
  7149. /// C99 spec dictates.
  7150. ///
  7151. /// Sets 'Kind' for any result kind except Incompatible.
  7152. Sema::AssignConvertType
  7153. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  7154. CastKind &Kind, bool ConvertRHS) {
  7155. QualType RHSType = RHS.get()->getType();
  7156. QualType OrigLHSType = LHSType;
  7157. // Get canonical types. We're not formatting these types, just comparing
  7158. // them.
  7159. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  7160. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  7161. // Common case: no conversion required.
  7162. if (LHSType == RHSType) {
  7163. Kind = CK_NoOp;
  7164. return Compatible;
  7165. }
  7166. // If we have an atomic type, try a non-atomic assignment, then just add an
  7167. // atomic qualification step.
  7168. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  7169. Sema::AssignConvertType result =
  7170. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  7171. if (result != Compatible)
  7172. return result;
  7173. if (Kind != CK_NoOp && ConvertRHS)
  7174. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  7175. Kind = CK_NonAtomicToAtomic;
  7176. return Compatible;
  7177. }
  7178. // If the left-hand side is a reference type, then we are in a
  7179. // (rare!) case where we've allowed the use of references in C,
  7180. // e.g., as a parameter type in a built-in function. In this case,
  7181. // just make sure that the type referenced is compatible with the
  7182. // right-hand side type. The caller is responsible for adjusting
  7183. // LHSType so that the resulting expression does not have reference
  7184. // type.
  7185. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7186. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7187. Kind = CK_LValueBitCast;
  7188. return Compatible;
  7189. }
  7190. return Incompatible;
  7191. }
  7192. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7193. // to the same ExtVector type.
  7194. if (LHSType->isExtVectorType()) {
  7195. if (RHSType->isExtVectorType())
  7196. return Incompatible;
  7197. if (RHSType->isArithmeticType()) {
  7198. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7199. if (ConvertRHS)
  7200. RHS = prepareVectorSplat(LHSType, RHS.get());
  7201. Kind = CK_VectorSplat;
  7202. return Compatible;
  7203. }
  7204. }
  7205. // Conversions to or from vector type.
  7206. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7207. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7208. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7209. // vector type and vice versa
  7210. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7211. Kind = CK_BitCast;
  7212. return Compatible;
  7213. }
  7214. // If we are allowing lax vector conversions, and LHS and RHS are both
  7215. // vectors, the total size only needs to be the same. This is a bitcast;
  7216. // no bits are changed but the result type is different.
  7217. if (isLaxVectorConversion(RHSType, LHSType)) {
  7218. Kind = CK_BitCast;
  7219. return IncompatibleVectors;
  7220. }
  7221. }
  7222. // When the RHS comes from another lax conversion (e.g. binops between
  7223. // scalars and vectors) the result is canonicalized as a vector. When the
  7224. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7225. // the case where LHS is a scalar.
  7226. if (LHSType->isScalarType()) {
  7227. const VectorType *VecType = RHSType->getAs<VectorType>();
  7228. if (VecType && VecType->getNumElements() == 1 &&
  7229. isLaxVectorConversion(RHSType, LHSType)) {
  7230. ExprResult *VecExpr = &RHS;
  7231. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7232. Kind = CK_BitCast;
  7233. return Compatible;
  7234. }
  7235. }
  7236. return Incompatible;
  7237. }
  7238. // Diagnose attempts to convert between __float128 and long double where
  7239. // such conversions currently can't be handled.
  7240. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7241. return Incompatible;
  7242. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7243. // discards the imaginary part.
  7244. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7245. !LHSType->getAs<ComplexType>())
  7246. return Incompatible;
  7247. // Arithmetic conversions.
  7248. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7249. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7250. if (ConvertRHS)
  7251. Kind = PrepareScalarCast(RHS, LHSType);
  7252. return Compatible;
  7253. }
  7254. // Conversions to normal pointers.
  7255. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7256. // U* -> T*
  7257. if (isa<PointerType>(RHSType)) {
  7258. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7259. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7260. if (AddrSpaceL != AddrSpaceR)
  7261. Kind = CK_AddressSpaceConversion;
  7262. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7263. Kind = CK_NoOp;
  7264. else
  7265. Kind = CK_BitCast;
  7266. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7267. }
  7268. // int -> T*
  7269. if (RHSType->isIntegerType()) {
  7270. Kind = CK_IntegralToPointer; // FIXME: null?
  7271. return IntToPointer;
  7272. }
  7273. // C pointers are not compatible with ObjC object pointers,
  7274. // with two exceptions:
  7275. if (isa<ObjCObjectPointerType>(RHSType)) {
  7276. // - conversions to void*
  7277. if (LHSPointer->getPointeeType()->isVoidType()) {
  7278. Kind = CK_BitCast;
  7279. return Compatible;
  7280. }
  7281. // - conversions from 'Class' to the redefinition type
  7282. if (RHSType->isObjCClassType() &&
  7283. Context.hasSameType(LHSType,
  7284. Context.getObjCClassRedefinitionType())) {
  7285. Kind = CK_BitCast;
  7286. return Compatible;
  7287. }
  7288. Kind = CK_BitCast;
  7289. return IncompatiblePointer;
  7290. }
  7291. // U^ -> void*
  7292. if (RHSType->getAs<BlockPointerType>()) {
  7293. if (LHSPointer->getPointeeType()->isVoidType()) {
  7294. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7295. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7296. ->getPointeeType()
  7297. .getAddressSpace();
  7298. Kind =
  7299. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7300. return Compatible;
  7301. }
  7302. }
  7303. return Incompatible;
  7304. }
  7305. // Conversions to block pointers.
  7306. if (isa<BlockPointerType>(LHSType)) {
  7307. // U^ -> T^
  7308. if (RHSType->isBlockPointerType()) {
  7309. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7310. ->getPointeeType()
  7311. .getAddressSpace();
  7312. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7313. ->getPointeeType()
  7314. .getAddressSpace();
  7315. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7316. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7317. }
  7318. // int or null -> T^
  7319. if (RHSType->isIntegerType()) {
  7320. Kind = CK_IntegralToPointer; // FIXME: null
  7321. return IntToBlockPointer;
  7322. }
  7323. // id -> T^
  7324. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7325. Kind = CK_AnyPointerToBlockPointerCast;
  7326. return Compatible;
  7327. }
  7328. // void* -> T^
  7329. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7330. if (RHSPT->getPointeeType()->isVoidType()) {
  7331. Kind = CK_AnyPointerToBlockPointerCast;
  7332. return Compatible;
  7333. }
  7334. return Incompatible;
  7335. }
  7336. // Conversions to Objective-C pointers.
  7337. if (isa<ObjCObjectPointerType>(LHSType)) {
  7338. // A* -> B*
  7339. if (RHSType->isObjCObjectPointerType()) {
  7340. Kind = CK_BitCast;
  7341. Sema::AssignConvertType result =
  7342. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7343. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7344. result == Compatible &&
  7345. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7346. result = IncompatibleObjCWeakRef;
  7347. return result;
  7348. }
  7349. // int or null -> A*
  7350. if (RHSType->isIntegerType()) {
  7351. Kind = CK_IntegralToPointer; // FIXME: null
  7352. return IntToPointer;
  7353. }
  7354. // In general, C pointers are not compatible with ObjC object pointers,
  7355. // with two exceptions:
  7356. if (isa<PointerType>(RHSType)) {
  7357. Kind = CK_CPointerToObjCPointerCast;
  7358. // - conversions from 'void*'
  7359. if (RHSType->isVoidPointerType()) {
  7360. return Compatible;
  7361. }
  7362. // - conversions to 'Class' from its redefinition type
  7363. if (LHSType->isObjCClassType() &&
  7364. Context.hasSameType(RHSType,
  7365. Context.getObjCClassRedefinitionType())) {
  7366. return Compatible;
  7367. }
  7368. return IncompatiblePointer;
  7369. }
  7370. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7371. if (RHSType->isBlockPointerType() &&
  7372. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7373. if (ConvertRHS)
  7374. maybeExtendBlockObject(RHS);
  7375. Kind = CK_BlockPointerToObjCPointerCast;
  7376. return Compatible;
  7377. }
  7378. return Incompatible;
  7379. }
  7380. // Conversions from pointers that are not covered by the above.
  7381. if (isa<PointerType>(RHSType)) {
  7382. // T* -> _Bool
  7383. if (LHSType == Context.BoolTy) {
  7384. Kind = CK_PointerToBoolean;
  7385. return Compatible;
  7386. }
  7387. // T* -> int
  7388. if (LHSType->isIntegerType()) {
  7389. Kind = CK_PointerToIntegral;
  7390. return PointerToInt;
  7391. }
  7392. return Incompatible;
  7393. }
  7394. // Conversions from Objective-C pointers that are not covered by the above.
  7395. if (isa<ObjCObjectPointerType>(RHSType)) {
  7396. // T* -> _Bool
  7397. if (LHSType == Context.BoolTy) {
  7398. Kind = CK_PointerToBoolean;
  7399. return Compatible;
  7400. }
  7401. // T* -> int
  7402. if (LHSType->isIntegerType()) {
  7403. Kind = CK_PointerToIntegral;
  7404. return PointerToInt;
  7405. }
  7406. return Incompatible;
  7407. }
  7408. // struct A -> struct B
  7409. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7410. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7411. Kind = CK_NoOp;
  7412. return Compatible;
  7413. }
  7414. }
  7415. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7416. Kind = CK_IntToOCLSampler;
  7417. return Compatible;
  7418. }
  7419. return Incompatible;
  7420. }
  7421. /// Constructs a transparent union from an expression that is
  7422. /// used to initialize the transparent union.
  7423. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7424. ExprResult &EResult, QualType UnionType,
  7425. FieldDecl *Field) {
  7426. // Build an initializer list that designates the appropriate member
  7427. // of the transparent union.
  7428. Expr *E = EResult.get();
  7429. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7430. E, SourceLocation());
  7431. Initializer->setType(UnionType);
  7432. Initializer->setInitializedFieldInUnion(Field);
  7433. // Build a compound literal constructing a value of the transparent
  7434. // union type from this initializer list.
  7435. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7436. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7437. VK_RValue, Initializer, false);
  7438. }
  7439. Sema::AssignConvertType
  7440. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7441. ExprResult &RHS) {
  7442. QualType RHSType = RHS.get()->getType();
  7443. // If the ArgType is a Union type, we want to handle a potential
  7444. // transparent_union GCC extension.
  7445. const RecordType *UT = ArgType->getAsUnionType();
  7446. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7447. return Incompatible;
  7448. // The field to initialize within the transparent union.
  7449. RecordDecl *UD = UT->getDecl();
  7450. FieldDecl *InitField = nullptr;
  7451. // It's compatible if the expression matches any of the fields.
  7452. for (auto *it : UD->fields()) {
  7453. if (it->getType()->isPointerType()) {
  7454. // If the transparent union contains a pointer type, we allow:
  7455. // 1) void pointer
  7456. // 2) null pointer constant
  7457. if (RHSType->isPointerType())
  7458. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7459. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7460. InitField = it;
  7461. break;
  7462. }
  7463. if (RHS.get()->isNullPointerConstant(Context,
  7464. Expr::NPC_ValueDependentIsNull)) {
  7465. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7466. CK_NullToPointer);
  7467. InitField = it;
  7468. break;
  7469. }
  7470. }
  7471. CastKind Kind;
  7472. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7473. == Compatible) {
  7474. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7475. InitField = it;
  7476. break;
  7477. }
  7478. }
  7479. if (!InitField)
  7480. return Incompatible;
  7481. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7482. return Compatible;
  7483. }
  7484. Sema::AssignConvertType
  7485. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7486. bool Diagnose,
  7487. bool DiagnoseCFAudited,
  7488. bool ConvertRHS) {
  7489. // We need to be able to tell the caller whether we diagnosed a problem, if
  7490. // they ask us to issue diagnostics.
  7491. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7492. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7493. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7494. // to put the updated value.
  7495. ExprResult LocalRHS = CallerRHS;
  7496. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7497. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7498. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7499. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7500. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7501. Diag(RHS.get()->getExprLoc(),
  7502. diag::warn_noderef_to_dereferenceable_pointer)
  7503. << RHS.get()->getSourceRange();
  7504. }
  7505. }
  7506. }
  7507. if (getLangOpts().CPlusPlus) {
  7508. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7509. // C++ 5.17p3: If the left operand is not of class type, the
  7510. // expression is implicitly converted (C++ 4) to the
  7511. // cv-unqualified type of the left operand.
  7512. QualType RHSType = RHS.get()->getType();
  7513. if (Diagnose) {
  7514. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7515. AA_Assigning);
  7516. } else {
  7517. ImplicitConversionSequence ICS =
  7518. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7519. /*SuppressUserConversions=*/false,
  7520. /*AllowExplicit=*/false,
  7521. /*InOverloadResolution=*/false,
  7522. /*CStyle=*/false,
  7523. /*AllowObjCWritebackConversion=*/false);
  7524. if (ICS.isFailure())
  7525. return Incompatible;
  7526. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7527. ICS, AA_Assigning);
  7528. }
  7529. if (RHS.isInvalid())
  7530. return Incompatible;
  7531. Sema::AssignConvertType result = Compatible;
  7532. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7533. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7534. result = IncompatibleObjCWeakRef;
  7535. return result;
  7536. }
  7537. // FIXME: Currently, we fall through and treat C++ classes like C
  7538. // structures.
  7539. // FIXME: We also fall through for atomics; not sure what should
  7540. // happen there, though.
  7541. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7542. // As a set of extensions to C, we support overloading on functions. These
  7543. // functions need to be resolved here.
  7544. DeclAccessPair DAP;
  7545. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7546. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7547. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7548. else
  7549. return Incompatible;
  7550. }
  7551. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7552. // a null pointer constant.
  7553. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7554. LHSType->isBlockPointerType()) &&
  7555. RHS.get()->isNullPointerConstant(Context,
  7556. Expr::NPC_ValueDependentIsNull)) {
  7557. if (Diagnose || ConvertRHS) {
  7558. CastKind Kind;
  7559. CXXCastPath Path;
  7560. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7561. /*IgnoreBaseAccess=*/false, Diagnose);
  7562. if (ConvertRHS)
  7563. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7564. }
  7565. return Compatible;
  7566. }
  7567. // OpenCL queue_t type assignment.
  7568. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7569. Context, Expr::NPC_ValueDependentIsNull)) {
  7570. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7571. return Compatible;
  7572. }
  7573. // This check seems unnatural, however it is necessary to ensure the proper
  7574. // conversion of functions/arrays. If the conversion were done for all
  7575. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7576. // expressions that suppress this implicit conversion (&, sizeof).
  7577. //
  7578. // Suppress this for references: C++ 8.5.3p5.
  7579. if (!LHSType->isReferenceType()) {
  7580. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7581. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7582. if (RHS.isInvalid())
  7583. return Incompatible;
  7584. }
  7585. CastKind Kind;
  7586. Sema::AssignConvertType result =
  7587. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7588. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7589. // type of the assignment expression.
  7590. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7591. // so that we can use references in built-in functions even in C.
  7592. // The getNonReferenceType() call makes sure that the resulting expression
  7593. // does not have reference type.
  7594. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7595. QualType Ty = LHSType.getNonLValueExprType(Context);
  7596. Expr *E = RHS.get();
  7597. // Check for various Objective-C errors. If we are not reporting
  7598. // diagnostics and just checking for errors, e.g., during overload
  7599. // resolution, return Incompatible to indicate the failure.
  7600. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7601. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7602. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7603. if (!Diagnose)
  7604. return Incompatible;
  7605. }
  7606. if (getLangOpts().ObjC &&
  7607. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7608. E->getType(), E, Diagnose) ||
  7609. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7610. if (!Diagnose)
  7611. return Incompatible;
  7612. // Replace the expression with a corrected version and continue so we
  7613. // can find further errors.
  7614. RHS = E;
  7615. return Compatible;
  7616. }
  7617. if (ConvertRHS)
  7618. RHS = ImpCastExprToType(E, Ty, Kind);
  7619. }
  7620. return result;
  7621. }
  7622. namespace {
  7623. /// The original operand to an operator, prior to the application of the usual
  7624. /// arithmetic conversions and converting the arguments of a builtin operator
  7625. /// candidate.
  7626. struct OriginalOperand {
  7627. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7628. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7629. Op = MTE->GetTemporaryExpr();
  7630. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7631. Op = BTE->getSubExpr();
  7632. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7633. Orig = ICE->getSubExprAsWritten();
  7634. Conversion = ICE->getConversionFunction();
  7635. }
  7636. }
  7637. QualType getType() const { return Orig->getType(); }
  7638. Expr *Orig;
  7639. NamedDecl *Conversion;
  7640. };
  7641. }
  7642. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7643. ExprResult &RHS) {
  7644. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7645. Diag(Loc, diag::err_typecheck_invalid_operands)
  7646. << OrigLHS.getType() << OrigRHS.getType()
  7647. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7648. // If a user-defined conversion was applied to either of the operands prior
  7649. // to applying the built-in operator rules, tell the user about it.
  7650. if (OrigLHS.Conversion) {
  7651. Diag(OrigLHS.Conversion->getLocation(),
  7652. diag::note_typecheck_invalid_operands_converted)
  7653. << 0 << LHS.get()->getType();
  7654. }
  7655. if (OrigRHS.Conversion) {
  7656. Diag(OrigRHS.Conversion->getLocation(),
  7657. diag::note_typecheck_invalid_operands_converted)
  7658. << 1 << RHS.get()->getType();
  7659. }
  7660. return QualType();
  7661. }
  7662. // Diagnose cases where a scalar was implicitly converted to a vector and
  7663. // diagnose the underlying types. Otherwise, diagnose the error
  7664. // as invalid vector logical operands for non-C++ cases.
  7665. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7666. ExprResult &RHS) {
  7667. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7668. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7669. bool LHSNatVec = LHSType->isVectorType();
  7670. bool RHSNatVec = RHSType->isVectorType();
  7671. if (!(LHSNatVec && RHSNatVec)) {
  7672. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7673. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7674. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7675. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7676. << Vector->getSourceRange();
  7677. return QualType();
  7678. }
  7679. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7680. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7681. << RHS.get()->getSourceRange();
  7682. return QualType();
  7683. }
  7684. /// Try to convert a value of non-vector type to a vector type by converting
  7685. /// the type to the element type of the vector and then performing a splat.
  7686. /// If the language is OpenCL, we only use conversions that promote scalar
  7687. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7688. /// for float->int.
  7689. ///
  7690. /// OpenCL V2.0 6.2.6.p2:
  7691. /// An error shall occur if any scalar operand type has greater rank
  7692. /// than the type of the vector element.
  7693. ///
  7694. /// \param scalar - if non-null, actually perform the conversions
  7695. /// \return true if the operation fails (but without diagnosing the failure)
  7696. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7697. QualType scalarTy,
  7698. QualType vectorEltTy,
  7699. QualType vectorTy,
  7700. unsigned &DiagID) {
  7701. // The conversion to apply to the scalar before splatting it,
  7702. // if necessary.
  7703. CastKind scalarCast = CK_NoOp;
  7704. if (vectorEltTy->isIntegralType(S.Context)) {
  7705. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7706. (scalarTy->isIntegerType() &&
  7707. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7708. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7709. return true;
  7710. }
  7711. if (!scalarTy->isIntegralType(S.Context))
  7712. return true;
  7713. scalarCast = CK_IntegralCast;
  7714. } else if (vectorEltTy->isRealFloatingType()) {
  7715. if (scalarTy->isRealFloatingType()) {
  7716. if (S.getLangOpts().OpenCL &&
  7717. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7718. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7719. return true;
  7720. }
  7721. scalarCast = CK_FloatingCast;
  7722. }
  7723. else if (scalarTy->isIntegralType(S.Context))
  7724. scalarCast = CK_IntegralToFloating;
  7725. else
  7726. return true;
  7727. } else {
  7728. return true;
  7729. }
  7730. // Adjust scalar if desired.
  7731. if (scalar) {
  7732. if (scalarCast != CK_NoOp)
  7733. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7734. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7735. }
  7736. return false;
  7737. }
  7738. /// Convert vector E to a vector with the same number of elements but different
  7739. /// element type.
  7740. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7741. const auto *VecTy = E->getType()->getAs<VectorType>();
  7742. assert(VecTy && "Expression E must be a vector");
  7743. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7744. VecTy->getNumElements(),
  7745. VecTy->getVectorKind());
  7746. // Look through the implicit cast. Return the subexpression if its type is
  7747. // NewVecTy.
  7748. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7749. if (ICE->getSubExpr()->getType() == NewVecTy)
  7750. return ICE->getSubExpr();
  7751. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7752. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7753. }
  7754. /// Test if a (constant) integer Int can be casted to another integer type
  7755. /// IntTy without losing precision.
  7756. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7757. QualType OtherIntTy) {
  7758. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7759. // Reject cases where the value of the Int is unknown as that would
  7760. // possibly cause truncation, but accept cases where the scalar can be
  7761. // demoted without loss of precision.
  7762. Expr::EvalResult EVResult;
  7763. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7764. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7765. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7766. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7767. if (CstInt) {
  7768. // If the scalar is constant and is of a higher order and has more active
  7769. // bits that the vector element type, reject it.
  7770. llvm::APSInt Result = EVResult.Val.getInt();
  7771. unsigned NumBits = IntSigned
  7772. ? (Result.isNegative() ? Result.getMinSignedBits()
  7773. : Result.getActiveBits())
  7774. : Result.getActiveBits();
  7775. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7776. return true;
  7777. // If the signedness of the scalar type and the vector element type
  7778. // differs and the number of bits is greater than that of the vector
  7779. // element reject it.
  7780. return (IntSigned != OtherIntSigned &&
  7781. NumBits > S.Context.getIntWidth(OtherIntTy));
  7782. }
  7783. // Reject cases where the value of the scalar is not constant and it's
  7784. // order is greater than that of the vector element type.
  7785. return (Order < 0);
  7786. }
  7787. /// Test if a (constant) integer Int can be casted to floating point type
  7788. /// FloatTy without losing precision.
  7789. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7790. QualType FloatTy) {
  7791. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7792. // Determine if the integer constant can be expressed as a floating point
  7793. // number of the appropriate type.
  7794. Expr::EvalResult EVResult;
  7795. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7796. uint64_t Bits = 0;
  7797. if (CstInt) {
  7798. // Reject constants that would be truncated if they were converted to
  7799. // the floating point type. Test by simple to/from conversion.
  7800. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7801. // could be avoided if there was a convertFromAPInt method
  7802. // which could signal back if implicit truncation occurred.
  7803. llvm::APSInt Result = EVResult.Val.getInt();
  7804. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7805. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7806. llvm::APFloat::rmTowardZero);
  7807. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7808. !IntTy->hasSignedIntegerRepresentation());
  7809. bool Ignored = false;
  7810. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7811. &Ignored);
  7812. if (Result != ConvertBack)
  7813. return true;
  7814. } else {
  7815. // Reject types that cannot be fully encoded into the mantissa of
  7816. // the float.
  7817. Bits = S.Context.getTypeSize(IntTy);
  7818. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7819. S.Context.getFloatTypeSemantics(FloatTy));
  7820. if (Bits > FloatPrec)
  7821. return true;
  7822. }
  7823. return false;
  7824. }
  7825. /// Attempt to convert and splat Scalar into a vector whose types matches
  7826. /// Vector following GCC conversion rules. The rule is that implicit
  7827. /// conversion can occur when Scalar can be casted to match Vector's element
  7828. /// type without causing truncation of Scalar.
  7829. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7830. ExprResult *Vector) {
  7831. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7832. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7833. const VectorType *VT = VectorTy->getAs<VectorType>();
  7834. assert(!isa<ExtVectorType>(VT) &&
  7835. "ExtVectorTypes should not be handled here!");
  7836. QualType VectorEltTy = VT->getElementType();
  7837. // Reject cases where the vector element type or the scalar element type are
  7838. // not integral or floating point types.
  7839. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7840. return true;
  7841. // The conversion to apply to the scalar before splatting it,
  7842. // if necessary.
  7843. CastKind ScalarCast = CK_NoOp;
  7844. // Accept cases where the vector elements are integers and the scalar is
  7845. // an integer.
  7846. // FIXME: Notionally if the scalar was a floating point value with a precise
  7847. // integral representation, we could cast it to an appropriate integer
  7848. // type and then perform the rest of the checks here. GCC will perform
  7849. // this conversion in some cases as determined by the input language.
  7850. // We should accept it on a language independent basis.
  7851. if (VectorEltTy->isIntegralType(S.Context) &&
  7852. ScalarTy->isIntegralType(S.Context) &&
  7853. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7854. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7855. return true;
  7856. ScalarCast = CK_IntegralCast;
  7857. } else if (VectorEltTy->isRealFloatingType()) {
  7858. if (ScalarTy->isRealFloatingType()) {
  7859. // Reject cases where the scalar type is not a constant and has a higher
  7860. // Order than the vector element type.
  7861. llvm::APFloat Result(0.0);
  7862. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7863. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7864. if (!CstScalar && Order < 0)
  7865. return true;
  7866. // If the scalar cannot be safely casted to the vector element type,
  7867. // reject it.
  7868. if (CstScalar) {
  7869. bool Truncated = false;
  7870. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7871. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7872. if (Truncated)
  7873. return true;
  7874. }
  7875. ScalarCast = CK_FloatingCast;
  7876. } else if (ScalarTy->isIntegralType(S.Context)) {
  7877. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7878. return true;
  7879. ScalarCast = CK_IntegralToFloating;
  7880. } else
  7881. return true;
  7882. }
  7883. // Adjust scalar if desired.
  7884. if (Scalar) {
  7885. if (ScalarCast != CK_NoOp)
  7886. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7887. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7888. }
  7889. return false;
  7890. }
  7891. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7892. SourceLocation Loc, bool IsCompAssign,
  7893. bool AllowBothBool,
  7894. bool AllowBoolConversions) {
  7895. if (!IsCompAssign) {
  7896. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7897. if (LHS.isInvalid())
  7898. return QualType();
  7899. }
  7900. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7901. if (RHS.isInvalid())
  7902. return QualType();
  7903. // For conversion purposes, we ignore any qualifiers.
  7904. // For example, "const float" and "float" are equivalent.
  7905. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7906. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7907. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7908. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7909. assert(LHSVecType || RHSVecType);
  7910. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7911. // for some operators but not others.
  7912. if (!AllowBothBool &&
  7913. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7914. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7915. return InvalidOperands(Loc, LHS, RHS);
  7916. // If the vector types are identical, return.
  7917. if (Context.hasSameType(LHSType, RHSType))
  7918. return LHSType;
  7919. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7920. if (LHSVecType && RHSVecType &&
  7921. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7922. if (isa<ExtVectorType>(LHSVecType)) {
  7923. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7924. return LHSType;
  7925. }
  7926. if (!IsCompAssign)
  7927. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7928. return RHSType;
  7929. }
  7930. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7931. // can be mixed, with the result being the non-bool type. The non-bool
  7932. // operand must have integer element type.
  7933. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7934. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7935. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7936. Context.getTypeSize(RHSVecType->getElementType()))) {
  7937. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7938. LHSVecType->getElementType()->isIntegerType() &&
  7939. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7940. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7941. return LHSType;
  7942. }
  7943. if (!IsCompAssign &&
  7944. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7945. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7946. RHSVecType->getElementType()->isIntegerType()) {
  7947. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7948. return RHSType;
  7949. }
  7950. }
  7951. // If there's a vector type and a scalar, try to convert the scalar to
  7952. // the vector element type and splat.
  7953. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7954. if (!RHSVecType) {
  7955. if (isa<ExtVectorType>(LHSVecType)) {
  7956. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7957. LHSVecType->getElementType(), LHSType,
  7958. DiagID))
  7959. return LHSType;
  7960. } else {
  7961. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7962. return LHSType;
  7963. }
  7964. }
  7965. if (!LHSVecType) {
  7966. if (isa<ExtVectorType>(RHSVecType)) {
  7967. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7968. LHSType, RHSVecType->getElementType(),
  7969. RHSType, DiagID))
  7970. return RHSType;
  7971. } else {
  7972. if (LHS.get()->getValueKind() == VK_LValue ||
  7973. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7974. return RHSType;
  7975. }
  7976. }
  7977. // FIXME: The code below also handles conversion between vectors and
  7978. // non-scalars, we should break this down into fine grained specific checks
  7979. // and emit proper diagnostics.
  7980. QualType VecType = LHSVecType ? LHSType : RHSType;
  7981. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7982. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7983. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7984. if (isLaxVectorConversion(OtherType, VecType)) {
  7985. // If we're allowing lax vector conversions, only the total (data) size
  7986. // needs to be the same. For non compound assignment, if one of the types is
  7987. // scalar, the result is always the vector type.
  7988. if (!IsCompAssign) {
  7989. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7990. return VecType;
  7991. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7992. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7993. // type. Note that this is already done by non-compound assignments in
  7994. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7995. // <1 x T> -> T. The result is also a vector type.
  7996. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7997. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7998. ExprResult *RHSExpr = &RHS;
  7999. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  8000. return VecType;
  8001. }
  8002. }
  8003. // Okay, the expression is invalid.
  8004. // If there's a non-vector, non-real operand, diagnose that.
  8005. if ((!RHSVecType && !RHSType->isRealType()) ||
  8006. (!LHSVecType && !LHSType->isRealType())) {
  8007. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  8008. << LHSType << RHSType
  8009. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8010. return QualType();
  8011. }
  8012. // OpenCL V1.1 6.2.6.p1:
  8013. // If the operands are of more than one vector type, then an error shall
  8014. // occur. Implicit conversions between vector types are not permitted, per
  8015. // section 6.2.1.
  8016. if (getLangOpts().OpenCL &&
  8017. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  8018. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  8019. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  8020. << RHSType;
  8021. return QualType();
  8022. }
  8023. // If there is a vector type that is not a ExtVector and a scalar, we reach
  8024. // this point if scalar could not be converted to the vector's element type
  8025. // without truncation.
  8026. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  8027. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  8028. QualType Scalar = LHSVecType ? RHSType : LHSType;
  8029. QualType Vector = LHSVecType ? LHSType : RHSType;
  8030. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  8031. Diag(Loc,
  8032. diag::err_typecheck_vector_not_convertable_implict_truncation)
  8033. << ScalarOrVector << Scalar << Vector;
  8034. return QualType();
  8035. }
  8036. // Otherwise, use the generic diagnostic.
  8037. Diag(Loc, DiagID)
  8038. << LHSType << RHSType
  8039. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8040. return QualType();
  8041. }
  8042. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  8043. // expression. These are mainly cases where the null pointer is used as an
  8044. // integer instead of a pointer.
  8045. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8046. SourceLocation Loc, bool IsCompare) {
  8047. // The canonical way to check for a GNU null is with isNullPointerConstant,
  8048. // but we use a bit of a hack here for speed; this is a relatively
  8049. // hot path, and isNullPointerConstant is slow.
  8050. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  8051. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  8052. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  8053. // Avoid analyzing cases where the result will either be invalid (and
  8054. // diagnosed as such) or entirely valid and not something to warn about.
  8055. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  8056. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  8057. return;
  8058. // Comparison operations would not make sense with a null pointer no matter
  8059. // what the other expression is.
  8060. if (!IsCompare) {
  8061. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  8062. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  8063. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  8064. return;
  8065. }
  8066. // The rest of the operations only make sense with a null pointer
  8067. // if the other expression is a pointer.
  8068. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  8069. NonNullType->canDecayToPointerType())
  8070. return;
  8071. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  8072. << LHSNull /* LHS is NULL */ << NonNullType
  8073. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8074. }
  8075. static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
  8076. SourceLocation Loc) {
  8077. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  8078. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  8079. if (!LUE || !RUE)
  8080. return;
  8081. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  8082. RUE->getKind() != UETT_SizeOf)
  8083. return;
  8084. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  8085. QualType LHSTy = LHSArg->getType();
  8086. QualType RHSTy;
  8087. if (RUE->isArgumentType())
  8088. RHSTy = RUE->getArgumentType();
  8089. else
  8090. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  8091. if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
  8092. if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
  8093. return;
  8094. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  8095. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8096. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8097. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  8098. << LHSArgDecl;
  8099. }
  8100. } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
  8101. QualType ArrayElemTy = ArrayTy->getElementType();
  8102. if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
  8103. ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
  8104. ArrayElemTy->isCharType() ||
  8105. S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
  8106. return;
  8107. S.Diag(Loc, diag::warn_division_sizeof_array)
  8108. << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
  8109. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8110. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8111. S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
  8112. << LHSArgDecl;
  8113. }
  8114. S.Diag(Loc, diag::note_precedence_silence) << RHS;
  8115. }
  8116. }
  8117. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  8118. ExprResult &RHS,
  8119. SourceLocation Loc, bool IsDiv) {
  8120. // Check for division/remainder by zero.
  8121. Expr::EvalResult RHSValue;
  8122. if (!RHS.get()->isValueDependent() &&
  8123. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  8124. RHSValue.Val.getInt() == 0)
  8125. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8126. S.PDiag(diag::warn_remainder_division_by_zero)
  8127. << IsDiv << RHS.get()->getSourceRange());
  8128. }
  8129. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  8130. SourceLocation Loc,
  8131. bool IsCompAssign, bool IsDiv) {
  8132. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8133. if (LHS.get()->getType()->isVectorType() ||
  8134. RHS.get()->getType()->isVectorType())
  8135. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8136. /*AllowBothBool*/getLangOpts().AltiVec,
  8137. /*AllowBoolConversions*/false);
  8138. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8139. if (LHS.isInvalid() || RHS.isInvalid())
  8140. return QualType();
  8141. if (compType.isNull() || !compType->isArithmeticType())
  8142. return InvalidOperands(Loc, LHS, RHS);
  8143. if (IsDiv) {
  8144. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  8145. DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
  8146. }
  8147. return compType;
  8148. }
  8149. QualType Sema::CheckRemainderOperands(
  8150. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  8151. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8152. if (LHS.get()->getType()->isVectorType() ||
  8153. RHS.get()->getType()->isVectorType()) {
  8154. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8155. RHS.get()->getType()->hasIntegerRepresentation())
  8156. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8157. /*AllowBothBool*/getLangOpts().AltiVec,
  8158. /*AllowBoolConversions*/false);
  8159. return InvalidOperands(Loc, LHS, RHS);
  8160. }
  8161. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8162. if (LHS.isInvalid() || RHS.isInvalid())
  8163. return QualType();
  8164. if (compType.isNull() || !compType->isIntegerType())
  8165. return InvalidOperands(Loc, LHS, RHS);
  8166. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  8167. return compType;
  8168. }
  8169. /// Diagnose invalid arithmetic on two void pointers.
  8170. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  8171. Expr *LHSExpr, Expr *RHSExpr) {
  8172. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8173. ? diag::err_typecheck_pointer_arith_void_type
  8174. : diag::ext_gnu_void_ptr)
  8175. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  8176. << RHSExpr->getSourceRange();
  8177. }
  8178. /// Diagnose invalid arithmetic on a void pointer.
  8179. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  8180. Expr *Pointer) {
  8181. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8182. ? diag::err_typecheck_pointer_arith_void_type
  8183. : diag::ext_gnu_void_ptr)
  8184. << 0 /* one pointer */ << Pointer->getSourceRange();
  8185. }
  8186. /// Diagnose invalid arithmetic on a null pointer.
  8187. ///
  8188. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  8189. /// idiom, which we recognize as a GNU extension.
  8190. ///
  8191. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  8192. Expr *Pointer, bool IsGNUIdiom) {
  8193. if (IsGNUIdiom)
  8194. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  8195. << Pointer->getSourceRange();
  8196. else
  8197. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8198. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8199. }
  8200. /// Diagnose invalid arithmetic on two function pointers.
  8201. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8202. Expr *LHS, Expr *RHS) {
  8203. assert(LHS->getType()->isAnyPointerType());
  8204. assert(RHS->getType()->isAnyPointerType());
  8205. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8206. ? diag::err_typecheck_pointer_arith_function_type
  8207. : diag::ext_gnu_ptr_func_arith)
  8208. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8209. // We only show the second type if it differs from the first.
  8210. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8211. RHS->getType())
  8212. << RHS->getType()->getPointeeType()
  8213. << LHS->getSourceRange() << RHS->getSourceRange();
  8214. }
  8215. /// Diagnose invalid arithmetic on a function pointer.
  8216. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8217. Expr *Pointer) {
  8218. assert(Pointer->getType()->isAnyPointerType());
  8219. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8220. ? diag::err_typecheck_pointer_arith_function_type
  8221. : diag::ext_gnu_ptr_func_arith)
  8222. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8223. << 0 /* one pointer, so only one type */
  8224. << Pointer->getSourceRange();
  8225. }
  8226. /// Emit error if Operand is incomplete pointer type
  8227. ///
  8228. /// \returns True if pointer has incomplete type
  8229. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8230. Expr *Operand) {
  8231. QualType ResType = Operand->getType();
  8232. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8233. ResType = ResAtomicType->getValueType();
  8234. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8235. QualType PointeeTy = ResType->getPointeeType();
  8236. return S.RequireCompleteType(Loc, PointeeTy,
  8237. diag::err_typecheck_arithmetic_incomplete_type,
  8238. PointeeTy, Operand->getSourceRange());
  8239. }
  8240. /// Check the validity of an arithmetic pointer operand.
  8241. ///
  8242. /// If the operand has pointer type, this code will check for pointer types
  8243. /// which are invalid in arithmetic operations. These will be diagnosed
  8244. /// appropriately, including whether or not the use is supported as an
  8245. /// extension.
  8246. ///
  8247. /// \returns True when the operand is valid to use (even if as an extension).
  8248. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8249. Expr *Operand) {
  8250. QualType ResType = Operand->getType();
  8251. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8252. ResType = ResAtomicType->getValueType();
  8253. if (!ResType->isAnyPointerType()) return true;
  8254. QualType PointeeTy = ResType->getPointeeType();
  8255. if (PointeeTy->isVoidType()) {
  8256. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8257. return !S.getLangOpts().CPlusPlus;
  8258. }
  8259. if (PointeeTy->isFunctionType()) {
  8260. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8261. return !S.getLangOpts().CPlusPlus;
  8262. }
  8263. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8264. return true;
  8265. }
  8266. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8267. /// operands.
  8268. ///
  8269. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8270. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8271. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8272. /// are (potentially problematic) pointers.
  8273. ///
  8274. /// \returns True when the operand is valid to use (even if as an extension).
  8275. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8276. Expr *LHSExpr, Expr *RHSExpr) {
  8277. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8278. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8279. if (!isLHSPointer && !isRHSPointer) return true;
  8280. QualType LHSPointeeTy, RHSPointeeTy;
  8281. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8282. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8283. // if both are pointers check if operation is valid wrt address spaces
  8284. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8285. const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
  8286. const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
  8287. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8288. S.Diag(Loc,
  8289. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8290. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8291. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8292. return false;
  8293. }
  8294. }
  8295. // Check for arithmetic on pointers to incomplete types.
  8296. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8297. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8298. if (isLHSVoidPtr || isRHSVoidPtr) {
  8299. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8300. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8301. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8302. return !S.getLangOpts().CPlusPlus;
  8303. }
  8304. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8305. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8306. if (isLHSFuncPtr || isRHSFuncPtr) {
  8307. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8308. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8309. RHSExpr);
  8310. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8311. return !S.getLangOpts().CPlusPlus;
  8312. }
  8313. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8314. return false;
  8315. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8316. return false;
  8317. return true;
  8318. }
  8319. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8320. /// literal.
  8321. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8322. Expr *LHSExpr, Expr *RHSExpr) {
  8323. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8324. Expr* IndexExpr = RHSExpr;
  8325. if (!StrExpr) {
  8326. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8327. IndexExpr = LHSExpr;
  8328. }
  8329. bool IsStringPlusInt = StrExpr &&
  8330. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8331. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8332. return;
  8333. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8334. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8335. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8336. // Only print a fixit for "str" + int, not for int + "str".
  8337. if (IndexExpr == RHSExpr) {
  8338. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8339. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8340. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8341. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8342. << FixItHint::CreateInsertion(EndLoc, "]");
  8343. } else
  8344. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8345. }
  8346. /// Emit a warning when adding a char literal to a string.
  8347. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8348. Expr *LHSExpr, Expr *RHSExpr) {
  8349. const Expr *StringRefExpr = LHSExpr;
  8350. const CharacterLiteral *CharExpr =
  8351. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8352. if (!CharExpr) {
  8353. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8354. StringRefExpr = RHSExpr;
  8355. }
  8356. if (!CharExpr || !StringRefExpr)
  8357. return;
  8358. const QualType StringType = StringRefExpr->getType();
  8359. // Return if not a PointerType.
  8360. if (!StringType->isAnyPointerType())
  8361. return;
  8362. // Return if not a CharacterType.
  8363. if (!StringType->getPointeeType()->isAnyCharacterType())
  8364. return;
  8365. ASTContext &Ctx = Self.getASTContext();
  8366. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8367. const QualType CharType = CharExpr->getType();
  8368. if (!CharType->isAnyCharacterType() &&
  8369. CharType->isIntegerType() &&
  8370. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8371. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8372. << DiagRange << Ctx.CharTy;
  8373. } else {
  8374. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8375. << DiagRange << CharExpr->getType();
  8376. }
  8377. // Only print a fixit for str + char, not for char + str.
  8378. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8379. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8380. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8381. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8382. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8383. << FixItHint::CreateInsertion(EndLoc, "]");
  8384. } else {
  8385. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8386. }
  8387. }
  8388. /// Emit error when two pointers are incompatible.
  8389. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8390. Expr *LHSExpr, Expr *RHSExpr) {
  8391. assert(LHSExpr->getType()->isAnyPointerType());
  8392. assert(RHSExpr->getType()->isAnyPointerType());
  8393. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8394. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8395. << RHSExpr->getSourceRange();
  8396. }
  8397. // C99 6.5.6
  8398. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8399. SourceLocation Loc, BinaryOperatorKind Opc,
  8400. QualType* CompLHSTy) {
  8401. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8402. if (LHS.get()->getType()->isVectorType() ||
  8403. RHS.get()->getType()->isVectorType()) {
  8404. QualType compType = CheckVectorOperands(
  8405. LHS, RHS, Loc, CompLHSTy,
  8406. /*AllowBothBool*/getLangOpts().AltiVec,
  8407. /*AllowBoolConversions*/getLangOpts().ZVector);
  8408. if (CompLHSTy) *CompLHSTy = compType;
  8409. return compType;
  8410. }
  8411. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8412. if (LHS.isInvalid() || RHS.isInvalid())
  8413. return QualType();
  8414. // Diagnose "string literal" '+' int and string '+' "char literal".
  8415. if (Opc == BO_Add) {
  8416. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8417. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8418. }
  8419. // handle the common case first (both operands are arithmetic).
  8420. if (!compType.isNull() && compType->isArithmeticType()) {
  8421. if (CompLHSTy) *CompLHSTy = compType;
  8422. return compType;
  8423. }
  8424. // Type-checking. Ultimately the pointer's going to be in PExp;
  8425. // note that we bias towards the LHS being the pointer.
  8426. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8427. bool isObjCPointer;
  8428. if (PExp->getType()->isPointerType()) {
  8429. isObjCPointer = false;
  8430. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8431. isObjCPointer = true;
  8432. } else {
  8433. std::swap(PExp, IExp);
  8434. if (PExp->getType()->isPointerType()) {
  8435. isObjCPointer = false;
  8436. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8437. isObjCPointer = true;
  8438. } else {
  8439. return InvalidOperands(Loc, LHS, RHS);
  8440. }
  8441. }
  8442. assert(PExp->getType()->isAnyPointerType());
  8443. if (!IExp->getType()->isIntegerType())
  8444. return InvalidOperands(Loc, LHS, RHS);
  8445. // Adding to a null pointer results in undefined behavior.
  8446. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8447. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8448. // In C++ adding zero to a null pointer is defined.
  8449. Expr::EvalResult KnownVal;
  8450. if (!getLangOpts().CPlusPlus ||
  8451. (!IExp->isValueDependent() &&
  8452. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8453. KnownVal.Val.getInt() != 0))) {
  8454. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8455. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8456. Context, BO_Add, PExp, IExp);
  8457. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8458. }
  8459. }
  8460. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8461. return QualType();
  8462. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8463. return QualType();
  8464. // Check array bounds for pointer arithemtic
  8465. CheckArrayAccess(PExp, IExp);
  8466. if (CompLHSTy) {
  8467. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8468. if (LHSTy.isNull()) {
  8469. LHSTy = LHS.get()->getType();
  8470. if (LHSTy->isPromotableIntegerType())
  8471. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8472. }
  8473. *CompLHSTy = LHSTy;
  8474. }
  8475. return PExp->getType();
  8476. }
  8477. // C99 6.5.6
  8478. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8479. SourceLocation Loc,
  8480. QualType* CompLHSTy) {
  8481. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8482. if (LHS.get()->getType()->isVectorType() ||
  8483. RHS.get()->getType()->isVectorType()) {
  8484. QualType compType = CheckVectorOperands(
  8485. LHS, RHS, Loc, CompLHSTy,
  8486. /*AllowBothBool*/getLangOpts().AltiVec,
  8487. /*AllowBoolConversions*/getLangOpts().ZVector);
  8488. if (CompLHSTy) *CompLHSTy = compType;
  8489. return compType;
  8490. }
  8491. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8492. if (LHS.isInvalid() || RHS.isInvalid())
  8493. return QualType();
  8494. // Enforce type constraints: C99 6.5.6p3.
  8495. // Handle the common case first (both operands are arithmetic).
  8496. if (!compType.isNull() && compType->isArithmeticType()) {
  8497. if (CompLHSTy) *CompLHSTy = compType;
  8498. return compType;
  8499. }
  8500. // Either ptr - int or ptr - ptr.
  8501. if (LHS.get()->getType()->isAnyPointerType()) {
  8502. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8503. // Diagnose bad cases where we step over interface counts.
  8504. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8505. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8506. return QualType();
  8507. // The result type of a pointer-int computation is the pointer type.
  8508. if (RHS.get()->getType()->isIntegerType()) {
  8509. // Subtracting from a null pointer should produce a warning.
  8510. // The last argument to the diagnose call says this doesn't match the
  8511. // GNU int-to-pointer idiom.
  8512. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8513. Expr::NPC_ValueDependentIsNotNull)) {
  8514. // In C++ adding zero to a null pointer is defined.
  8515. Expr::EvalResult KnownVal;
  8516. if (!getLangOpts().CPlusPlus ||
  8517. (!RHS.get()->isValueDependent() &&
  8518. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8519. KnownVal.Val.getInt() != 0))) {
  8520. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8521. }
  8522. }
  8523. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8524. return QualType();
  8525. // Check array bounds for pointer arithemtic
  8526. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8527. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8528. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8529. return LHS.get()->getType();
  8530. }
  8531. // Handle pointer-pointer subtractions.
  8532. if (const PointerType *RHSPTy
  8533. = RHS.get()->getType()->getAs<PointerType>()) {
  8534. QualType rpointee = RHSPTy->getPointeeType();
  8535. if (getLangOpts().CPlusPlus) {
  8536. // Pointee types must be the same: C++ [expr.add]
  8537. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8538. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8539. }
  8540. } else {
  8541. // Pointee types must be compatible C99 6.5.6p3
  8542. if (!Context.typesAreCompatible(
  8543. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8544. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8545. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8546. return QualType();
  8547. }
  8548. }
  8549. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8550. LHS.get(), RHS.get()))
  8551. return QualType();
  8552. // FIXME: Add warnings for nullptr - ptr.
  8553. // The pointee type may have zero size. As an extension, a structure or
  8554. // union may have zero size or an array may have zero length. In this
  8555. // case subtraction does not make sense.
  8556. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8557. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8558. if (ElementSize.isZero()) {
  8559. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8560. << rpointee.getUnqualifiedType()
  8561. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8562. }
  8563. }
  8564. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8565. return Context.getPointerDiffType();
  8566. }
  8567. }
  8568. return InvalidOperands(Loc, LHS, RHS);
  8569. }
  8570. static bool isScopedEnumerationType(QualType T) {
  8571. if (const EnumType *ET = T->getAs<EnumType>())
  8572. return ET->getDecl()->isScoped();
  8573. return false;
  8574. }
  8575. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8576. SourceLocation Loc, BinaryOperatorKind Opc,
  8577. QualType LHSType) {
  8578. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8579. // so skip remaining warnings as we don't want to modify values within Sema.
  8580. if (S.getLangOpts().OpenCL)
  8581. return;
  8582. // Check right/shifter operand
  8583. Expr::EvalResult RHSResult;
  8584. if (RHS.get()->isValueDependent() ||
  8585. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8586. return;
  8587. llvm::APSInt Right = RHSResult.Val.getInt();
  8588. if (Right.isNegative()) {
  8589. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8590. S.PDiag(diag::warn_shift_negative)
  8591. << RHS.get()->getSourceRange());
  8592. return;
  8593. }
  8594. llvm::APInt LeftBits(Right.getBitWidth(),
  8595. S.Context.getTypeSize(LHS.get()->getType()));
  8596. if (Right.uge(LeftBits)) {
  8597. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8598. S.PDiag(diag::warn_shift_gt_typewidth)
  8599. << RHS.get()->getSourceRange());
  8600. return;
  8601. }
  8602. if (Opc != BO_Shl)
  8603. return;
  8604. // When left shifting an ICE which is signed, we can check for overflow which
  8605. // according to C++ standards prior to C++2a has undefined behavior
  8606. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  8607. // more than the maximum value representable in the result type, so never
  8608. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  8609. // expression is still probably a bug.)
  8610. Expr::EvalResult LHSResult;
  8611. if (LHS.get()->isValueDependent() ||
  8612. LHSType->hasUnsignedIntegerRepresentation() ||
  8613. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8614. return;
  8615. llvm::APSInt Left = LHSResult.Val.getInt();
  8616. // If LHS does not have a signed type and non-negative value
  8617. // then, the behavior is undefined before C++2a. Warn about it.
  8618. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  8619. !S.getLangOpts().CPlusPlus2a) {
  8620. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8621. S.PDiag(diag::warn_shift_lhs_negative)
  8622. << LHS.get()->getSourceRange());
  8623. return;
  8624. }
  8625. llvm::APInt ResultBits =
  8626. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8627. if (LeftBits.uge(ResultBits))
  8628. return;
  8629. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8630. Result = Result.shl(Right);
  8631. // Print the bit representation of the signed integer as an unsigned
  8632. // hexadecimal number.
  8633. SmallString<40> HexResult;
  8634. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8635. // If we are only missing a sign bit, this is less likely to result in actual
  8636. // bugs -- if the result is cast back to an unsigned type, it will have the
  8637. // expected value. Thus we place this behind a different warning that can be
  8638. // turned off separately if needed.
  8639. if (LeftBits == ResultBits - 1) {
  8640. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8641. << HexResult << LHSType
  8642. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8643. return;
  8644. }
  8645. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8646. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8647. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8648. << RHS.get()->getSourceRange();
  8649. }
  8650. /// Return the resulting type when a vector is shifted
  8651. /// by a scalar or vector shift amount.
  8652. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8653. SourceLocation Loc, bool IsCompAssign) {
  8654. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8655. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8656. !LHS.get()->getType()->isVectorType()) {
  8657. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8658. << RHS.get()->getType() << LHS.get()->getType()
  8659. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8660. return QualType();
  8661. }
  8662. if (!IsCompAssign) {
  8663. LHS = S.UsualUnaryConversions(LHS.get());
  8664. if (LHS.isInvalid()) return QualType();
  8665. }
  8666. RHS = S.UsualUnaryConversions(RHS.get());
  8667. if (RHS.isInvalid()) return QualType();
  8668. QualType LHSType = LHS.get()->getType();
  8669. // Note that LHS might be a scalar because the routine calls not only in
  8670. // OpenCL case.
  8671. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8672. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8673. // Note that RHS might not be a vector.
  8674. QualType RHSType = RHS.get()->getType();
  8675. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8676. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8677. // The operands need to be integers.
  8678. if (!LHSEleType->isIntegerType()) {
  8679. S.Diag(Loc, diag::err_typecheck_expect_int)
  8680. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8681. return QualType();
  8682. }
  8683. if (!RHSEleType->isIntegerType()) {
  8684. S.Diag(Loc, diag::err_typecheck_expect_int)
  8685. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8686. return QualType();
  8687. }
  8688. if (!LHSVecTy) {
  8689. assert(RHSVecTy);
  8690. if (IsCompAssign)
  8691. return RHSType;
  8692. if (LHSEleType != RHSEleType) {
  8693. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8694. LHSEleType = RHSEleType;
  8695. }
  8696. QualType VecTy =
  8697. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8698. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8699. LHSType = VecTy;
  8700. } else if (RHSVecTy) {
  8701. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8702. // are applied component-wise. So if RHS is a vector, then ensure
  8703. // that the number of elements is the same as LHS...
  8704. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8705. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8706. << LHS.get()->getType() << RHS.get()->getType()
  8707. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8708. return QualType();
  8709. }
  8710. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8711. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8712. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8713. if (LHSBT != RHSBT &&
  8714. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8715. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8716. << LHS.get()->getType() << RHS.get()->getType()
  8717. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8718. }
  8719. }
  8720. } else {
  8721. // ...else expand RHS to match the number of elements in LHS.
  8722. QualType VecTy =
  8723. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8724. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8725. }
  8726. return LHSType;
  8727. }
  8728. // C99 6.5.7
  8729. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8730. SourceLocation Loc, BinaryOperatorKind Opc,
  8731. bool IsCompAssign) {
  8732. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8733. // Vector shifts promote their scalar inputs to vector type.
  8734. if (LHS.get()->getType()->isVectorType() ||
  8735. RHS.get()->getType()->isVectorType()) {
  8736. if (LangOpts.ZVector) {
  8737. // The shift operators for the z vector extensions work basically
  8738. // like general shifts, except that neither the LHS nor the RHS is
  8739. // allowed to be a "vector bool".
  8740. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8741. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8742. return InvalidOperands(Loc, LHS, RHS);
  8743. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8744. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8745. return InvalidOperands(Loc, LHS, RHS);
  8746. }
  8747. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8748. }
  8749. // Shifts don't perform usual arithmetic conversions, they just do integer
  8750. // promotions on each operand. C99 6.5.7p3
  8751. // For the LHS, do usual unary conversions, but then reset them away
  8752. // if this is a compound assignment.
  8753. ExprResult OldLHS = LHS;
  8754. LHS = UsualUnaryConversions(LHS.get());
  8755. if (LHS.isInvalid())
  8756. return QualType();
  8757. QualType LHSType = LHS.get()->getType();
  8758. if (IsCompAssign) LHS = OldLHS;
  8759. // The RHS is simpler.
  8760. RHS = UsualUnaryConversions(RHS.get());
  8761. if (RHS.isInvalid())
  8762. return QualType();
  8763. QualType RHSType = RHS.get()->getType();
  8764. // C99 6.5.7p2: Each of the operands shall have integer type.
  8765. if (!LHSType->hasIntegerRepresentation() ||
  8766. !RHSType->hasIntegerRepresentation())
  8767. return InvalidOperands(Loc, LHS, RHS);
  8768. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8769. // hasIntegerRepresentation() above instead of this.
  8770. if (isScopedEnumerationType(LHSType) ||
  8771. isScopedEnumerationType(RHSType)) {
  8772. return InvalidOperands(Loc, LHS, RHS);
  8773. }
  8774. // Sanity-check shift operands
  8775. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8776. // "The type of the result is that of the promoted left operand."
  8777. return LHSType;
  8778. }
  8779. /// If two different enums are compared, raise a warning.
  8780. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8781. Expr *RHS) {
  8782. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8783. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8784. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8785. if (!LHSEnumType)
  8786. return;
  8787. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8788. if (!RHSEnumType)
  8789. return;
  8790. // Ignore anonymous enums.
  8791. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8792. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8793. return;
  8794. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8795. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8796. return;
  8797. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8798. return;
  8799. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8800. << LHSStrippedType << RHSStrippedType
  8801. << LHS->getSourceRange() << RHS->getSourceRange();
  8802. }
  8803. /// Diagnose bad pointer comparisons.
  8804. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8805. ExprResult &LHS, ExprResult &RHS,
  8806. bool IsError) {
  8807. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8808. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8809. << LHS.get()->getType() << RHS.get()->getType()
  8810. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8811. }
  8812. /// Returns false if the pointers are converted to a composite type,
  8813. /// true otherwise.
  8814. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8815. ExprResult &LHS, ExprResult &RHS) {
  8816. // C++ [expr.rel]p2:
  8817. // [...] Pointer conversions (4.10) and qualification
  8818. // conversions (4.4) are performed on pointer operands (or on
  8819. // a pointer operand and a null pointer constant) to bring
  8820. // them to their composite pointer type. [...]
  8821. //
  8822. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8823. // comparisons of pointers.
  8824. QualType LHSType = LHS.get()->getType();
  8825. QualType RHSType = RHS.get()->getType();
  8826. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8827. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8828. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8829. if (T.isNull()) {
  8830. if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
  8831. (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
  8832. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8833. else
  8834. S.InvalidOperands(Loc, LHS, RHS);
  8835. return true;
  8836. }
  8837. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8838. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8839. return false;
  8840. }
  8841. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8842. ExprResult &LHS,
  8843. ExprResult &RHS,
  8844. bool IsError) {
  8845. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8846. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8847. << LHS.get()->getType() << RHS.get()->getType()
  8848. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8849. }
  8850. static bool isObjCObjectLiteral(ExprResult &E) {
  8851. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8852. case Stmt::ObjCArrayLiteralClass:
  8853. case Stmt::ObjCDictionaryLiteralClass:
  8854. case Stmt::ObjCStringLiteralClass:
  8855. case Stmt::ObjCBoxedExprClass:
  8856. return true;
  8857. default:
  8858. // Note that ObjCBoolLiteral is NOT an object literal!
  8859. return false;
  8860. }
  8861. }
  8862. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8863. const ObjCObjectPointerType *Type =
  8864. LHS->getType()->getAs<ObjCObjectPointerType>();
  8865. // If this is not actually an Objective-C object, bail out.
  8866. if (!Type)
  8867. return false;
  8868. // Get the LHS object's interface type.
  8869. QualType InterfaceType = Type->getPointeeType();
  8870. // If the RHS isn't an Objective-C object, bail out.
  8871. if (!RHS->getType()->isObjCObjectPointerType())
  8872. return false;
  8873. // Try to find the -isEqual: method.
  8874. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8875. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8876. InterfaceType,
  8877. /*IsInstance=*/true);
  8878. if (!Method) {
  8879. if (Type->isObjCIdType()) {
  8880. // For 'id', just check the global pool.
  8881. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8882. /*receiverId=*/true);
  8883. } else {
  8884. // Check protocols.
  8885. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8886. /*IsInstance=*/true);
  8887. }
  8888. }
  8889. if (!Method)
  8890. return false;
  8891. QualType T = Method->parameters()[0]->getType();
  8892. if (!T->isObjCObjectPointerType())
  8893. return false;
  8894. QualType R = Method->getReturnType();
  8895. if (!R->isScalarType())
  8896. return false;
  8897. return true;
  8898. }
  8899. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8900. FromE = FromE->IgnoreParenImpCasts();
  8901. switch (FromE->getStmtClass()) {
  8902. default:
  8903. break;
  8904. case Stmt::ObjCStringLiteralClass:
  8905. // "string literal"
  8906. return LK_String;
  8907. case Stmt::ObjCArrayLiteralClass:
  8908. // "array literal"
  8909. return LK_Array;
  8910. case Stmt::ObjCDictionaryLiteralClass:
  8911. // "dictionary literal"
  8912. return LK_Dictionary;
  8913. case Stmt::BlockExprClass:
  8914. return LK_Block;
  8915. case Stmt::ObjCBoxedExprClass: {
  8916. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8917. switch (Inner->getStmtClass()) {
  8918. case Stmt::IntegerLiteralClass:
  8919. case Stmt::FloatingLiteralClass:
  8920. case Stmt::CharacterLiteralClass:
  8921. case Stmt::ObjCBoolLiteralExprClass:
  8922. case Stmt::CXXBoolLiteralExprClass:
  8923. // "numeric literal"
  8924. return LK_Numeric;
  8925. case Stmt::ImplicitCastExprClass: {
  8926. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8927. // Boolean literals can be represented by implicit casts.
  8928. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8929. return LK_Numeric;
  8930. break;
  8931. }
  8932. default:
  8933. break;
  8934. }
  8935. return LK_Boxed;
  8936. }
  8937. }
  8938. return LK_None;
  8939. }
  8940. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8941. ExprResult &LHS, ExprResult &RHS,
  8942. BinaryOperator::Opcode Opc){
  8943. Expr *Literal;
  8944. Expr *Other;
  8945. if (isObjCObjectLiteral(LHS)) {
  8946. Literal = LHS.get();
  8947. Other = RHS.get();
  8948. } else {
  8949. Literal = RHS.get();
  8950. Other = LHS.get();
  8951. }
  8952. // Don't warn on comparisons against nil.
  8953. Other = Other->IgnoreParenCasts();
  8954. if (Other->isNullPointerConstant(S.getASTContext(),
  8955. Expr::NPC_ValueDependentIsNotNull))
  8956. return;
  8957. // This should be kept in sync with warn_objc_literal_comparison.
  8958. // LK_String should always be after the other literals, since it has its own
  8959. // warning flag.
  8960. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8961. assert(LiteralKind != Sema::LK_Block);
  8962. if (LiteralKind == Sema::LK_None) {
  8963. llvm_unreachable("Unknown Objective-C object literal kind");
  8964. }
  8965. if (LiteralKind == Sema::LK_String)
  8966. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8967. << Literal->getSourceRange();
  8968. else
  8969. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8970. << LiteralKind << Literal->getSourceRange();
  8971. if (BinaryOperator::isEqualityOp(Opc) &&
  8972. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8973. SourceLocation Start = LHS.get()->getBeginLoc();
  8974. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8975. CharSourceRange OpRange =
  8976. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8977. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8978. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8979. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8980. << FixItHint::CreateInsertion(End, "]");
  8981. }
  8982. }
  8983. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8984. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8985. ExprResult &RHS, SourceLocation Loc,
  8986. BinaryOperatorKind Opc) {
  8987. // Check that left hand side is !something.
  8988. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8989. if (!UO || UO->getOpcode() != UO_LNot) return;
  8990. // Only check if the right hand side is non-bool arithmetic type.
  8991. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8992. // Make sure that the something in !something is not bool.
  8993. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8994. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8995. // Emit warning.
  8996. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8997. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8998. << Loc << IsBitwiseOp;
  8999. // First note suggest !(x < y)
  9000. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  9001. SourceLocation FirstClose = RHS.get()->getEndLoc();
  9002. FirstClose = S.getLocForEndOfToken(FirstClose);
  9003. if (FirstClose.isInvalid())
  9004. FirstOpen = SourceLocation();
  9005. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  9006. << IsBitwiseOp
  9007. << FixItHint::CreateInsertion(FirstOpen, "(")
  9008. << FixItHint::CreateInsertion(FirstClose, ")");
  9009. // Second note suggests (!x) < y
  9010. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  9011. SourceLocation SecondClose = LHS.get()->getEndLoc();
  9012. SecondClose = S.getLocForEndOfToken(SecondClose);
  9013. if (SecondClose.isInvalid())
  9014. SecondOpen = SourceLocation();
  9015. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  9016. << FixItHint::CreateInsertion(SecondOpen, "(")
  9017. << FixItHint::CreateInsertion(SecondClose, ")");
  9018. }
  9019. // Returns true if E refers to a non-weak array.
  9020. static bool checkForArray(const Expr *E) {
  9021. const ValueDecl *D = nullptr;
  9022. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  9023. D = DR->getDecl();
  9024. } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  9025. if (Mem->isImplicitAccess())
  9026. D = Mem->getMemberDecl();
  9027. }
  9028. if (!D)
  9029. return false;
  9030. return D->getType()->isArrayType() && !D->isWeak();
  9031. }
  9032. /// Diagnose some forms of syntactically-obvious tautological comparison.
  9033. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  9034. Expr *LHS, Expr *RHS,
  9035. BinaryOperatorKind Opc) {
  9036. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  9037. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  9038. QualType LHSType = LHS->getType();
  9039. QualType RHSType = RHS->getType();
  9040. if (LHSType->hasFloatingRepresentation() ||
  9041. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  9042. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  9043. S.inTemplateInstantiation())
  9044. return;
  9045. // Comparisons between two array types are ill-formed for operator<=>, so
  9046. // we shouldn't emit any additional warnings about it.
  9047. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  9048. return;
  9049. // For non-floating point types, check for self-comparisons of the form
  9050. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9051. // often indicate logic errors in the program.
  9052. //
  9053. // NOTE: Don't warn about comparison expressions resulting from macro
  9054. // expansion. Also don't warn about comparisons which are only self
  9055. // comparisons within a template instantiation. The warnings should catch
  9056. // obvious cases in the definition of the template anyways. The idea is to
  9057. // warn when the typed comparison operator will always evaluate to the same
  9058. // result.
  9059. // Used for indexing into %select in warn_comparison_always
  9060. enum {
  9061. AlwaysConstant,
  9062. AlwaysTrue,
  9063. AlwaysFalse,
  9064. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  9065. };
  9066. if (Expr::isSameComparisonOperand(LHS, RHS)) {
  9067. unsigned Result;
  9068. switch (Opc) {
  9069. case BO_EQ: case BO_LE: case BO_GE:
  9070. Result = AlwaysTrue;
  9071. break;
  9072. case BO_NE: case BO_LT: case BO_GT:
  9073. Result = AlwaysFalse;
  9074. break;
  9075. case BO_Cmp:
  9076. Result = AlwaysEqual;
  9077. break;
  9078. default:
  9079. Result = AlwaysConstant;
  9080. break;
  9081. }
  9082. S.DiagRuntimeBehavior(Loc, nullptr,
  9083. S.PDiag(diag::warn_comparison_always)
  9084. << 0 /*self-comparison*/
  9085. << Result);
  9086. } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
  9087. // What is it always going to evaluate to?
  9088. unsigned Result;
  9089. switch(Opc) {
  9090. case BO_EQ: // e.g. array1 == array2
  9091. Result = AlwaysFalse;
  9092. break;
  9093. case BO_NE: // e.g. array1 != array2
  9094. Result = AlwaysTrue;
  9095. break;
  9096. default: // e.g. array1 <= array2
  9097. // The best we can say is 'a constant'
  9098. Result = AlwaysConstant;
  9099. break;
  9100. }
  9101. S.DiagRuntimeBehavior(Loc, nullptr,
  9102. S.PDiag(diag::warn_comparison_always)
  9103. << 1 /*array comparison*/
  9104. << Result);
  9105. }
  9106. if (isa<CastExpr>(LHSStripped))
  9107. LHSStripped = LHSStripped->IgnoreParenCasts();
  9108. if (isa<CastExpr>(RHSStripped))
  9109. RHSStripped = RHSStripped->IgnoreParenCasts();
  9110. // Warn about comparisons against a string constant (unless the other
  9111. // operand is null); the user probably wants strcmp.
  9112. Expr *LiteralString = nullptr;
  9113. Expr *LiteralStringStripped = nullptr;
  9114. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  9115. !RHSStripped->isNullPointerConstant(S.Context,
  9116. Expr::NPC_ValueDependentIsNull)) {
  9117. LiteralString = LHS;
  9118. LiteralStringStripped = LHSStripped;
  9119. } else if ((isa<StringLiteral>(RHSStripped) ||
  9120. isa<ObjCEncodeExpr>(RHSStripped)) &&
  9121. !LHSStripped->isNullPointerConstant(S.Context,
  9122. Expr::NPC_ValueDependentIsNull)) {
  9123. LiteralString = RHS;
  9124. LiteralStringStripped = RHSStripped;
  9125. }
  9126. if (LiteralString) {
  9127. S.DiagRuntimeBehavior(Loc, nullptr,
  9128. S.PDiag(diag::warn_stringcompare)
  9129. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  9130. << LiteralString->getSourceRange());
  9131. }
  9132. }
  9133. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  9134. switch (CK) {
  9135. default: {
  9136. #ifndef NDEBUG
  9137. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  9138. << "\n";
  9139. #endif
  9140. llvm_unreachable("unhandled cast kind");
  9141. }
  9142. case CK_UserDefinedConversion:
  9143. return ICK_Identity;
  9144. case CK_LValueToRValue:
  9145. return ICK_Lvalue_To_Rvalue;
  9146. case CK_ArrayToPointerDecay:
  9147. return ICK_Array_To_Pointer;
  9148. case CK_FunctionToPointerDecay:
  9149. return ICK_Function_To_Pointer;
  9150. case CK_IntegralCast:
  9151. return ICK_Integral_Conversion;
  9152. case CK_FloatingCast:
  9153. return ICK_Floating_Conversion;
  9154. case CK_IntegralToFloating:
  9155. case CK_FloatingToIntegral:
  9156. return ICK_Floating_Integral;
  9157. case CK_IntegralComplexCast:
  9158. case CK_FloatingComplexCast:
  9159. case CK_FloatingComplexToIntegralComplex:
  9160. case CK_IntegralComplexToFloatingComplex:
  9161. return ICK_Complex_Conversion;
  9162. case CK_FloatingComplexToReal:
  9163. case CK_FloatingRealToComplex:
  9164. case CK_IntegralComplexToReal:
  9165. case CK_IntegralRealToComplex:
  9166. return ICK_Complex_Real;
  9167. }
  9168. }
  9169. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  9170. QualType FromType,
  9171. SourceLocation Loc) {
  9172. // Check for a narrowing implicit conversion.
  9173. StandardConversionSequence SCS;
  9174. SCS.setAsIdentityConversion();
  9175. SCS.setToType(0, FromType);
  9176. SCS.setToType(1, ToType);
  9177. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9178. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  9179. APValue PreNarrowingValue;
  9180. QualType PreNarrowingType;
  9181. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  9182. PreNarrowingType,
  9183. /*IgnoreFloatToIntegralConversion*/ true)) {
  9184. case NK_Dependent_Narrowing:
  9185. // Implicit conversion to a narrower type, but the expression is
  9186. // value-dependent so we can't tell whether it's actually narrowing.
  9187. case NK_Not_Narrowing:
  9188. return false;
  9189. case NK_Constant_Narrowing:
  9190. // Implicit conversion to a narrower type, and the value is not a constant
  9191. // expression.
  9192. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9193. << /*Constant*/ 1
  9194. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  9195. return true;
  9196. case NK_Variable_Narrowing:
  9197. // Implicit conversion to a narrower type, and the value is not a constant
  9198. // expression.
  9199. case NK_Type_Narrowing:
  9200. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9201. << /*Constant*/ 0 << FromType << ToType;
  9202. // TODO: It's not a constant expression, but what if the user intended it
  9203. // to be? Can we produce notes to help them figure out why it isn't?
  9204. return true;
  9205. }
  9206. llvm_unreachable("unhandled case in switch");
  9207. }
  9208. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9209. ExprResult &LHS,
  9210. ExprResult &RHS,
  9211. SourceLocation Loc) {
  9212. using CCT = ComparisonCategoryType;
  9213. QualType LHSType = LHS.get()->getType();
  9214. QualType RHSType = RHS.get()->getType();
  9215. // Dig out the original argument type and expression before implicit casts
  9216. // were applied. These are the types/expressions we need to check the
  9217. // [expr.spaceship] requirements against.
  9218. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9219. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9220. QualType LHSStrippedType = LHSStripped.get()->getType();
  9221. QualType RHSStrippedType = RHSStripped.get()->getType();
  9222. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9223. // other is not, the program is ill-formed.
  9224. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9225. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9226. return QualType();
  9227. }
  9228. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9229. RHSStrippedType->isEnumeralType();
  9230. if (NumEnumArgs == 1) {
  9231. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9232. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9233. if (OtherTy->hasFloatingRepresentation()) {
  9234. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9235. return QualType();
  9236. }
  9237. }
  9238. if (NumEnumArgs == 2) {
  9239. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9240. // type E, the operator yields the result of converting the operands
  9241. // to the underlying type of E and applying <=> to the converted operands.
  9242. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9243. S.InvalidOperands(Loc, LHS, RHS);
  9244. return QualType();
  9245. }
  9246. QualType IntType =
  9247. LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
  9248. assert(IntType->isArithmeticType());
  9249. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9250. // promote the boolean type, and all other promotable integer types, to
  9251. // avoid this.
  9252. if (IntType->isPromotableIntegerType())
  9253. IntType = S.Context.getPromotedIntegerType(IntType);
  9254. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9255. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9256. LHSType = RHSType = IntType;
  9257. }
  9258. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9259. // usual arithmetic conversions are applied to the operands.
  9260. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9261. if (LHS.isInvalid() || RHS.isInvalid())
  9262. return QualType();
  9263. if (Type.isNull())
  9264. return S.InvalidOperands(Loc, LHS, RHS);
  9265. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9266. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9267. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9268. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9269. RHS.get()->getBeginLoc());
  9270. if (HasNarrowing)
  9271. return QualType();
  9272. assert(!Type.isNull() && "composite type for <=> has not been set");
  9273. auto TypeKind = [&]() {
  9274. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9275. if (CT->getElementType()->hasFloatingRepresentation())
  9276. return CCT::WeakEquality;
  9277. return CCT::StrongEquality;
  9278. }
  9279. if (Type->isIntegralOrEnumerationType())
  9280. return CCT::StrongOrdering;
  9281. if (Type->hasFloatingRepresentation())
  9282. return CCT::PartialOrdering;
  9283. llvm_unreachable("other types are unimplemented");
  9284. }();
  9285. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9286. }
  9287. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9288. ExprResult &RHS,
  9289. SourceLocation Loc,
  9290. BinaryOperatorKind Opc) {
  9291. if (Opc == BO_Cmp)
  9292. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9293. // C99 6.5.8p3 / C99 6.5.9p4
  9294. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9295. if (LHS.isInvalid() || RHS.isInvalid())
  9296. return QualType();
  9297. if (Type.isNull())
  9298. return S.InvalidOperands(Loc, LHS, RHS);
  9299. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9300. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9301. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9302. return S.InvalidOperands(Loc, LHS, RHS);
  9303. // Check for comparisons of floating point operands using != and ==.
  9304. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9305. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9306. // The result of comparisons is 'bool' in C++, 'int' in C.
  9307. return S.Context.getLogicalOperationType();
  9308. }
  9309. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  9310. if (!NullE.get()->getType()->isAnyPointerType())
  9311. return;
  9312. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  9313. if (!E.get()->getType()->isAnyPointerType() &&
  9314. E.get()->isNullPointerConstant(Context,
  9315. Expr::NPC_ValueDependentIsNotNull) ==
  9316. Expr::NPCK_ZeroExpression) {
  9317. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  9318. if (CL->getValue() == 0)
  9319. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9320. << NullValue
  9321. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9322. NullValue ? "NULL" : "(void *)0");
  9323. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  9324. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  9325. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  9326. if (T == Context.CharTy)
  9327. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9328. << NullValue
  9329. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9330. NullValue ? "NULL" : "(void *)0");
  9331. }
  9332. }
  9333. }
  9334. // C99 6.5.8, C++ [expr.rel]
  9335. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9336. SourceLocation Loc,
  9337. BinaryOperatorKind Opc) {
  9338. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9339. bool IsThreeWay = Opc == BO_Cmp;
  9340. auto IsAnyPointerType = [](ExprResult E) {
  9341. QualType Ty = E.get()->getType();
  9342. return Ty->isPointerType() || Ty->isMemberPointerType();
  9343. };
  9344. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9345. // type, array-to-pointer, ..., conversions are performed on both operands to
  9346. // bring them to their composite type.
  9347. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9348. // any type-related checks.
  9349. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9350. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9351. if (LHS.isInvalid())
  9352. return QualType();
  9353. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9354. if (RHS.isInvalid())
  9355. return QualType();
  9356. } else {
  9357. LHS = DefaultLvalueConversion(LHS.get());
  9358. if (LHS.isInvalid())
  9359. return QualType();
  9360. RHS = DefaultLvalueConversion(RHS.get());
  9361. if (RHS.isInvalid())
  9362. return QualType();
  9363. }
  9364. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  9365. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  9366. CheckPtrComparisonWithNullChar(LHS, RHS);
  9367. CheckPtrComparisonWithNullChar(RHS, LHS);
  9368. }
  9369. // Handle vector comparisons separately.
  9370. if (LHS.get()->getType()->isVectorType() ||
  9371. RHS.get()->getType()->isVectorType())
  9372. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9373. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9374. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9375. QualType LHSType = LHS.get()->getType();
  9376. QualType RHSType = RHS.get()->getType();
  9377. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9378. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9379. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9380. const Expr::NullPointerConstantKind LHSNullKind =
  9381. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9382. const Expr::NullPointerConstantKind RHSNullKind =
  9383. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9384. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9385. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9386. auto computeResultTy = [&]() {
  9387. if (Opc != BO_Cmp)
  9388. return Context.getLogicalOperationType();
  9389. assert(getLangOpts().CPlusPlus);
  9390. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9391. QualType CompositeTy = LHS.get()->getType();
  9392. assert(!CompositeTy->isReferenceType());
  9393. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9394. return CheckComparisonCategoryType(Kind, Loc);
  9395. };
  9396. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9397. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9398. // result is of type std::strong_equality
  9399. if (CompositeTy->isFunctionPointerType() ||
  9400. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9401. // FIXME: consider making the function pointer case produce
  9402. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9403. // and direction polls
  9404. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9405. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9406. // pointer type, p <=> q is of type std::strong_ordering.
  9407. if (CompositeTy->isPointerType()) {
  9408. // P0946R0: Comparisons between a null pointer constant and an object
  9409. // pointer result in std::strong_equality
  9410. if (LHSIsNull != RHSIsNull)
  9411. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9412. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9413. }
  9414. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9415. // TODO: Extend support for operator<=> to ObjC types.
  9416. return InvalidOperands(Loc, LHS, RHS);
  9417. };
  9418. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9419. bool IsEquality = Opc == BO_EQ;
  9420. if (RHSIsNull)
  9421. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9422. RHS.get()->getSourceRange());
  9423. else
  9424. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9425. LHS.get()->getSourceRange());
  9426. }
  9427. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9428. (RHSType->isIntegerType() && !RHSIsNull)) {
  9429. // Skip normal pointer conversion checks in this case; we have better
  9430. // diagnostics for this below.
  9431. } else if (getLangOpts().CPlusPlus) {
  9432. // Equality comparison of a function pointer to a void pointer is invalid,
  9433. // but we allow it as an extension.
  9434. // FIXME: If we really want to allow this, should it be part of composite
  9435. // pointer type computation so it works in conditionals too?
  9436. if (!IsRelational &&
  9437. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9438. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9439. // This is a gcc extension compatibility comparison.
  9440. // In a SFINAE context, we treat this as a hard error to maintain
  9441. // conformance with the C++ standard.
  9442. diagnoseFunctionPointerToVoidComparison(
  9443. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9444. if (isSFINAEContext())
  9445. return QualType();
  9446. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9447. return computeResultTy();
  9448. }
  9449. // C++ [expr.eq]p2:
  9450. // If at least one operand is a pointer [...] bring them to their
  9451. // composite pointer type.
  9452. // C++ [expr.spaceship]p6
  9453. // If at least one of the operands is of pointer type, [...] bring them
  9454. // to their composite pointer type.
  9455. // C++ [expr.rel]p2:
  9456. // If both operands are pointers, [...] bring them to their composite
  9457. // pointer type.
  9458. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9459. (IsRelational ? 2 : 1) &&
  9460. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9461. RHSType->isObjCObjectPointerType()))) {
  9462. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9463. return QualType();
  9464. return computeResultTy();
  9465. }
  9466. } else if (LHSType->isPointerType() &&
  9467. RHSType->isPointerType()) { // C99 6.5.8p2
  9468. // All of the following pointer-related warnings are GCC extensions, except
  9469. // when handling null pointer constants.
  9470. QualType LCanPointeeTy =
  9471. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9472. QualType RCanPointeeTy =
  9473. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9474. // C99 6.5.9p2 and C99 6.5.8p2
  9475. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9476. RCanPointeeTy.getUnqualifiedType())) {
  9477. // Valid unless a relational comparison of function pointers
  9478. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9479. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9480. << LHSType << RHSType << LHS.get()->getSourceRange()
  9481. << RHS.get()->getSourceRange();
  9482. }
  9483. } else if (!IsRelational &&
  9484. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9485. // Valid unless comparison between non-null pointer and function pointer
  9486. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9487. && !LHSIsNull && !RHSIsNull)
  9488. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9489. /*isError*/false);
  9490. } else {
  9491. // Invalid
  9492. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9493. }
  9494. if (LCanPointeeTy != RCanPointeeTy) {
  9495. // Treat NULL constant as a special case in OpenCL.
  9496. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9497. const PointerType *LHSPtr = LHSType->castAs<PointerType>();
  9498. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
  9499. Diag(Loc,
  9500. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9501. << LHSType << RHSType << 0 /* comparison */
  9502. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9503. }
  9504. }
  9505. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9506. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9507. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9508. : CK_BitCast;
  9509. if (LHSIsNull && !RHSIsNull)
  9510. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9511. else
  9512. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9513. }
  9514. return computeResultTy();
  9515. }
  9516. if (getLangOpts().CPlusPlus) {
  9517. // C++ [expr.eq]p4:
  9518. // Two operands of type std::nullptr_t or one operand of type
  9519. // std::nullptr_t and the other a null pointer constant compare equal.
  9520. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9521. if (LHSType->isNullPtrType()) {
  9522. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9523. return computeResultTy();
  9524. }
  9525. if (RHSType->isNullPtrType()) {
  9526. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9527. return computeResultTy();
  9528. }
  9529. }
  9530. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9531. // These aren't covered by the composite pointer type rules.
  9532. if (!IsRelational && RHSType->isNullPtrType() &&
  9533. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9534. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9535. return computeResultTy();
  9536. }
  9537. if (!IsRelational && LHSType->isNullPtrType() &&
  9538. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9539. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9540. return computeResultTy();
  9541. }
  9542. if (IsRelational &&
  9543. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9544. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9545. // HACK: Relational comparison of nullptr_t against a pointer type is
  9546. // invalid per DR583, but we allow it within std::less<> and friends,
  9547. // since otherwise common uses of it break.
  9548. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9549. // friends to have std::nullptr_t overload candidates.
  9550. DeclContext *DC = CurContext;
  9551. if (isa<FunctionDecl>(DC))
  9552. DC = DC->getParent();
  9553. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9554. if (CTSD->isInStdNamespace() &&
  9555. llvm::StringSwitch<bool>(CTSD->getName())
  9556. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9557. .Default(false)) {
  9558. if (RHSType->isNullPtrType())
  9559. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9560. else
  9561. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9562. return computeResultTy();
  9563. }
  9564. }
  9565. }
  9566. // C++ [expr.eq]p2:
  9567. // If at least one operand is a pointer to member, [...] bring them to
  9568. // their composite pointer type.
  9569. if (!IsRelational &&
  9570. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9571. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9572. return QualType();
  9573. else
  9574. return computeResultTy();
  9575. }
  9576. }
  9577. // Handle block pointer types.
  9578. if (!IsRelational && LHSType->isBlockPointerType() &&
  9579. RHSType->isBlockPointerType()) {
  9580. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9581. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9582. if (!LHSIsNull && !RHSIsNull &&
  9583. !Context.typesAreCompatible(lpointee, rpointee)) {
  9584. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9585. << LHSType << RHSType << LHS.get()->getSourceRange()
  9586. << RHS.get()->getSourceRange();
  9587. }
  9588. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9589. return computeResultTy();
  9590. }
  9591. // Allow block pointers to be compared with null pointer constants.
  9592. if (!IsRelational
  9593. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9594. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9595. if (!LHSIsNull && !RHSIsNull) {
  9596. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9597. ->getPointeeType()->isVoidType())
  9598. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9599. ->getPointeeType()->isVoidType())))
  9600. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9601. << LHSType << RHSType << LHS.get()->getSourceRange()
  9602. << RHS.get()->getSourceRange();
  9603. }
  9604. if (LHSIsNull && !RHSIsNull)
  9605. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9606. RHSType->isPointerType() ? CK_BitCast
  9607. : CK_AnyPointerToBlockPointerCast);
  9608. else
  9609. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9610. LHSType->isPointerType() ? CK_BitCast
  9611. : CK_AnyPointerToBlockPointerCast);
  9612. return computeResultTy();
  9613. }
  9614. if (LHSType->isObjCObjectPointerType() ||
  9615. RHSType->isObjCObjectPointerType()) {
  9616. const PointerType *LPT = LHSType->getAs<PointerType>();
  9617. const PointerType *RPT = RHSType->getAs<PointerType>();
  9618. if (LPT || RPT) {
  9619. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9620. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9621. if (!LPtrToVoid && !RPtrToVoid &&
  9622. !Context.typesAreCompatible(LHSType, RHSType)) {
  9623. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9624. /*isError*/false);
  9625. }
  9626. if (LHSIsNull && !RHSIsNull) {
  9627. Expr *E = LHS.get();
  9628. if (getLangOpts().ObjCAutoRefCount)
  9629. CheckObjCConversion(SourceRange(), RHSType, E,
  9630. CCK_ImplicitConversion);
  9631. LHS = ImpCastExprToType(E, RHSType,
  9632. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9633. }
  9634. else {
  9635. Expr *E = RHS.get();
  9636. if (getLangOpts().ObjCAutoRefCount)
  9637. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9638. /*Diagnose=*/true,
  9639. /*DiagnoseCFAudited=*/false, Opc);
  9640. RHS = ImpCastExprToType(E, LHSType,
  9641. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9642. }
  9643. return computeResultTy();
  9644. }
  9645. if (LHSType->isObjCObjectPointerType() &&
  9646. RHSType->isObjCObjectPointerType()) {
  9647. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9648. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9649. /*isError*/false);
  9650. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9651. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9652. if (LHSIsNull && !RHSIsNull)
  9653. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9654. else
  9655. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9656. return computeResultTy();
  9657. }
  9658. if (!IsRelational && LHSType->isBlockPointerType() &&
  9659. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9660. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9661. CK_BlockPointerToObjCPointerCast);
  9662. return computeResultTy();
  9663. } else if (!IsRelational &&
  9664. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9665. RHSType->isBlockPointerType()) {
  9666. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9667. CK_BlockPointerToObjCPointerCast);
  9668. return computeResultTy();
  9669. }
  9670. }
  9671. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9672. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9673. unsigned DiagID = 0;
  9674. bool isError = false;
  9675. if (LangOpts.DebuggerSupport) {
  9676. // Under a debugger, allow the comparison of pointers to integers,
  9677. // since users tend to want to compare addresses.
  9678. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9679. (RHSIsNull && RHSType->isIntegerType())) {
  9680. if (IsRelational) {
  9681. isError = getLangOpts().CPlusPlus;
  9682. DiagID =
  9683. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9684. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9685. }
  9686. } else if (getLangOpts().CPlusPlus) {
  9687. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9688. isError = true;
  9689. } else if (IsRelational)
  9690. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9691. else
  9692. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9693. if (DiagID) {
  9694. Diag(Loc, DiagID)
  9695. << LHSType << RHSType << LHS.get()->getSourceRange()
  9696. << RHS.get()->getSourceRange();
  9697. if (isError)
  9698. return QualType();
  9699. }
  9700. if (LHSType->isIntegerType())
  9701. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9702. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9703. else
  9704. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9705. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9706. return computeResultTy();
  9707. }
  9708. // Handle block pointers.
  9709. if (!IsRelational && RHSIsNull
  9710. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9711. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9712. return computeResultTy();
  9713. }
  9714. if (!IsRelational && LHSIsNull
  9715. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9716. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9717. return computeResultTy();
  9718. }
  9719. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9720. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9721. return computeResultTy();
  9722. }
  9723. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9724. return computeResultTy();
  9725. }
  9726. if (LHSIsNull && RHSType->isQueueT()) {
  9727. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9728. return computeResultTy();
  9729. }
  9730. if (LHSType->isQueueT() && RHSIsNull) {
  9731. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9732. return computeResultTy();
  9733. }
  9734. }
  9735. return InvalidOperands(Loc, LHS, RHS);
  9736. }
  9737. // Return a signed ext_vector_type that is of identical size and number of
  9738. // elements. For floating point vectors, return an integer type of identical
  9739. // size and number of elements. In the non ext_vector_type case, search from
  9740. // the largest type to the smallest type to avoid cases where long long == long,
  9741. // where long gets picked over long long.
  9742. QualType Sema::GetSignedVectorType(QualType V) {
  9743. const VectorType *VTy = V->castAs<VectorType>();
  9744. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9745. if (isa<ExtVectorType>(VTy)) {
  9746. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9747. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9748. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9749. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9750. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9751. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9752. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9753. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9754. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9755. "Unhandled vector element size in vector compare");
  9756. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9757. }
  9758. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9759. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9760. VectorType::GenericVector);
  9761. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9762. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9763. VectorType::GenericVector);
  9764. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9765. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9766. VectorType::GenericVector);
  9767. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9768. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9769. VectorType::GenericVector);
  9770. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9771. "Unhandled vector element size in vector compare");
  9772. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9773. VectorType::GenericVector);
  9774. }
  9775. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9776. /// operates on extended vector types. Instead of producing an IntTy result,
  9777. /// like a scalar comparison, a vector comparison produces a vector of integer
  9778. /// types.
  9779. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9780. SourceLocation Loc,
  9781. BinaryOperatorKind Opc) {
  9782. // Check to make sure we're operating on vectors of the same type and width,
  9783. // Allowing one side to be a scalar of element type.
  9784. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9785. /*AllowBothBool*/true,
  9786. /*AllowBoolConversions*/getLangOpts().ZVector);
  9787. if (vType.isNull())
  9788. return vType;
  9789. QualType LHSType = LHS.get()->getType();
  9790. // If AltiVec, the comparison results in a numeric type, i.e.
  9791. // bool for C++, int for C
  9792. if (getLangOpts().AltiVec &&
  9793. vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9794. return Context.getLogicalOperationType();
  9795. // For non-floating point types, check for self-comparisons of the form
  9796. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9797. // often indicate logic errors in the program.
  9798. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9799. // Check for comparisons of floating point operands using != and ==.
  9800. if (BinaryOperator::isEqualityOp(Opc) &&
  9801. LHSType->hasFloatingRepresentation()) {
  9802. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9803. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9804. }
  9805. // Return a signed type for the vector.
  9806. return GetSignedVectorType(vType);
  9807. }
  9808. static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
  9809. const ExprResult &XorRHS,
  9810. const SourceLocation Loc) {
  9811. // Do not diagnose macros.
  9812. if (Loc.isMacroID())
  9813. return;
  9814. bool Negative = false;
  9815. bool ExplicitPlus = false;
  9816. const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
  9817. const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
  9818. if (!LHSInt)
  9819. return;
  9820. if (!RHSInt) {
  9821. // Check negative literals.
  9822. if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
  9823. UnaryOperatorKind Opc = UO->getOpcode();
  9824. if (Opc != UO_Minus && Opc != UO_Plus)
  9825. return;
  9826. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  9827. if (!RHSInt)
  9828. return;
  9829. Negative = (Opc == UO_Minus);
  9830. ExplicitPlus = !Negative;
  9831. } else {
  9832. return;
  9833. }
  9834. }
  9835. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  9836. llvm::APInt RightSideValue = RHSInt->getValue();
  9837. if (LeftSideValue != 2 && LeftSideValue != 10)
  9838. return;
  9839. if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
  9840. return;
  9841. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  9842. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  9843. llvm::StringRef ExprStr =
  9844. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  9845. CharSourceRange XorRange =
  9846. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  9847. llvm::StringRef XorStr =
  9848. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  9849. // Do not diagnose if xor keyword/macro is used.
  9850. if (XorStr == "xor")
  9851. return;
  9852. std::string LHSStr = Lexer::getSourceText(
  9853. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  9854. S.getSourceManager(), S.getLangOpts());
  9855. std::string RHSStr = Lexer::getSourceText(
  9856. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  9857. S.getSourceManager(), S.getLangOpts());
  9858. if (Negative) {
  9859. RightSideValue = -RightSideValue;
  9860. RHSStr = "-" + RHSStr;
  9861. } else if (ExplicitPlus) {
  9862. RHSStr = "+" + RHSStr;
  9863. }
  9864. StringRef LHSStrRef = LHSStr;
  9865. StringRef RHSStrRef = RHSStr;
  9866. // Do not diagnose literals with digit separators, binary, hexadecimal, octal
  9867. // literals.
  9868. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  9869. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  9870. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  9871. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  9872. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  9873. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
  9874. LHSStrRef.find('\'') != StringRef::npos ||
  9875. RHSStrRef.find('\'') != StringRef::npos)
  9876. return;
  9877. bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
  9878. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  9879. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  9880. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  9881. std::string SuggestedExpr = "1 << " + RHSStr;
  9882. bool Overflow = false;
  9883. llvm::APInt One = (LeftSideValue - 1);
  9884. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  9885. if (Overflow) {
  9886. if (RightSideIntValue < 64)
  9887. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9888. << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
  9889. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  9890. else if (RightSideIntValue == 64)
  9891. S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
  9892. else
  9893. return;
  9894. } else {
  9895. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  9896. << ExprStr << XorValue.toString(10, true) << SuggestedExpr
  9897. << PowValue.toString(10, true)
  9898. << FixItHint::CreateReplacement(
  9899. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  9900. }
  9901. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
  9902. } else if (LeftSideValue == 10) {
  9903. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  9904. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9905. << ExprStr << XorValue.toString(10, true) << SuggestedValue
  9906. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  9907. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
  9908. }
  9909. }
  9910. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9911. SourceLocation Loc) {
  9912. // Ensure that either both operands are of the same vector type, or
  9913. // one operand is of a vector type and the other is of its element type.
  9914. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9915. /*AllowBothBool*/true,
  9916. /*AllowBoolConversions*/false);
  9917. if (vType.isNull())
  9918. return InvalidOperands(Loc, LHS, RHS);
  9919. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9920. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9921. return InvalidOperands(Loc, LHS, RHS);
  9922. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9923. // usage of the logical operators && and || with vectors in C. This
  9924. // check could be notionally dropped.
  9925. if (!getLangOpts().CPlusPlus &&
  9926. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9927. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9928. return GetSignedVectorType(LHS.get()->getType());
  9929. }
  9930. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9931. SourceLocation Loc,
  9932. BinaryOperatorKind Opc) {
  9933. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9934. bool IsCompAssign =
  9935. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9936. if (LHS.get()->getType()->isVectorType() ||
  9937. RHS.get()->getType()->isVectorType()) {
  9938. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9939. RHS.get()->getType()->hasIntegerRepresentation())
  9940. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9941. /*AllowBothBool*/true,
  9942. /*AllowBoolConversions*/getLangOpts().ZVector);
  9943. return InvalidOperands(Loc, LHS, RHS);
  9944. }
  9945. if (Opc == BO_And)
  9946. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9947. ExprResult LHSResult = LHS, RHSResult = RHS;
  9948. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9949. IsCompAssign);
  9950. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9951. return QualType();
  9952. LHS = LHSResult.get();
  9953. RHS = RHSResult.get();
  9954. if (Opc == BO_Xor)
  9955. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  9956. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9957. return compType;
  9958. return InvalidOperands(Loc, LHS, RHS);
  9959. }
  9960. // C99 6.5.[13,14]
  9961. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9962. SourceLocation Loc,
  9963. BinaryOperatorKind Opc) {
  9964. // Check vector operands differently.
  9965. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9966. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9967. bool EnumConstantInBoolContext = false;
  9968. for (const ExprResult &HS : {LHS, RHS}) {
  9969. if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
  9970. const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
  9971. if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
  9972. EnumConstantInBoolContext = true;
  9973. }
  9974. }
  9975. if (EnumConstantInBoolContext)
  9976. Diag(Loc, diag::warn_enum_constant_in_bool_context);
  9977. // Diagnose cases where the user write a logical and/or but probably meant a
  9978. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9979. // is a constant.
  9980. if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
  9981. !LHS.get()->getType()->isBooleanType() &&
  9982. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9983. // Don't warn in macros or template instantiations.
  9984. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9985. // If the RHS can be constant folded, and if it constant folds to something
  9986. // that isn't 0 or 1 (which indicate a potential logical operation that
  9987. // happened to fold to true/false) then warn.
  9988. // Parens on the RHS are ignored.
  9989. Expr::EvalResult EVResult;
  9990. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9991. llvm::APSInt Result = EVResult.Val.getInt();
  9992. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9993. !RHS.get()->getExprLoc().isMacroID()) ||
  9994. (Result != 0 && Result != 1)) {
  9995. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9996. << RHS.get()->getSourceRange()
  9997. << (Opc == BO_LAnd ? "&&" : "||");
  9998. // Suggest replacing the logical operator with the bitwise version
  9999. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  10000. << (Opc == BO_LAnd ? "&" : "|")
  10001. << FixItHint::CreateReplacement(SourceRange(
  10002. Loc, getLocForEndOfToken(Loc)),
  10003. Opc == BO_LAnd ? "&" : "|");
  10004. if (Opc == BO_LAnd)
  10005. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  10006. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  10007. << FixItHint::CreateRemoval(
  10008. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  10009. RHS.get()->getEndLoc()));
  10010. }
  10011. }
  10012. }
  10013. if (!Context.getLangOpts().CPlusPlus) {
  10014. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  10015. // not operate on the built-in scalar and vector float types.
  10016. if (Context.getLangOpts().OpenCL &&
  10017. Context.getLangOpts().OpenCLVersion < 120) {
  10018. if (LHS.get()->getType()->isFloatingType() ||
  10019. RHS.get()->getType()->isFloatingType())
  10020. return InvalidOperands(Loc, LHS, RHS);
  10021. }
  10022. LHS = UsualUnaryConversions(LHS.get());
  10023. if (LHS.isInvalid())
  10024. return QualType();
  10025. RHS = UsualUnaryConversions(RHS.get());
  10026. if (RHS.isInvalid())
  10027. return QualType();
  10028. if (!LHS.get()->getType()->isScalarType() ||
  10029. !RHS.get()->getType()->isScalarType())
  10030. return InvalidOperands(Loc, LHS, RHS);
  10031. return Context.IntTy;
  10032. }
  10033. // The following is safe because we only use this method for
  10034. // non-overloadable operands.
  10035. // C++ [expr.log.and]p1
  10036. // C++ [expr.log.or]p1
  10037. // The operands are both contextually converted to type bool.
  10038. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  10039. if (LHSRes.isInvalid())
  10040. return InvalidOperands(Loc, LHS, RHS);
  10041. LHS = LHSRes;
  10042. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  10043. if (RHSRes.isInvalid())
  10044. return InvalidOperands(Loc, LHS, RHS);
  10045. RHS = RHSRes;
  10046. // C++ [expr.log.and]p2
  10047. // C++ [expr.log.or]p2
  10048. // The result is a bool.
  10049. return Context.BoolTy;
  10050. }
  10051. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  10052. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  10053. if (!ME) return false;
  10054. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  10055. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  10056. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  10057. if (!Base) return false;
  10058. return Base->getMethodDecl() != nullptr;
  10059. }
  10060. /// Is the given expression (which must be 'const') a reference to a
  10061. /// variable which was originally non-const, but which has become
  10062. /// 'const' due to being captured within a block?
  10063. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  10064. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  10065. assert(E->isLValue() && E->getType().isConstQualified());
  10066. E = E->IgnoreParens();
  10067. // Must be a reference to a declaration from an enclosing scope.
  10068. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  10069. if (!DRE) return NCCK_None;
  10070. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  10071. // The declaration must be a variable which is not declared 'const'.
  10072. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  10073. if (!var) return NCCK_None;
  10074. if (var->getType().isConstQualified()) return NCCK_None;
  10075. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  10076. // Decide whether the first capture was for a block or a lambda.
  10077. DeclContext *DC = S.CurContext, *Prev = nullptr;
  10078. // Decide whether the first capture was for a block or a lambda.
  10079. while (DC) {
  10080. // For init-capture, it is possible that the variable belongs to the
  10081. // template pattern of the current context.
  10082. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  10083. if (var->isInitCapture() &&
  10084. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  10085. break;
  10086. if (DC == var->getDeclContext())
  10087. break;
  10088. Prev = DC;
  10089. DC = DC->getParent();
  10090. }
  10091. // Unless we have an init-capture, we've gone one step too far.
  10092. if (!var->isInitCapture())
  10093. DC = Prev;
  10094. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  10095. }
  10096. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  10097. Ty = Ty.getNonReferenceType();
  10098. if (IsDereference && Ty->isPointerType())
  10099. Ty = Ty->getPointeeType();
  10100. return !Ty.isConstQualified();
  10101. }
  10102. // Update err_typecheck_assign_const and note_typecheck_assign_const
  10103. // when this enum is changed.
  10104. enum {
  10105. ConstFunction,
  10106. ConstVariable,
  10107. ConstMember,
  10108. ConstMethod,
  10109. NestedConstMember,
  10110. ConstUnknown, // Keep as last element
  10111. };
  10112. /// Emit the "read-only variable not assignable" error and print notes to give
  10113. /// more information about why the variable is not assignable, such as pointing
  10114. /// to the declaration of a const variable, showing that a method is const, or
  10115. /// that the function is returning a const reference.
  10116. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  10117. SourceLocation Loc) {
  10118. SourceRange ExprRange = E->getSourceRange();
  10119. // Only emit one error on the first const found. All other consts will emit
  10120. // a note to the error.
  10121. bool DiagnosticEmitted = false;
  10122. // Track if the current expression is the result of a dereference, and if the
  10123. // next checked expression is the result of a dereference.
  10124. bool IsDereference = false;
  10125. bool NextIsDereference = false;
  10126. // Loop to process MemberExpr chains.
  10127. while (true) {
  10128. IsDereference = NextIsDereference;
  10129. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  10130. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10131. NextIsDereference = ME->isArrow();
  10132. const ValueDecl *VD = ME->getMemberDecl();
  10133. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  10134. // Mutable fields can be modified even if the class is const.
  10135. if (Field->isMutable()) {
  10136. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  10137. break;
  10138. }
  10139. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  10140. if (!DiagnosticEmitted) {
  10141. S.Diag(Loc, diag::err_typecheck_assign_const)
  10142. << ExprRange << ConstMember << false /*static*/ << Field
  10143. << Field->getType();
  10144. DiagnosticEmitted = true;
  10145. }
  10146. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10147. << ConstMember << false /*static*/ << Field << Field->getType()
  10148. << Field->getSourceRange();
  10149. }
  10150. E = ME->getBase();
  10151. continue;
  10152. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  10153. if (VDecl->getType().isConstQualified()) {
  10154. if (!DiagnosticEmitted) {
  10155. S.Diag(Loc, diag::err_typecheck_assign_const)
  10156. << ExprRange << ConstMember << true /*static*/ << VDecl
  10157. << VDecl->getType();
  10158. DiagnosticEmitted = true;
  10159. }
  10160. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10161. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  10162. << VDecl->getSourceRange();
  10163. }
  10164. // Static fields do not inherit constness from parents.
  10165. break;
  10166. }
  10167. break; // End MemberExpr
  10168. } else if (const ArraySubscriptExpr *ASE =
  10169. dyn_cast<ArraySubscriptExpr>(E)) {
  10170. E = ASE->getBase()->IgnoreParenImpCasts();
  10171. continue;
  10172. } else if (const ExtVectorElementExpr *EVE =
  10173. dyn_cast<ExtVectorElementExpr>(E)) {
  10174. E = EVE->getBase()->IgnoreParenImpCasts();
  10175. continue;
  10176. }
  10177. break;
  10178. }
  10179. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  10180. // Function calls
  10181. const FunctionDecl *FD = CE->getDirectCallee();
  10182. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  10183. if (!DiagnosticEmitted) {
  10184. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10185. << ConstFunction << FD;
  10186. DiagnosticEmitted = true;
  10187. }
  10188. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  10189. diag::note_typecheck_assign_const)
  10190. << ConstFunction << FD << FD->getReturnType()
  10191. << FD->getReturnTypeSourceRange();
  10192. }
  10193. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10194. // Point to variable declaration.
  10195. if (const ValueDecl *VD = DRE->getDecl()) {
  10196. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  10197. if (!DiagnosticEmitted) {
  10198. S.Diag(Loc, diag::err_typecheck_assign_const)
  10199. << ExprRange << ConstVariable << VD << VD->getType();
  10200. DiagnosticEmitted = true;
  10201. }
  10202. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10203. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  10204. }
  10205. }
  10206. } else if (isa<CXXThisExpr>(E)) {
  10207. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  10208. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  10209. if (MD->isConst()) {
  10210. if (!DiagnosticEmitted) {
  10211. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10212. << ConstMethod << MD;
  10213. DiagnosticEmitted = true;
  10214. }
  10215. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  10216. << ConstMethod << MD << MD->getSourceRange();
  10217. }
  10218. }
  10219. }
  10220. }
  10221. if (DiagnosticEmitted)
  10222. return;
  10223. // Can't determine a more specific message, so display the generic error.
  10224. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  10225. }
  10226. enum OriginalExprKind {
  10227. OEK_Variable,
  10228. OEK_Member,
  10229. OEK_LValue
  10230. };
  10231. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  10232. const RecordType *Ty,
  10233. SourceLocation Loc, SourceRange Range,
  10234. OriginalExprKind OEK,
  10235. bool &DiagnosticEmitted) {
  10236. std::vector<const RecordType *> RecordTypeList;
  10237. RecordTypeList.push_back(Ty);
  10238. unsigned NextToCheckIndex = 0;
  10239. // We walk the record hierarchy breadth-first to ensure that we print
  10240. // diagnostics in field nesting order.
  10241. while (RecordTypeList.size() > NextToCheckIndex) {
  10242. bool IsNested = NextToCheckIndex > 0;
  10243. for (const FieldDecl *Field :
  10244. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  10245. // First, check every field for constness.
  10246. QualType FieldTy = Field->getType();
  10247. if (FieldTy.isConstQualified()) {
  10248. if (!DiagnosticEmitted) {
  10249. S.Diag(Loc, diag::err_typecheck_assign_const)
  10250. << Range << NestedConstMember << OEK << VD
  10251. << IsNested << Field;
  10252. DiagnosticEmitted = true;
  10253. }
  10254. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  10255. << NestedConstMember << IsNested << Field
  10256. << FieldTy << Field->getSourceRange();
  10257. }
  10258. // Then we append it to the list to check next in order.
  10259. FieldTy = FieldTy.getCanonicalType();
  10260. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  10261. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  10262. RecordTypeList.push_back(FieldRecTy);
  10263. }
  10264. }
  10265. ++NextToCheckIndex;
  10266. }
  10267. }
  10268. /// Emit an error for the case where a record we are trying to assign to has a
  10269. /// const-qualified field somewhere in its hierarchy.
  10270. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  10271. SourceLocation Loc) {
  10272. QualType Ty = E->getType();
  10273. assert(Ty->isRecordType() && "lvalue was not record?");
  10274. SourceRange Range = E->getSourceRange();
  10275. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  10276. bool DiagEmitted = false;
  10277. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  10278. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  10279. Range, OEK_Member, DiagEmitted);
  10280. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10281. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  10282. Range, OEK_Variable, DiagEmitted);
  10283. else
  10284. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  10285. Range, OEK_LValue, DiagEmitted);
  10286. if (!DiagEmitted)
  10287. DiagnoseConstAssignment(S, E, Loc);
  10288. }
  10289. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  10290. /// emit an error and return true. If so, return false.
  10291. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  10292. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  10293. S.CheckShadowingDeclModification(E, Loc);
  10294. SourceLocation OrigLoc = Loc;
  10295. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  10296. &Loc);
  10297. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  10298. IsLV = Expr::MLV_InvalidMessageExpression;
  10299. if (IsLV == Expr::MLV_Valid)
  10300. return false;
  10301. unsigned DiagID = 0;
  10302. bool NeedType = false;
  10303. switch (IsLV) { // C99 6.5.16p2
  10304. case Expr::MLV_ConstQualified:
  10305. // Use a specialized diagnostic when we're assigning to an object
  10306. // from an enclosing function or block.
  10307. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  10308. if (NCCK == NCCK_Block)
  10309. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  10310. else
  10311. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  10312. break;
  10313. }
  10314. // In ARC, use some specialized diagnostics for occasions where we
  10315. // infer 'const'. These are always pseudo-strong variables.
  10316. if (S.getLangOpts().ObjCAutoRefCount) {
  10317. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  10318. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  10319. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  10320. // Use the normal diagnostic if it's pseudo-__strong but the
  10321. // user actually wrote 'const'.
  10322. if (var->isARCPseudoStrong() &&
  10323. (!var->getTypeSourceInfo() ||
  10324. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  10325. // There are three pseudo-strong cases:
  10326. // - self
  10327. ObjCMethodDecl *method = S.getCurMethodDecl();
  10328. if (method && var == method->getSelfDecl()) {
  10329. DiagID = method->isClassMethod()
  10330. ? diag::err_typecheck_arc_assign_self_class_method
  10331. : diag::err_typecheck_arc_assign_self;
  10332. // - Objective-C externally_retained attribute.
  10333. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  10334. isa<ParmVarDecl>(var)) {
  10335. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  10336. // - fast enumeration variables
  10337. } else {
  10338. DiagID = diag::err_typecheck_arr_assign_enumeration;
  10339. }
  10340. SourceRange Assign;
  10341. if (Loc != OrigLoc)
  10342. Assign = SourceRange(OrigLoc, OrigLoc);
  10343. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10344. // We need to preserve the AST regardless, so migration tool
  10345. // can do its job.
  10346. return false;
  10347. }
  10348. }
  10349. }
  10350. // If none of the special cases above are triggered, then this is a
  10351. // simple const assignment.
  10352. if (DiagID == 0) {
  10353. DiagnoseConstAssignment(S, E, Loc);
  10354. return true;
  10355. }
  10356. break;
  10357. case Expr::MLV_ConstAddrSpace:
  10358. DiagnoseConstAssignment(S, E, Loc);
  10359. return true;
  10360. case Expr::MLV_ConstQualifiedField:
  10361. DiagnoseRecursiveConstFields(S, E, Loc);
  10362. return true;
  10363. case Expr::MLV_ArrayType:
  10364. case Expr::MLV_ArrayTemporary:
  10365. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10366. NeedType = true;
  10367. break;
  10368. case Expr::MLV_NotObjectType:
  10369. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10370. NeedType = true;
  10371. break;
  10372. case Expr::MLV_LValueCast:
  10373. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10374. break;
  10375. case Expr::MLV_Valid:
  10376. llvm_unreachable("did not take early return for MLV_Valid");
  10377. case Expr::MLV_InvalidExpression:
  10378. case Expr::MLV_MemberFunction:
  10379. case Expr::MLV_ClassTemporary:
  10380. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10381. break;
  10382. case Expr::MLV_IncompleteType:
  10383. case Expr::MLV_IncompleteVoidType:
  10384. return S.RequireCompleteType(Loc, E->getType(),
  10385. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10386. case Expr::MLV_DuplicateVectorComponents:
  10387. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10388. break;
  10389. case Expr::MLV_NoSetterProperty:
  10390. llvm_unreachable("readonly properties should be processed differently");
  10391. case Expr::MLV_InvalidMessageExpression:
  10392. DiagID = diag::err_readonly_message_assignment;
  10393. break;
  10394. case Expr::MLV_SubObjCPropertySetting:
  10395. DiagID = diag::err_no_subobject_property_setting;
  10396. break;
  10397. }
  10398. SourceRange Assign;
  10399. if (Loc != OrigLoc)
  10400. Assign = SourceRange(OrigLoc, OrigLoc);
  10401. if (NeedType)
  10402. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10403. else
  10404. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10405. return true;
  10406. }
  10407. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10408. SourceLocation Loc,
  10409. Sema &Sema) {
  10410. if (Sema.inTemplateInstantiation())
  10411. return;
  10412. if (Sema.isUnevaluatedContext())
  10413. return;
  10414. if (Loc.isInvalid() || Loc.isMacroID())
  10415. return;
  10416. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10417. return;
  10418. // C / C++ fields
  10419. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10420. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10421. if (ML && MR) {
  10422. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10423. return;
  10424. const ValueDecl *LHSDecl =
  10425. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10426. const ValueDecl *RHSDecl =
  10427. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10428. if (LHSDecl != RHSDecl)
  10429. return;
  10430. if (LHSDecl->getType().isVolatileQualified())
  10431. return;
  10432. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10433. if (RefTy->getPointeeType().isVolatileQualified())
  10434. return;
  10435. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10436. }
  10437. // Objective-C instance variables
  10438. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10439. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10440. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10441. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10442. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10443. if (RL && RR && RL->getDecl() == RR->getDecl())
  10444. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10445. }
  10446. }
  10447. // C99 6.5.16.1
  10448. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10449. SourceLocation Loc,
  10450. QualType CompoundType) {
  10451. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10452. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10453. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10454. return QualType();
  10455. QualType LHSType = LHSExpr->getType();
  10456. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10457. CompoundType;
  10458. // OpenCL v1.2 s6.1.1.1 p2:
  10459. // The half data type can only be used to declare a pointer to a buffer that
  10460. // contains half values
  10461. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10462. LHSType->isHalfType()) {
  10463. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10464. << LHSType.getUnqualifiedType();
  10465. return QualType();
  10466. }
  10467. AssignConvertType ConvTy;
  10468. if (CompoundType.isNull()) {
  10469. Expr *RHSCheck = RHS.get();
  10470. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10471. QualType LHSTy(LHSType);
  10472. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10473. if (RHS.isInvalid())
  10474. return QualType();
  10475. // Special case of NSObject attributes on c-style pointer types.
  10476. if (ConvTy == IncompatiblePointer &&
  10477. ((Context.isObjCNSObjectType(LHSType) &&
  10478. RHSType->isObjCObjectPointerType()) ||
  10479. (Context.isObjCNSObjectType(RHSType) &&
  10480. LHSType->isObjCObjectPointerType())))
  10481. ConvTy = Compatible;
  10482. if (ConvTy == Compatible &&
  10483. LHSType->isObjCObjectType())
  10484. Diag(Loc, diag::err_objc_object_assignment)
  10485. << LHSType;
  10486. // If the RHS is a unary plus or minus, check to see if they = and + are
  10487. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10488. // instead of "x += 4".
  10489. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10490. RHSCheck = ICE->getSubExpr();
  10491. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10492. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10493. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10494. // Only if the two operators are exactly adjacent.
  10495. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10496. // And there is a space or other character before the subexpr of the
  10497. // unary +/-. We don't want to warn on "x=-1".
  10498. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10499. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10500. Diag(Loc, diag::warn_not_compound_assign)
  10501. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10502. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10503. }
  10504. }
  10505. if (ConvTy == Compatible) {
  10506. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10507. // Warn about retain cycles where a block captures the LHS, but
  10508. // not if the LHS is a simple variable into which the block is
  10509. // being stored...unless that variable can be captured by reference!
  10510. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10511. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10512. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10513. checkRetainCycles(LHSExpr, RHS.get());
  10514. }
  10515. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10516. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10517. // It is safe to assign a weak reference into a strong variable.
  10518. // Although this code can still have problems:
  10519. // id x = self.weakProp;
  10520. // id y = self.weakProp;
  10521. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10522. // paths through the function. This should be revisited if
  10523. // -Wrepeated-use-of-weak is made flow-sensitive.
  10524. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10525. // variable, which will be valid for the current autorelease scope.
  10526. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10527. RHS.get()->getBeginLoc()))
  10528. getCurFunction()->markSafeWeakUse(RHS.get());
  10529. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10530. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10531. }
  10532. }
  10533. } else {
  10534. // Compound assignment "x += y"
  10535. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10536. }
  10537. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10538. RHS.get(), AA_Assigning))
  10539. return QualType();
  10540. CheckForNullPointerDereference(*this, LHSExpr);
  10541. if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
  10542. if (CompoundType.isNull()) {
  10543. // C++2a [expr.ass]p5:
  10544. // A simple-assignment whose left operand is of a volatile-qualified
  10545. // type is deprecated unless the assignment is either a discarded-value
  10546. // expression or an unevaluated operand
  10547. ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
  10548. } else {
  10549. // C++2a [expr.ass]p6:
  10550. // [Compound-assignment] expressions are deprecated if E1 has
  10551. // volatile-qualified type
  10552. Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
  10553. }
  10554. }
  10555. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10556. // left operand unless the left operand has qualified type, in which case
  10557. // it is the unqualified version of the type of the left operand.
  10558. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10559. // is converted to the type of the assignment expression (above).
  10560. // C++ 5.17p1: the type of the assignment expression is that of its left
  10561. // operand.
  10562. return (getLangOpts().CPlusPlus
  10563. ? LHSType : LHSType.getUnqualifiedType());
  10564. }
  10565. // Only ignore explicit casts to void.
  10566. static bool IgnoreCommaOperand(const Expr *E) {
  10567. E = E->IgnoreParens();
  10568. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10569. if (CE->getCastKind() == CK_ToVoid) {
  10570. return true;
  10571. }
  10572. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10573. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10574. CE->getSubExpr()->getType()->isDependentType()) {
  10575. return true;
  10576. }
  10577. }
  10578. return false;
  10579. }
  10580. // Look for instances where it is likely the comma operator is confused with
  10581. // another operator. There is a whitelist of acceptable expressions for the
  10582. // left hand side of the comma operator, otherwise emit a warning.
  10583. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10584. // No warnings in macros
  10585. if (Loc.isMacroID())
  10586. return;
  10587. // Don't warn in template instantiations.
  10588. if (inTemplateInstantiation())
  10589. return;
  10590. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10591. // instead, skip more than needed, then call back into here with the
  10592. // CommaVisitor in SemaStmt.cpp.
  10593. // The whitelisted locations are the initialization and increment portions
  10594. // of a for loop. The additional checks are on the condition of
  10595. // if statements, do/while loops, and for loops.
  10596. // Differences in scope flags for C89 mode requires the extra logic.
  10597. const unsigned ForIncrementFlags =
  10598. getLangOpts().C99 || getLangOpts().CPlusPlus
  10599. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10600. : Scope::ContinueScope | Scope::BreakScope;
  10601. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10602. const unsigned ScopeFlags = getCurScope()->getFlags();
  10603. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10604. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10605. return;
  10606. // If there are multiple comma operators used together, get the RHS of the
  10607. // of the comma operator as the LHS.
  10608. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10609. if (BO->getOpcode() != BO_Comma)
  10610. break;
  10611. LHS = BO->getRHS();
  10612. }
  10613. // Only allow some expressions on LHS to not warn.
  10614. if (IgnoreCommaOperand(LHS))
  10615. return;
  10616. Diag(Loc, diag::warn_comma_operator);
  10617. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10618. << LHS->getSourceRange()
  10619. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10620. LangOpts.CPlusPlus ? "static_cast<void>("
  10621. : "(void)(")
  10622. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10623. ")");
  10624. }
  10625. // C99 6.5.17
  10626. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10627. SourceLocation Loc) {
  10628. LHS = S.CheckPlaceholderExpr(LHS.get());
  10629. RHS = S.CheckPlaceholderExpr(RHS.get());
  10630. if (LHS.isInvalid() || RHS.isInvalid())
  10631. return QualType();
  10632. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10633. // operands, but not unary promotions.
  10634. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10635. // So we treat the LHS as a ignored value, and in C++ we allow the
  10636. // containing site to determine what should be done with the RHS.
  10637. LHS = S.IgnoredValueConversions(LHS.get());
  10638. if (LHS.isInvalid())
  10639. return QualType();
  10640. S.DiagnoseUnusedExprResult(LHS.get());
  10641. if (!S.getLangOpts().CPlusPlus) {
  10642. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10643. if (RHS.isInvalid())
  10644. return QualType();
  10645. if (!RHS.get()->getType()->isVoidType())
  10646. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10647. diag::err_incomplete_type);
  10648. }
  10649. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10650. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10651. return RHS.get()->getType();
  10652. }
  10653. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10654. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10655. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10656. ExprValueKind &VK,
  10657. ExprObjectKind &OK,
  10658. SourceLocation OpLoc,
  10659. bool IsInc, bool IsPrefix) {
  10660. if (Op->isTypeDependent())
  10661. return S.Context.DependentTy;
  10662. QualType ResType = Op->getType();
  10663. // Atomic types can be used for increment / decrement where the non-atomic
  10664. // versions can, so ignore the _Atomic() specifier for the purpose of
  10665. // checking.
  10666. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10667. ResType = ResAtomicType->getValueType();
  10668. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10669. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10670. // Decrement of bool is not allowed.
  10671. if (!IsInc) {
  10672. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10673. return QualType();
  10674. }
  10675. // Increment of bool sets it to true, but is deprecated.
  10676. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10677. : diag::warn_increment_bool)
  10678. << Op->getSourceRange();
  10679. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10680. // Error on enum increments and decrements in C++ mode
  10681. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10682. return QualType();
  10683. } else if (ResType->isRealType()) {
  10684. // OK!
  10685. } else if (ResType->isPointerType()) {
  10686. // C99 6.5.2.4p2, 6.5.6p2
  10687. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10688. return QualType();
  10689. } else if (ResType->isObjCObjectPointerType()) {
  10690. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10691. // Otherwise, we just need a complete type.
  10692. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10693. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10694. return QualType();
  10695. } else if (ResType->isAnyComplexType()) {
  10696. // C99 does not support ++/-- on complex types, we allow as an extension.
  10697. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10698. << ResType << Op->getSourceRange();
  10699. } else if (ResType->isPlaceholderType()) {
  10700. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10701. if (PR.isInvalid()) return QualType();
  10702. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10703. IsInc, IsPrefix);
  10704. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10705. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10706. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10707. (ResType->castAs<VectorType>()->getVectorKind() !=
  10708. VectorType::AltiVecBool)) {
  10709. // The z vector extensions allow ++ and -- for non-bool vectors.
  10710. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10711. ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
  10712. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10713. } else {
  10714. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10715. << ResType << int(IsInc) << Op->getSourceRange();
  10716. return QualType();
  10717. }
  10718. // At this point, we know we have a real, complex or pointer type.
  10719. // Now make sure the operand is a modifiable lvalue.
  10720. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10721. return QualType();
  10722. if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
  10723. // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
  10724. // An operand with volatile-qualified type is deprecated
  10725. S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
  10726. << IsInc << ResType;
  10727. }
  10728. // In C++, a prefix increment is the same type as the operand. Otherwise
  10729. // (in C or with postfix), the increment is the unqualified type of the
  10730. // operand.
  10731. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10732. VK = VK_LValue;
  10733. OK = Op->getObjectKind();
  10734. return ResType;
  10735. } else {
  10736. VK = VK_RValue;
  10737. return ResType.getUnqualifiedType();
  10738. }
  10739. }
  10740. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10741. /// This routine allows us to typecheck complex/recursive expressions
  10742. /// where the declaration is needed for type checking. We only need to
  10743. /// handle cases when the expression references a function designator
  10744. /// or is an lvalue. Here are some examples:
  10745. /// - &(x) => x
  10746. /// - &*****f => f for f a function designator.
  10747. /// - &s.xx => s
  10748. /// - &s.zz[1].yy -> s, if zz is an array
  10749. /// - *(x + 1) -> x, if x is an array
  10750. /// - &"123"[2] -> 0
  10751. /// - & __real__ x -> x
  10752. static ValueDecl *getPrimaryDecl(Expr *E) {
  10753. switch (E->getStmtClass()) {
  10754. case Stmt::DeclRefExprClass:
  10755. return cast<DeclRefExpr>(E)->getDecl();
  10756. case Stmt::MemberExprClass:
  10757. // If this is an arrow operator, the address is an offset from
  10758. // the base's value, so the object the base refers to is
  10759. // irrelevant.
  10760. if (cast<MemberExpr>(E)->isArrow())
  10761. return nullptr;
  10762. // Otherwise, the expression refers to a part of the base
  10763. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10764. case Stmt::ArraySubscriptExprClass: {
  10765. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10766. // promotion of register arrays earlier.
  10767. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10768. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10769. if (ICE->getSubExpr()->getType()->isArrayType())
  10770. return getPrimaryDecl(ICE->getSubExpr());
  10771. }
  10772. return nullptr;
  10773. }
  10774. case Stmt::UnaryOperatorClass: {
  10775. UnaryOperator *UO = cast<UnaryOperator>(E);
  10776. switch(UO->getOpcode()) {
  10777. case UO_Real:
  10778. case UO_Imag:
  10779. case UO_Extension:
  10780. return getPrimaryDecl(UO->getSubExpr());
  10781. default:
  10782. return nullptr;
  10783. }
  10784. }
  10785. case Stmt::ParenExprClass:
  10786. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10787. case Stmt::ImplicitCastExprClass:
  10788. // If the result of an implicit cast is an l-value, we care about
  10789. // the sub-expression; otherwise, the result here doesn't matter.
  10790. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10791. default:
  10792. return nullptr;
  10793. }
  10794. }
  10795. namespace {
  10796. enum {
  10797. AO_Bit_Field = 0,
  10798. AO_Vector_Element = 1,
  10799. AO_Property_Expansion = 2,
  10800. AO_Register_Variable = 3,
  10801. AO_No_Error = 4
  10802. };
  10803. }
  10804. /// Diagnose invalid operand for address of operations.
  10805. ///
  10806. /// \param Type The type of operand which cannot have its address taken.
  10807. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10808. Expr *E, unsigned Type) {
  10809. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10810. }
  10811. /// CheckAddressOfOperand - The operand of & must be either a function
  10812. /// designator or an lvalue designating an object. If it is an lvalue, the
  10813. /// object cannot be declared with storage class register or be a bit field.
  10814. /// Note: The usual conversions are *not* applied to the operand of the &
  10815. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10816. /// In C++, the operand might be an overloaded function name, in which case
  10817. /// we allow the '&' but retain the overloaded-function type.
  10818. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10819. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10820. if (PTy->getKind() == BuiltinType::Overload) {
  10821. Expr *E = OrigOp.get()->IgnoreParens();
  10822. if (!isa<OverloadExpr>(E)) {
  10823. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10824. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10825. << OrigOp.get()->getSourceRange();
  10826. return QualType();
  10827. }
  10828. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10829. if (isa<UnresolvedMemberExpr>(Ovl))
  10830. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10831. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10832. << OrigOp.get()->getSourceRange();
  10833. return QualType();
  10834. }
  10835. return Context.OverloadTy;
  10836. }
  10837. if (PTy->getKind() == BuiltinType::UnknownAny)
  10838. return Context.UnknownAnyTy;
  10839. if (PTy->getKind() == BuiltinType::BoundMember) {
  10840. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10841. << OrigOp.get()->getSourceRange();
  10842. return QualType();
  10843. }
  10844. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10845. if (OrigOp.isInvalid()) return QualType();
  10846. }
  10847. if (OrigOp.get()->isTypeDependent())
  10848. return Context.DependentTy;
  10849. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10850. // Make sure to ignore parentheses in subsequent checks
  10851. Expr *op = OrigOp.get()->IgnoreParens();
  10852. // In OpenCL captures for blocks called as lambda functions
  10853. // are located in the private address space. Blocks used in
  10854. // enqueue_kernel can be located in a different address space
  10855. // depending on a vendor implementation. Thus preventing
  10856. // taking an address of the capture to avoid invalid AS casts.
  10857. if (LangOpts.OpenCL) {
  10858. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10859. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10860. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10861. return QualType();
  10862. }
  10863. }
  10864. if (getLangOpts().C99) {
  10865. // Implement C99-only parts of addressof rules.
  10866. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10867. if (uOp->getOpcode() == UO_Deref)
  10868. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10869. // (assuming the deref expression is valid).
  10870. return uOp->getSubExpr()->getType();
  10871. }
  10872. // Technically, there should be a check for array subscript
  10873. // expressions here, but the result of one is always an lvalue anyway.
  10874. }
  10875. ValueDecl *dcl = getPrimaryDecl(op);
  10876. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10877. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10878. op->getBeginLoc()))
  10879. return QualType();
  10880. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10881. unsigned AddressOfError = AO_No_Error;
  10882. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10883. bool sfinae = (bool)isSFINAEContext();
  10884. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10885. : diag::ext_typecheck_addrof_temporary)
  10886. << op->getType() << op->getSourceRange();
  10887. if (sfinae)
  10888. return QualType();
  10889. // Materialize the temporary as an lvalue so that we can take its address.
  10890. OrigOp = op =
  10891. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10892. } else if (isa<ObjCSelectorExpr>(op)) {
  10893. return Context.getPointerType(op->getType());
  10894. } else if (lval == Expr::LV_MemberFunction) {
  10895. // If it's an instance method, make a member pointer.
  10896. // The expression must have exactly the form &A::foo.
  10897. // If the underlying expression isn't a decl ref, give up.
  10898. if (!isa<DeclRefExpr>(op)) {
  10899. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10900. << OrigOp.get()->getSourceRange();
  10901. return QualType();
  10902. }
  10903. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10904. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10905. // The id-expression was parenthesized.
  10906. if (OrigOp.get() != DRE) {
  10907. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10908. << OrigOp.get()->getSourceRange();
  10909. // The method was named without a qualifier.
  10910. } else if (!DRE->getQualifier()) {
  10911. if (MD->getParent()->getName().empty())
  10912. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10913. << op->getSourceRange();
  10914. else {
  10915. SmallString<32> Str;
  10916. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10917. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10918. << op->getSourceRange()
  10919. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10920. }
  10921. }
  10922. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10923. if (isa<CXXDestructorDecl>(MD))
  10924. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10925. QualType MPTy = Context.getMemberPointerType(
  10926. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10927. // Under the MS ABI, lock down the inheritance model now.
  10928. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10929. (void)isCompleteType(OpLoc, MPTy);
  10930. return MPTy;
  10931. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10932. // C99 6.5.3.2p1
  10933. // The operand must be either an l-value or a function designator
  10934. if (!op->getType()->isFunctionType()) {
  10935. // Use a special diagnostic for loads from property references.
  10936. if (isa<PseudoObjectExpr>(op)) {
  10937. AddressOfError = AO_Property_Expansion;
  10938. } else {
  10939. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10940. << op->getType() << op->getSourceRange();
  10941. return QualType();
  10942. }
  10943. }
  10944. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10945. // The operand cannot be a bit-field
  10946. AddressOfError = AO_Bit_Field;
  10947. } else if (op->getObjectKind() == OK_VectorComponent) {
  10948. // The operand cannot be an element of a vector
  10949. AddressOfError = AO_Vector_Element;
  10950. } else if (dcl) { // C99 6.5.3.2p1
  10951. // We have an lvalue with a decl. Make sure the decl is not declared
  10952. // with the register storage-class specifier.
  10953. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10954. // in C++ it is not error to take address of a register
  10955. // variable (c++03 7.1.1P3)
  10956. if (vd->getStorageClass() == SC_Register &&
  10957. !getLangOpts().CPlusPlus) {
  10958. AddressOfError = AO_Register_Variable;
  10959. }
  10960. } else if (isa<MSPropertyDecl>(dcl)) {
  10961. AddressOfError = AO_Property_Expansion;
  10962. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10963. return Context.OverloadTy;
  10964. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10965. // Okay: we can take the address of a field.
  10966. // Could be a pointer to member, though, if there is an explicit
  10967. // scope qualifier for the class.
  10968. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10969. DeclContext *Ctx = dcl->getDeclContext();
  10970. if (Ctx && Ctx->isRecord()) {
  10971. if (dcl->getType()->isReferenceType()) {
  10972. Diag(OpLoc,
  10973. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10974. << dcl->getDeclName() << dcl->getType();
  10975. return QualType();
  10976. }
  10977. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10978. Ctx = Ctx->getParent();
  10979. QualType MPTy = Context.getMemberPointerType(
  10980. op->getType(),
  10981. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10982. // Under the MS ABI, lock down the inheritance model now.
  10983. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10984. (void)isCompleteType(OpLoc, MPTy);
  10985. return MPTy;
  10986. }
  10987. }
  10988. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10989. !isa<BindingDecl>(dcl))
  10990. llvm_unreachable("Unknown/unexpected decl type");
  10991. }
  10992. if (AddressOfError != AO_No_Error) {
  10993. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10994. return QualType();
  10995. }
  10996. if (lval == Expr::LV_IncompleteVoidType) {
  10997. // Taking the address of a void variable is technically illegal, but we
  10998. // allow it in cases which are otherwise valid.
  10999. // Example: "extern void x; void* y = &x;".
  11000. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  11001. }
  11002. // If the operand has type "type", the result has type "pointer to type".
  11003. if (op->getType()->isObjCObjectType())
  11004. return Context.getObjCObjectPointerType(op->getType());
  11005. CheckAddressOfPackedMember(op);
  11006. return Context.getPointerType(op->getType());
  11007. }
  11008. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  11009. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  11010. if (!DRE)
  11011. return;
  11012. const Decl *D = DRE->getDecl();
  11013. if (!D)
  11014. return;
  11015. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  11016. if (!Param)
  11017. return;
  11018. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  11019. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  11020. return;
  11021. if (FunctionScopeInfo *FD = S.getCurFunction())
  11022. if (!FD->ModifiedNonNullParams.count(Param))
  11023. FD->ModifiedNonNullParams.insert(Param);
  11024. }
  11025. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  11026. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  11027. SourceLocation OpLoc) {
  11028. if (Op->isTypeDependent())
  11029. return S.Context.DependentTy;
  11030. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  11031. if (ConvResult.isInvalid())
  11032. return QualType();
  11033. Op = ConvResult.get();
  11034. QualType OpTy = Op->getType();
  11035. QualType Result;
  11036. if (isa<CXXReinterpretCastExpr>(Op)) {
  11037. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  11038. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  11039. Op->getSourceRange());
  11040. }
  11041. if (const PointerType *PT = OpTy->getAs<PointerType>())
  11042. {
  11043. Result = PT->getPointeeType();
  11044. }
  11045. else if (const ObjCObjectPointerType *OPT =
  11046. OpTy->getAs<ObjCObjectPointerType>())
  11047. Result = OPT->getPointeeType();
  11048. else {
  11049. ExprResult PR = S.CheckPlaceholderExpr(Op);
  11050. if (PR.isInvalid()) return QualType();
  11051. if (PR.get() != Op)
  11052. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  11053. }
  11054. if (Result.isNull()) {
  11055. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  11056. << OpTy << Op->getSourceRange();
  11057. return QualType();
  11058. }
  11059. // Note that per both C89 and C99, indirection is always legal, even if Result
  11060. // is an incomplete type or void. It would be possible to warn about
  11061. // dereferencing a void pointer, but it's completely well-defined, and such a
  11062. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  11063. // for pointers to 'void' but is fine for any other pointer type:
  11064. //
  11065. // C++ [expr.unary.op]p1:
  11066. // [...] the expression to which [the unary * operator] is applied shall
  11067. // be a pointer to an object type, or a pointer to a function type
  11068. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  11069. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  11070. << OpTy << Op->getSourceRange();
  11071. // Dereferences are usually l-values...
  11072. VK = VK_LValue;
  11073. // ...except that certain expressions are never l-values in C.
  11074. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  11075. VK = VK_RValue;
  11076. return Result;
  11077. }
  11078. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  11079. BinaryOperatorKind Opc;
  11080. switch (Kind) {
  11081. default: llvm_unreachable("Unknown binop!");
  11082. case tok::periodstar: Opc = BO_PtrMemD; break;
  11083. case tok::arrowstar: Opc = BO_PtrMemI; break;
  11084. case tok::star: Opc = BO_Mul; break;
  11085. case tok::slash: Opc = BO_Div; break;
  11086. case tok::percent: Opc = BO_Rem; break;
  11087. case tok::plus: Opc = BO_Add; break;
  11088. case tok::minus: Opc = BO_Sub; break;
  11089. case tok::lessless: Opc = BO_Shl; break;
  11090. case tok::greatergreater: Opc = BO_Shr; break;
  11091. case tok::lessequal: Opc = BO_LE; break;
  11092. case tok::less: Opc = BO_LT; break;
  11093. case tok::greaterequal: Opc = BO_GE; break;
  11094. case tok::greater: Opc = BO_GT; break;
  11095. case tok::exclaimequal: Opc = BO_NE; break;
  11096. case tok::equalequal: Opc = BO_EQ; break;
  11097. case tok::spaceship: Opc = BO_Cmp; break;
  11098. case tok::amp: Opc = BO_And; break;
  11099. case tok::caret: Opc = BO_Xor; break;
  11100. case tok::pipe: Opc = BO_Or; break;
  11101. case tok::ampamp: Opc = BO_LAnd; break;
  11102. case tok::pipepipe: Opc = BO_LOr; break;
  11103. case tok::equal: Opc = BO_Assign; break;
  11104. case tok::starequal: Opc = BO_MulAssign; break;
  11105. case tok::slashequal: Opc = BO_DivAssign; break;
  11106. case tok::percentequal: Opc = BO_RemAssign; break;
  11107. case tok::plusequal: Opc = BO_AddAssign; break;
  11108. case tok::minusequal: Opc = BO_SubAssign; break;
  11109. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  11110. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  11111. case tok::ampequal: Opc = BO_AndAssign; break;
  11112. case tok::caretequal: Opc = BO_XorAssign; break;
  11113. case tok::pipeequal: Opc = BO_OrAssign; break;
  11114. case tok::comma: Opc = BO_Comma; break;
  11115. }
  11116. return Opc;
  11117. }
  11118. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  11119. tok::TokenKind Kind) {
  11120. UnaryOperatorKind Opc;
  11121. switch (Kind) {
  11122. default: llvm_unreachable("Unknown unary op!");
  11123. case tok::plusplus: Opc = UO_PreInc; break;
  11124. case tok::minusminus: Opc = UO_PreDec; break;
  11125. case tok::amp: Opc = UO_AddrOf; break;
  11126. case tok::star: Opc = UO_Deref; break;
  11127. case tok::plus: Opc = UO_Plus; break;
  11128. case tok::minus: Opc = UO_Minus; break;
  11129. case tok::tilde: Opc = UO_Not; break;
  11130. case tok::exclaim: Opc = UO_LNot; break;
  11131. case tok::kw___real: Opc = UO_Real; break;
  11132. case tok::kw___imag: Opc = UO_Imag; break;
  11133. case tok::kw___extension__: Opc = UO_Extension; break;
  11134. }
  11135. return Opc;
  11136. }
  11137. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  11138. /// This warning suppressed in the event of macro expansions.
  11139. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  11140. SourceLocation OpLoc, bool IsBuiltin) {
  11141. if (S.inTemplateInstantiation())
  11142. return;
  11143. if (S.isUnevaluatedContext())
  11144. return;
  11145. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  11146. return;
  11147. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11148. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11149. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11150. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11151. if (!LHSDeclRef || !RHSDeclRef ||
  11152. LHSDeclRef->getLocation().isMacroID() ||
  11153. RHSDeclRef->getLocation().isMacroID())
  11154. return;
  11155. const ValueDecl *LHSDecl =
  11156. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  11157. const ValueDecl *RHSDecl =
  11158. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  11159. if (LHSDecl != RHSDecl)
  11160. return;
  11161. if (LHSDecl->getType().isVolatileQualified())
  11162. return;
  11163. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  11164. if (RefTy->getPointeeType().isVolatileQualified())
  11165. return;
  11166. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  11167. : diag::warn_self_assignment_overloaded)
  11168. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  11169. << RHSExpr->getSourceRange();
  11170. }
  11171. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  11172. /// is usually indicative of introspection within the Objective-C pointer.
  11173. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  11174. SourceLocation OpLoc) {
  11175. if (!S.getLangOpts().ObjC)
  11176. return;
  11177. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  11178. const Expr *LHS = L.get();
  11179. const Expr *RHS = R.get();
  11180. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11181. ObjCPointerExpr = LHS;
  11182. OtherExpr = RHS;
  11183. }
  11184. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11185. ObjCPointerExpr = RHS;
  11186. OtherExpr = LHS;
  11187. }
  11188. // This warning is deliberately made very specific to reduce false
  11189. // positives with logic that uses '&' for hashing. This logic mainly
  11190. // looks for code trying to introspect into tagged pointers, which
  11191. // code should generally never do.
  11192. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  11193. unsigned Diag = diag::warn_objc_pointer_masking;
  11194. // Determine if we are introspecting the result of performSelectorXXX.
  11195. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  11196. // Special case messages to -performSelector and friends, which
  11197. // can return non-pointer values boxed in a pointer value.
  11198. // Some clients may wish to silence warnings in this subcase.
  11199. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  11200. Selector S = ME->getSelector();
  11201. StringRef SelArg0 = S.getNameForSlot(0);
  11202. if (SelArg0.startswith("performSelector"))
  11203. Diag = diag::warn_objc_pointer_masking_performSelector;
  11204. }
  11205. S.Diag(OpLoc, Diag)
  11206. << ObjCPointerExpr->getSourceRange();
  11207. }
  11208. }
  11209. static NamedDecl *getDeclFromExpr(Expr *E) {
  11210. if (!E)
  11211. return nullptr;
  11212. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  11213. return DRE->getDecl();
  11214. if (auto *ME = dyn_cast<MemberExpr>(E))
  11215. return ME->getMemberDecl();
  11216. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  11217. return IRE->getDecl();
  11218. return nullptr;
  11219. }
  11220. // This helper function promotes a binary operator's operands (which are of a
  11221. // half vector type) to a vector of floats and then truncates the result to
  11222. // a vector of either half or short.
  11223. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  11224. BinaryOperatorKind Opc, QualType ResultTy,
  11225. ExprValueKind VK, ExprObjectKind OK,
  11226. bool IsCompAssign, SourceLocation OpLoc,
  11227. FPOptions FPFeatures) {
  11228. auto &Context = S.getASTContext();
  11229. assert((isVector(ResultTy, Context.HalfTy) ||
  11230. isVector(ResultTy, Context.ShortTy)) &&
  11231. "Result must be a vector of half or short");
  11232. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  11233. isVector(RHS.get()->getType(), Context.HalfTy) &&
  11234. "both operands expected to be a half vector");
  11235. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  11236. QualType BinOpResTy = RHS.get()->getType();
  11237. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  11238. // change BinOpResTy to a vector of ints.
  11239. if (isVector(ResultTy, Context.ShortTy))
  11240. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  11241. if (IsCompAssign)
  11242. return new (Context) CompoundAssignOperator(
  11243. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  11244. OpLoc, FPFeatures);
  11245. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  11246. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  11247. VK, OK, OpLoc, FPFeatures);
  11248. return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
  11249. }
  11250. static std::pair<ExprResult, ExprResult>
  11251. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  11252. Expr *RHSExpr) {
  11253. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11254. if (!S.getLangOpts().CPlusPlus) {
  11255. // C cannot handle TypoExpr nodes on either side of a binop because it
  11256. // doesn't handle dependent types properly, so make sure any TypoExprs have
  11257. // been dealt with before checking the operands.
  11258. LHS = S.CorrectDelayedTyposInExpr(LHS);
  11259. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  11260. if (Opc != BO_Assign)
  11261. return ExprResult(E);
  11262. // Avoid correcting the RHS to the same Expr as the LHS.
  11263. Decl *D = getDeclFromExpr(E);
  11264. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  11265. });
  11266. }
  11267. return std::make_pair(LHS, RHS);
  11268. }
  11269. /// Returns true if conversion between vectors of halfs and vectors of floats
  11270. /// is needed.
  11271. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  11272. QualType SrcType) {
  11273. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  11274. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  11275. isVector(SrcType, Ctx.HalfTy);
  11276. }
  11277. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  11278. /// operator @p Opc at location @c TokLoc. This routine only supports
  11279. /// built-in operations; ActOnBinOp handles overloaded operators.
  11280. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  11281. BinaryOperatorKind Opc,
  11282. Expr *LHSExpr, Expr *RHSExpr) {
  11283. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  11284. // The syntax only allows initializer lists on the RHS of assignment,
  11285. // so we don't need to worry about accepting invalid code for
  11286. // non-assignment operators.
  11287. // C++11 5.17p9:
  11288. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  11289. // of x = {} is x = T().
  11290. InitializationKind Kind = InitializationKind::CreateDirectList(
  11291. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11292. InitializedEntity Entity =
  11293. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  11294. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  11295. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  11296. if (Init.isInvalid())
  11297. return Init;
  11298. RHSExpr = Init.get();
  11299. }
  11300. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11301. QualType ResultTy; // Result type of the binary operator.
  11302. // The following two variables are used for compound assignment operators
  11303. QualType CompLHSTy; // Type of LHS after promotions for computation
  11304. QualType CompResultTy; // Type of computation result
  11305. ExprValueKind VK = VK_RValue;
  11306. ExprObjectKind OK = OK_Ordinary;
  11307. bool ConvertHalfVec = false;
  11308. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11309. if (!LHS.isUsable() || !RHS.isUsable())
  11310. return ExprError();
  11311. if (getLangOpts().OpenCL) {
  11312. QualType LHSTy = LHSExpr->getType();
  11313. QualType RHSTy = RHSExpr->getType();
  11314. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  11315. // the ATOMIC_VAR_INIT macro.
  11316. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  11317. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11318. if (BO_Assign == Opc)
  11319. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  11320. else
  11321. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11322. return ExprError();
  11323. }
  11324. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11325. // only with a builtin functions and therefore should be disallowed here.
  11326. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  11327. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  11328. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  11329. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  11330. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11331. return ExprError();
  11332. }
  11333. }
  11334. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11335. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11336. if (Opc != BO_Assign && Opc != BO_Comma) {
  11337. checkOpenMPDeviceExpr(LHSExpr);
  11338. checkOpenMPDeviceExpr(RHSExpr);
  11339. }
  11340. }
  11341. switch (Opc) {
  11342. case BO_Assign:
  11343. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  11344. if (getLangOpts().CPlusPlus &&
  11345. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  11346. VK = LHS.get()->getValueKind();
  11347. OK = LHS.get()->getObjectKind();
  11348. }
  11349. if (!ResultTy.isNull()) {
  11350. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11351. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  11352. // Avoid copying a block to the heap if the block is assigned to a local
  11353. // auto variable that is declared in the same scope as the block. This
  11354. // optimization is unsafe if the local variable is declared in an outer
  11355. // scope. For example:
  11356. //
  11357. // BlockTy b;
  11358. // {
  11359. // b = ^{...};
  11360. // }
  11361. // // It is unsafe to invoke the block here if it wasn't copied to the
  11362. // // heap.
  11363. // b();
  11364. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  11365. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  11366. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11367. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11368. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11369. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11370. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  11371. NTCUC_Assignment, NTCUK_Copy);
  11372. }
  11373. RecordModifiableNonNullParam(*this, LHS.get());
  11374. break;
  11375. case BO_PtrMemD:
  11376. case BO_PtrMemI:
  11377. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11378. Opc == BO_PtrMemI);
  11379. break;
  11380. case BO_Mul:
  11381. case BO_Div:
  11382. ConvertHalfVec = true;
  11383. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11384. Opc == BO_Div);
  11385. break;
  11386. case BO_Rem:
  11387. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11388. break;
  11389. case BO_Add:
  11390. ConvertHalfVec = true;
  11391. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11392. break;
  11393. case BO_Sub:
  11394. ConvertHalfVec = true;
  11395. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11396. break;
  11397. case BO_Shl:
  11398. case BO_Shr:
  11399. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11400. break;
  11401. case BO_LE:
  11402. case BO_LT:
  11403. case BO_GE:
  11404. case BO_GT:
  11405. ConvertHalfVec = true;
  11406. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11407. break;
  11408. case BO_EQ:
  11409. case BO_NE:
  11410. ConvertHalfVec = true;
  11411. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11412. break;
  11413. case BO_Cmp:
  11414. ConvertHalfVec = true;
  11415. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11416. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11417. break;
  11418. case BO_And:
  11419. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11420. LLVM_FALLTHROUGH;
  11421. case BO_Xor:
  11422. case BO_Or:
  11423. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11424. break;
  11425. case BO_LAnd:
  11426. case BO_LOr:
  11427. ConvertHalfVec = true;
  11428. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11429. break;
  11430. case BO_MulAssign:
  11431. case BO_DivAssign:
  11432. ConvertHalfVec = true;
  11433. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11434. Opc == BO_DivAssign);
  11435. CompLHSTy = CompResultTy;
  11436. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11437. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11438. break;
  11439. case BO_RemAssign:
  11440. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11441. CompLHSTy = CompResultTy;
  11442. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11443. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11444. break;
  11445. case BO_AddAssign:
  11446. ConvertHalfVec = true;
  11447. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11448. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11449. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11450. break;
  11451. case BO_SubAssign:
  11452. ConvertHalfVec = true;
  11453. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11454. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11455. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11456. break;
  11457. case BO_ShlAssign:
  11458. case BO_ShrAssign:
  11459. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11460. CompLHSTy = CompResultTy;
  11461. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11462. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11463. break;
  11464. case BO_AndAssign:
  11465. case BO_OrAssign: // fallthrough
  11466. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11467. LLVM_FALLTHROUGH;
  11468. case BO_XorAssign:
  11469. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11470. CompLHSTy = CompResultTy;
  11471. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11472. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11473. break;
  11474. case BO_Comma:
  11475. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11476. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11477. VK = RHS.get()->getValueKind();
  11478. OK = RHS.get()->getObjectKind();
  11479. }
  11480. break;
  11481. }
  11482. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11483. return ExprError();
  11484. // Some of the binary operations require promoting operands of half vector to
  11485. // float vectors and truncating the result back to half vector. For now, we do
  11486. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11487. // arm64).
  11488. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11489. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11490. "both sides are half vectors or neither sides are");
  11491. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11492. LHS.get()->getType());
  11493. // Check for array bounds violations for both sides of the BinaryOperator
  11494. CheckArrayAccess(LHS.get());
  11495. CheckArrayAccess(RHS.get());
  11496. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11497. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11498. &Context.Idents.get("object_setClass"),
  11499. SourceLocation(), LookupOrdinaryName);
  11500. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11501. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11502. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11503. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11504. "object_setClass(")
  11505. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11506. ",")
  11507. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11508. }
  11509. else
  11510. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11511. }
  11512. else if (const ObjCIvarRefExpr *OIRE =
  11513. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11514. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11515. // Opc is not a compound assignment if CompResultTy is null.
  11516. if (CompResultTy.isNull()) {
  11517. if (ConvertHalfVec)
  11518. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11519. OpLoc, FPFeatures);
  11520. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11521. OK, OpLoc, FPFeatures);
  11522. }
  11523. // Handle compound assignments.
  11524. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11525. OK_ObjCProperty) {
  11526. VK = VK_LValue;
  11527. OK = LHS.get()->getObjectKind();
  11528. }
  11529. if (ConvertHalfVec)
  11530. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11531. OpLoc, FPFeatures);
  11532. return new (Context) CompoundAssignOperator(
  11533. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11534. OpLoc, FPFeatures);
  11535. }
  11536. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11537. /// operators are mixed in a way that suggests that the programmer forgot that
  11538. /// comparison operators have higher precedence. The most typical example of
  11539. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11540. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11541. SourceLocation OpLoc, Expr *LHSExpr,
  11542. Expr *RHSExpr) {
  11543. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11544. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11545. // Check that one of the sides is a comparison operator and the other isn't.
  11546. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11547. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11548. if (isLeftComp == isRightComp)
  11549. return;
  11550. // Bitwise operations are sometimes used as eager logical ops.
  11551. // Don't diagnose this.
  11552. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11553. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11554. if (isLeftBitwise || isRightBitwise)
  11555. return;
  11556. SourceRange DiagRange = isLeftComp
  11557. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11558. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11559. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11560. SourceRange ParensRange =
  11561. isLeftComp
  11562. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11563. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11564. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11565. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11566. SuggestParentheses(Self, OpLoc,
  11567. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11568. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11569. SuggestParentheses(Self, OpLoc,
  11570. Self.PDiag(diag::note_precedence_bitwise_first)
  11571. << BinaryOperator::getOpcodeStr(Opc),
  11572. ParensRange);
  11573. }
  11574. /// It accepts a '&&' expr that is inside a '||' one.
  11575. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11576. /// in parentheses.
  11577. static void
  11578. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11579. BinaryOperator *Bop) {
  11580. assert(Bop->getOpcode() == BO_LAnd);
  11581. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11582. << Bop->getSourceRange() << OpLoc;
  11583. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11584. Self.PDiag(diag::note_precedence_silence)
  11585. << Bop->getOpcodeStr(),
  11586. Bop->getSourceRange());
  11587. }
  11588. /// Returns true if the given expression can be evaluated as a constant
  11589. /// 'true'.
  11590. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11591. bool Res;
  11592. return !E->isValueDependent() &&
  11593. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11594. }
  11595. /// Returns true if the given expression can be evaluated as a constant
  11596. /// 'false'.
  11597. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11598. bool Res;
  11599. return !E->isValueDependent() &&
  11600. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11601. }
  11602. /// Look for '&&' in the left hand of a '||' expr.
  11603. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11604. Expr *LHSExpr, Expr *RHSExpr) {
  11605. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11606. if (Bop->getOpcode() == BO_LAnd) {
  11607. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11608. if (EvaluatesAsFalse(S, RHSExpr))
  11609. return;
  11610. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11611. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11612. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11613. } else if (Bop->getOpcode() == BO_LOr) {
  11614. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11615. // If it's "a || b && 1 || c" we didn't warn earlier for
  11616. // "a || b && 1", but warn now.
  11617. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11618. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11619. }
  11620. }
  11621. }
  11622. }
  11623. /// Look for '&&' in the right hand of a '||' expr.
  11624. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11625. Expr *LHSExpr, Expr *RHSExpr) {
  11626. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11627. if (Bop->getOpcode() == BO_LAnd) {
  11628. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11629. if (EvaluatesAsFalse(S, LHSExpr))
  11630. return;
  11631. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11632. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11633. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11634. }
  11635. }
  11636. }
  11637. /// Look for bitwise op in the left or right hand of a bitwise op with
  11638. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11639. /// the '&' expression in parentheses.
  11640. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11641. SourceLocation OpLoc, Expr *SubExpr) {
  11642. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11643. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11644. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11645. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11646. << Bop->getSourceRange() << OpLoc;
  11647. SuggestParentheses(S, Bop->getOperatorLoc(),
  11648. S.PDiag(diag::note_precedence_silence)
  11649. << Bop->getOpcodeStr(),
  11650. Bop->getSourceRange());
  11651. }
  11652. }
  11653. }
  11654. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11655. Expr *SubExpr, StringRef Shift) {
  11656. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11657. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11658. StringRef Op = Bop->getOpcodeStr();
  11659. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11660. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11661. SuggestParentheses(S, Bop->getOperatorLoc(),
  11662. S.PDiag(diag::note_precedence_silence) << Op,
  11663. Bop->getSourceRange());
  11664. }
  11665. }
  11666. }
  11667. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11668. Expr *LHSExpr, Expr *RHSExpr) {
  11669. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11670. if (!OCE)
  11671. return;
  11672. FunctionDecl *FD = OCE->getDirectCallee();
  11673. if (!FD || !FD->isOverloadedOperator())
  11674. return;
  11675. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11676. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11677. return;
  11678. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11679. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11680. << (Kind == OO_LessLess);
  11681. SuggestParentheses(S, OCE->getOperatorLoc(),
  11682. S.PDiag(diag::note_precedence_silence)
  11683. << (Kind == OO_LessLess ? "<<" : ">>"),
  11684. OCE->getSourceRange());
  11685. SuggestParentheses(
  11686. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11687. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11688. }
  11689. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11690. /// precedence.
  11691. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11692. SourceLocation OpLoc, Expr *LHSExpr,
  11693. Expr *RHSExpr){
  11694. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11695. if (BinaryOperator::isBitwiseOp(Opc))
  11696. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11697. // Diagnose "arg1 & arg2 | arg3"
  11698. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11699. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11700. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11701. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11702. }
  11703. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11704. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11705. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11706. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11707. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11708. }
  11709. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11710. || Opc == BO_Shr) {
  11711. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11712. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11713. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11714. }
  11715. // Warn on overloaded shift operators and comparisons, such as:
  11716. // cout << 5 == 4;
  11717. if (BinaryOperator::isComparisonOp(Opc))
  11718. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11719. }
  11720. // Binary Operators. 'Tok' is the token for the operator.
  11721. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11722. tok::TokenKind Kind,
  11723. Expr *LHSExpr, Expr *RHSExpr) {
  11724. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11725. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11726. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11727. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11728. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11729. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11730. }
  11731. /// Build an overloaded binary operator expression in the given scope.
  11732. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11733. BinaryOperatorKind Opc,
  11734. Expr *LHS, Expr *RHS) {
  11735. switch (Opc) {
  11736. case BO_Assign:
  11737. case BO_DivAssign:
  11738. case BO_RemAssign:
  11739. case BO_SubAssign:
  11740. case BO_AndAssign:
  11741. case BO_OrAssign:
  11742. case BO_XorAssign:
  11743. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11744. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11745. break;
  11746. default:
  11747. break;
  11748. }
  11749. // Find all of the overloaded operators visible from this
  11750. // point. We perform both an operator-name lookup from the local
  11751. // scope and an argument-dependent lookup based on the types of
  11752. // the arguments.
  11753. UnresolvedSet<16> Functions;
  11754. OverloadedOperatorKind OverOp
  11755. = BinaryOperator::getOverloadedOperator(Opc);
  11756. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11757. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11758. RHS->getType(), Functions);
  11759. // In C++20 onwards, we may have a second operator to look up.
  11760. if (S.getLangOpts().CPlusPlus2a) {
  11761. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
  11762. S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
  11763. RHS->getType(), Functions);
  11764. }
  11765. // Build the (potentially-overloaded, potentially-dependent)
  11766. // binary operation.
  11767. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11768. }
  11769. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11770. BinaryOperatorKind Opc,
  11771. Expr *LHSExpr, Expr *RHSExpr) {
  11772. ExprResult LHS, RHS;
  11773. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11774. if (!LHS.isUsable() || !RHS.isUsable())
  11775. return ExprError();
  11776. LHSExpr = LHS.get();
  11777. RHSExpr = RHS.get();
  11778. // We want to end up calling one of checkPseudoObjectAssignment
  11779. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11780. // both expressions are overloadable or either is type-dependent),
  11781. // or CreateBuiltinBinOp (in any other case). We also want to get
  11782. // any placeholder types out of the way.
  11783. // Handle pseudo-objects in the LHS.
  11784. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11785. // Assignments with a pseudo-object l-value need special analysis.
  11786. if (pty->getKind() == BuiltinType::PseudoObject &&
  11787. BinaryOperator::isAssignmentOp(Opc))
  11788. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11789. // Don't resolve overloads if the other type is overloadable.
  11790. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11791. // We can't actually test that if we still have a placeholder,
  11792. // though. Fortunately, none of the exceptions we see in that
  11793. // code below are valid when the LHS is an overload set. Note
  11794. // that an overload set can be dependently-typed, but it never
  11795. // instantiates to having an overloadable type.
  11796. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11797. if (resolvedRHS.isInvalid()) return ExprError();
  11798. RHSExpr = resolvedRHS.get();
  11799. if (RHSExpr->isTypeDependent() ||
  11800. RHSExpr->getType()->isOverloadableType())
  11801. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11802. }
  11803. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11804. // template, diagnose the missing 'template' keyword instead of diagnosing
  11805. // an invalid use of a bound member function.
  11806. //
  11807. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11808. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11809. if (Opc == BO_LT && inTemplateInstantiation() &&
  11810. (pty->getKind() == BuiltinType::BoundMember ||
  11811. pty->getKind() == BuiltinType::Overload)) {
  11812. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11813. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11814. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11815. return isa<FunctionTemplateDecl>(ND);
  11816. })) {
  11817. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11818. : OE->getNameLoc(),
  11819. diag::err_template_kw_missing)
  11820. << OE->getName().getAsString() << "";
  11821. return ExprError();
  11822. }
  11823. }
  11824. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11825. if (LHS.isInvalid()) return ExprError();
  11826. LHSExpr = LHS.get();
  11827. }
  11828. // Handle pseudo-objects in the RHS.
  11829. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11830. // An overload in the RHS can potentially be resolved by the type
  11831. // being assigned to.
  11832. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11833. if (getLangOpts().CPlusPlus &&
  11834. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11835. LHSExpr->getType()->isOverloadableType()))
  11836. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11837. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11838. }
  11839. // Don't resolve overloads if the other type is overloadable.
  11840. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11841. LHSExpr->getType()->isOverloadableType())
  11842. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11843. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11844. if (!resolvedRHS.isUsable()) return ExprError();
  11845. RHSExpr = resolvedRHS.get();
  11846. }
  11847. if (getLangOpts().CPlusPlus) {
  11848. // If either expression is type-dependent, always build an
  11849. // overloaded op.
  11850. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11851. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11852. // Otherwise, build an overloaded op if either expression has an
  11853. // overloadable type.
  11854. if (LHSExpr->getType()->isOverloadableType() ||
  11855. RHSExpr->getType()->isOverloadableType())
  11856. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11857. }
  11858. // Build a built-in binary operation.
  11859. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11860. }
  11861. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11862. if (T.isNull() || T->isDependentType())
  11863. return false;
  11864. if (!T->isPromotableIntegerType())
  11865. return true;
  11866. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11867. }
  11868. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11869. UnaryOperatorKind Opc,
  11870. Expr *InputExpr) {
  11871. ExprResult Input = InputExpr;
  11872. ExprValueKind VK = VK_RValue;
  11873. ExprObjectKind OK = OK_Ordinary;
  11874. QualType resultType;
  11875. bool CanOverflow = false;
  11876. bool ConvertHalfVec = false;
  11877. if (getLangOpts().OpenCL) {
  11878. QualType Ty = InputExpr->getType();
  11879. // The only legal unary operation for atomics is '&'.
  11880. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11881. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11882. // only with a builtin functions and therefore should be disallowed here.
  11883. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11884. || Ty->isBlockPointerType())) {
  11885. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11886. << InputExpr->getType()
  11887. << Input.get()->getSourceRange());
  11888. }
  11889. }
  11890. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11891. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11892. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11893. UnaryOperator::isArithmeticOp(Opc))
  11894. checkOpenMPDeviceExpr(InputExpr);
  11895. }
  11896. switch (Opc) {
  11897. case UO_PreInc:
  11898. case UO_PreDec:
  11899. case UO_PostInc:
  11900. case UO_PostDec:
  11901. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11902. OpLoc,
  11903. Opc == UO_PreInc ||
  11904. Opc == UO_PostInc,
  11905. Opc == UO_PreInc ||
  11906. Opc == UO_PreDec);
  11907. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11908. break;
  11909. case UO_AddrOf:
  11910. resultType = CheckAddressOfOperand(Input, OpLoc);
  11911. CheckAddressOfNoDeref(InputExpr);
  11912. RecordModifiableNonNullParam(*this, InputExpr);
  11913. break;
  11914. case UO_Deref: {
  11915. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11916. if (Input.isInvalid()) return ExprError();
  11917. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11918. break;
  11919. }
  11920. case UO_Plus:
  11921. case UO_Minus:
  11922. CanOverflow = Opc == UO_Minus &&
  11923. isOverflowingIntegerType(Context, Input.get()->getType());
  11924. Input = UsualUnaryConversions(Input.get());
  11925. if (Input.isInvalid()) return ExprError();
  11926. // Unary plus and minus require promoting an operand of half vector to a
  11927. // float vector and truncating the result back to a half vector. For now, we
  11928. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11929. // arm or arm64).
  11930. ConvertHalfVec =
  11931. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11932. // If the operand is a half vector, promote it to a float vector.
  11933. if (ConvertHalfVec)
  11934. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11935. resultType = Input.get()->getType();
  11936. if (resultType->isDependentType())
  11937. break;
  11938. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11939. break;
  11940. else if (resultType->isVectorType() &&
  11941. // The z vector extensions don't allow + or - with bool vectors.
  11942. (!Context.getLangOpts().ZVector ||
  11943. resultType->castAs<VectorType>()->getVectorKind() !=
  11944. VectorType::AltiVecBool))
  11945. break;
  11946. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11947. Opc == UO_Plus &&
  11948. resultType->isPointerType())
  11949. break;
  11950. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11951. << resultType << Input.get()->getSourceRange());
  11952. case UO_Not: // bitwise complement
  11953. Input = UsualUnaryConversions(Input.get());
  11954. if (Input.isInvalid())
  11955. return ExprError();
  11956. resultType = Input.get()->getType();
  11957. if (resultType->isDependentType())
  11958. break;
  11959. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11960. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11961. // C99 does not support '~' for complex conjugation.
  11962. Diag(OpLoc, diag::ext_integer_complement_complex)
  11963. << resultType << Input.get()->getSourceRange();
  11964. else if (resultType->hasIntegerRepresentation())
  11965. break;
  11966. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11967. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11968. // on vector float types.
  11969. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  11970. if (!T->isIntegerType())
  11971. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11972. << resultType << Input.get()->getSourceRange());
  11973. } else {
  11974. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11975. << resultType << Input.get()->getSourceRange());
  11976. }
  11977. break;
  11978. case UO_LNot: // logical negation
  11979. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11980. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11981. if (Input.isInvalid()) return ExprError();
  11982. resultType = Input.get()->getType();
  11983. // Though we still have to promote half FP to float...
  11984. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11985. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11986. resultType = Context.FloatTy;
  11987. }
  11988. if (resultType->isDependentType())
  11989. break;
  11990. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11991. // C99 6.5.3.3p1: ok, fallthrough;
  11992. if (Context.getLangOpts().CPlusPlus) {
  11993. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11994. // operand contextually converted to bool.
  11995. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11996. ScalarTypeToBooleanCastKind(resultType));
  11997. } else if (Context.getLangOpts().OpenCL &&
  11998. Context.getLangOpts().OpenCLVersion < 120) {
  11999. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  12000. // operate on scalar float types.
  12001. if (!resultType->isIntegerType() && !resultType->isPointerType())
  12002. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12003. << resultType << Input.get()->getSourceRange());
  12004. }
  12005. } else if (resultType->isExtVectorType()) {
  12006. if (Context.getLangOpts().OpenCL &&
  12007. Context.getLangOpts().OpenCLVersion < 120 &&
  12008. !Context.getLangOpts().OpenCLCPlusPlus) {
  12009. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  12010. // operate on vector float types.
  12011. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  12012. if (!T->isIntegerType())
  12013. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12014. << resultType << Input.get()->getSourceRange());
  12015. }
  12016. // Vector logical not returns the signed variant of the operand type.
  12017. resultType = GetSignedVectorType(resultType);
  12018. break;
  12019. } else {
  12020. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  12021. // type in C++. We should allow that here too.
  12022. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12023. << resultType << Input.get()->getSourceRange());
  12024. }
  12025. // LNot always has type int. C99 6.5.3.3p5.
  12026. // In C++, it's bool. C++ 5.3.1p8
  12027. resultType = Context.getLogicalOperationType();
  12028. break;
  12029. case UO_Real:
  12030. case UO_Imag:
  12031. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  12032. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  12033. // complex l-values to ordinary l-values and all other values to r-values.
  12034. if (Input.isInvalid()) return ExprError();
  12035. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  12036. if (Input.get()->getValueKind() != VK_RValue &&
  12037. Input.get()->getObjectKind() == OK_Ordinary)
  12038. VK = Input.get()->getValueKind();
  12039. } else if (!getLangOpts().CPlusPlus) {
  12040. // In C, a volatile scalar is read by __imag. In C++, it is not.
  12041. Input = DefaultLvalueConversion(Input.get());
  12042. }
  12043. break;
  12044. case UO_Extension:
  12045. resultType = Input.get()->getType();
  12046. VK = Input.get()->getValueKind();
  12047. OK = Input.get()->getObjectKind();
  12048. break;
  12049. case UO_Coawait:
  12050. // It's unnecessary to represent the pass-through operator co_await in the
  12051. // AST; just return the input expression instead.
  12052. assert(!Input.get()->getType()->isDependentType() &&
  12053. "the co_await expression must be non-dependant before "
  12054. "building operator co_await");
  12055. return Input;
  12056. }
  12057. if (resultType.isNull() || Input.isInvalid())
  12058. return ExprError();
  12059. // Check for array bounds violations in the operand of the UnaryOperator,
  12060. // except for the '*' and '&' operators that have to be handled specially
  12061. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  12062. // that are explicitly defined as valid by the standard).
  12063. if (Opc != UO_AddrOf && Opc != UO_Deref)
  12064. CheckArrayAccess(Input.get());
  12065. auto *UO = new (Context)
  12066. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  12067. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  12068. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  12069. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  12070. // Convert the result back to a half vector.
  12071. if (ConvertHalfVec)
  12072. return convertVector(UO, Context.HalfTy, *this);
  12073. return UO;
  12074. }
  12075. /// Determine whether the given expression is a qualified member
  12076. /// access expression, of a form that could be turned into a pointer to member
  12077. /// with the address-of operator.
  12078. bool Sema::isQualifiedMemberAccess(Expr *E) {
  12079. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12080. if (!DRE->getQualifier())
  12081. return false;
  12082. ValueDecl *VD = DRE->getDecl();
  12083. if (!VD->isCXXClassMember())
  12084. return false;
  12085. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  12086. return true;
  12087. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  12088. return Method->isInstance();
  12089. return false;
  12090. }
  12091. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12092. if (!ULE->getQualifier())
  12093. return false;
  12094. for (NamedDecl *D : ULE->decls()) {
  12095. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  12096. if (Method->isInstance())
  12097. return true;
  12098. } else {
  12099. // Overload set does not contain methods.
  12100. break;
  12101. }
  12102. }
  12103. return false;
  12104. }
  12105. return false;
  12106. }
  12107. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  12108. UnaryOperatorKind Opc, Expr *Input) {
  12109. // First things first: handle placeholders so that the
  12110. // overloaded-operator check considers the right type.
  12111. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  12112. // Increment and decrement of pseudo-object references.
  12113. if (pty->getKind() == BuiltinType::PseudoObject &&
  12114. UnaryOperator::isIncrementDecrementOp(Opc))
  12115. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  12116. // extension is always a builtin operator.
  12117. if (Opc == UO_Extension)
  12118. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12119. // & gets special logic for several kinds of placeholder.
  12120. // The builtin code knows what to do.
  12121. if (Opc == UO_AddrOf &&
  12122. (pty->getKind() == BuiltinType::Overload ||
  12123. pty->getKind() == BuiltinType::UnknownAny ||
  12124. pty->getKind() == BuiltinType::BoundMember))
  12125. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12126. // Anything else needs to be handled now.
  12127. ExprResult Result = CheckPlaceholderExpr(Input);
  12128. if (Result.isInvalid()) return ExprError();
  12129. Input = Result.get();
  12130. }
  12131. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  12132. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  12133. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  12134. // Find all of the overloaded operators visible from this
  12135. // point. We perform both an operator-name lookup from the local
  12136. // scope and an argument-dependent lookup based on the types of
  12137. // the arguments.
  12138. UnresolvedSet<16> Functions;
  12139. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  12140. if (S && OverOp != OO_None)
  12141. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  12142. Functions);
  12143. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  12144. }
  12145. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12146. }
  12147. // Unary Operators. 'Tok' is the token for the operator.
  12148. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  12149. tok::TokenKind Op, Expr *Input) {
  12150. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  12151. }
  12152. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  12153. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  12154. LabelDecl *TheDecl) {
  12155. TheDecl->markUsed(Context);
  12156. // Create the AST node. The address of a label always has type 'void*'.
  12157. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  12158. Context.getPointerType(Context.VoidTy));
  12159. }
  12160. void Sema::ActOnStartStmtExpr() {
  12161. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  12162. }
  12163. void Sema::ActOnStmtExprError() {
  12164. // Note that function is also called by TreeTransform when leaving a
  12165. // StmtExpr scope without rebuilding anything.
  12166. DiscardCleanupsInEvaluationContext();
  12167. PopExpressionEvaluationContext();
  12168. }
  12169. ExprResult
  12170. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  12171. SourceLocation RPLoc) { // "({..})"
  12172. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  12173. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  12174. if (hasAnyUnrecoverableErrorsInThisFunction())
  12175. DiscardCleanupsInEvaluationContext();
  12176. assert(!Cleanup.exprNeedsCleanups() &&
  12177. "cleanups within StmtExpr not correctly bound!");
  12178. PopExpressionEvaluationContext();
  12179. // FIXME: there are a variety of strange constraints to enforce here, for
  12180. // example, it is not possible to goto into a stmt expression apparently.
  12181. // More semantic analysis is needed.
  12182. // If there are sub-stmts in the compound stmt, take the type of the last one
  12183. // as the type of the stmtexpr.
  12184. QualType Ty = Context.VoidTy;
  12185. bool StmtExprMayBindToTemp = false;
  12186. if (!Compound->body_empty()) {
  12187. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  12188. if (const auto *LastStmt =
  12189. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  12190. if (const Expr *Value = LastStmt->getExprStmt()) {
  12191. StmtExprMayBindToTemp = true;
  12192. Ty = Value->getType();
  12193. }
  12194. }
  12195. }
  12196. // FIXME: Check that expression type is complete/non-abstract; statement
  12197. // expressions are not lvalues.
  12198. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  12199. if (StmtExprMayBindToTemp)
  12200. return MaybeBindToTemporary(ResStmtExpr);
  12201. return ResStmtExpr;
  12202. }
  12203. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  12204. if (ER.isInvalid())
  12205. return ExprError();
  12206. // Do function/array conversion on the last expression, but not
  12207. // lvalue-to-rvalue. However, initialize an unqualified type.
  12208. ER = DefaultFunctionArrayConversion(ER.get());
  12209. if (ER.isInvalid())
  12210. return ExprError();
  12211. Expr *E = ER.get();
  12212. if (E->isTypeDependent())
  12213. return E;
  12214. // In ARC, if the final expression ends in a consume, splice
  12215. // the consume out and bind it later. In the alternate case
  12216. // (when dealing with a retainable type), the result
  12217. // initialization will create a produce. In both cases the
  12218. // result will be +1, and we'll need to balance that out with
  12219. // a bind.
  12220. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  12221. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  12222. return Cast->getSubExpr();
  12223. // FIXME: Provide a better location for the initialization.
  12224. return PerformCopyInitialization(
  12225. InitializedEntity::InitializeStmtExprResult(
  12226. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  12227. SourceLocation(), E);
  12228. }
  12229. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  12230. TypeSourceInfo *TInfo,
  12231. ArrayRef<OffsetOfComponent> Components,
  12232. SourceLocation RParenLoc) {
  12233. QualType ArgTy = TInfo->getType();
  12234. bool Dependent = ArgTy->isDependentType();
  12235. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  12236. // We must have at least one component that refers to the type, and the first
  12237. // one is known to be a field designator. Verify that the ArgTy represents
  12238. // a struct/union/class.
  12239. if (!Dependent && !ArgTy->isRecordType())
  12240. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  12241. << ArgTy << TypeRange);
  12242. // Type must be complete per C99 7.17p3 because a declaring a variable
  12243. // with an incomplete type would be ill-formed.
  12244. if (!Dependent
  12245. && RequireCompleteType(BuiltinLoc, ArgTy,
  12246. diag::err_offsetof_incomplete_type, TypeRange))
  12247. return ExprError();
  12248. bool DidWarnAboutNonPOD = false;
  12249. QualType CurrentType = ArgTy;
  12250. SmallVector<OffsetOfNode, 4> Comps;
  12251. SmallVector<Expr*, 4> Exprs;
  12252. for (const OffsetOfComponent &OC : Components) {
  12253. if (OC.isBrackets) {
  12254. // Offset of an array sub-field. TODO: Should we allow vector elements?
  12255. if (!CurrentType->isDependentType()) {
  12256. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  12257. if(!AT)
  12258. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  12259. << CurrentType);
  12260. CurrentType = AT->getElementType();
  12261. } else
  12262. CurrentType = Context.DependentTy;
  12263. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  12264. if (IdxRval.isInvalid())
  12265. return ExprError();
  12266. Expr *Idx = IdxRval.get();
  12267. // The expression must be an integral expression.
  12268. // FIXME: An integral constant expression?
  12269. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  12270. !Idx->getType()->isIntegerType())
  12271. return ExprError(
  12272. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  12273. << Idx->getSourceRange());
  12274. // Record this array index.
  12275. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  12276. Exprs.push_back(Idx);
  12277. continue;
  12278. }
  12279. // Offset of a field.
  12280. if (CurrentType->isDependentType()) {
  12281. // We have the offset of a field, but we can't look into the dependent
  12282. // type. Just record the identifier of the field.
  12283. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  12284. CurrentType = Context.DependentTy;
  12285. continue;
  12286. }
  12287. // We need to have a complete type to look into.
  12288. if (RequireCompleteType(OC.LocStart, CurrentType,
  12289. diag::err_offsetof_incomplete_type))
  12290. return ExprError();
  12291. // Look for the designated field.
  12292. const RecordType *RC = CurrentType->getAs<RecordType>();
  12293. if (!RC)
  12294. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  12295. << CurrentType);
  12296. RecordDecl *RD = RC->getDecl();
  12297. // C++ [lib.support.types]p5:
  12298. // The macro offsetof accepts a restricted set of type arguments in this
  12299. // International Standard. type shall be a POD structure or a POD union
  12300. // (clause 9).
  12301. // C++11 [support.types]p4:
  12302. // If type is not a standard-layout class (Clause 9), the results are
  12303. // undefined.
  12304. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  12305. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  12306. unsigned DiagID =
  12307. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  12308. : diag::ext_offsetof_non_pod_type;
  12309. if (!IsSafe && !DidWarnAboutNonPOD &&
  12310. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  12311. PDiag(DiagID)
  12312. << SourceRange(Components[0].LocStart, OC.LocEnd)
  12313. << CurrentType))
  12314. DidWarnAboutNonPOD = true;
  12315. }
  12316. // Look for the field.
  12317. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  12318. LookupQualifiedName(R, RD);
  12319. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  12320. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  12321. if (!MemberDecl) {
  12322. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  12323. MemberDecl = IndirectMemberDecl->getAnonField();
  12324. }
  12325. if (!MemberDecl)
  12326. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  12327. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  12328. OC.LocEnd));
  12329. // C99 7.17p3:
  12330. // (If the specified member is a bit-field, the behavior is undefined.)
  12331. //
  12332. // We diagnose this as an error.
  12333. if (MemberDecl->isBitField()) {
  12334. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  12335. << MemberDecl->getDeclName()
  12336. << SourceRange(BuiltinLoc, RParenLoc);
  12337. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  12338. return ExprError();
  12339. }
  12340. RecordDecl *Parent = MemberDecl->getParent();
  12341. if (IndirectMemberDecl)
  12342. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  12343. // If the member was found in a base class, introduce OffsetOfNodes for
  12344. // the base class indirections.
  12345. CXXBasePaths Paths;
  12346. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  12347. Paths)) {
  12348. if (Paths.getDetectedVirtual()) {
  12349. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  12350. << MemberDecl->getDeclName()
  12351. << SourceRange(BuiltinLoc, RParenLoc);
  12352. return ExprError();
  12353. }
  12354. CXXBasePath &Path = Paths.front();
  12355. for (const CXXBasePathElement &B : Path)
  12356. Comps.push_back(OffsetOfNode(B.Base));
  12357. }
  12358. if (IndirectMemberDecl) {
  12359. for (auto *FI : IndirectMemberDecl->chain()) {
  12360. assert(isa<FieldDecl>(FI));
  12361. Comps.push_back(OffsetOfNode(OC.LocStart,
  12362. cast<FieldDecl>(FI), OC.LocEnd));
  12363. }
  12364. } else
  12365. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  12366. CurrentType = MemberDecl->getType().getNonReferenceType();
  12367. }
  12368. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  12369. Comps, Exprs, RParenLoc);
  12370. }
  12371. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  12372. SourceLocation BuiltinLoc,
  12373. SourceLocation TypeLoc,
  12374. ParsedType ParsedArgTy,
  12375. ArrayRef<OffsetOfComponent> Components,
  12376. SourceLocation RParenLoc) {
  12377. TypeSourceInfo *ArgTInfo;
  12378. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12379. if (ArgTy.isNull())
  12380. return ExprError();
  12381. if (!ArgTInfo)
  12382. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12383. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12384. }
  12385. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12386. Expr *CondExpr,
  12387. Expr *LHSExpr, Expr *RHSExpr,
  12388. SourceLocation RPLoc) {
  12389. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12390. ExprValueKind VK = VK_RValue;
  12391. ExprObjectKind OK = OK_Ordinary;
  12392. QualType resType;
  12393. bool ValueDependent = false;
  12394. bool CondIsTrue = false;
  12395. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12396. resType = Context.DependentTy;
  12397. ValueDependent = true;
  12398. } else {
  12399. // The conditional expression is required to be a constant expression.
  12400. llvm::APSInt condEval(32);
  12401. ExprResult CondICE
  12402. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12403. diag::err_typecheck_choose_expr_requires_constant, false);
  12404. if (CondICE.isInvalid())
  12405. return ExprError();
  12406. CondExpr = CondICE.get();
  12407. CondIsTrue = condEval.getZExtValue();
  12408. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12409. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12410. resType = ActiveExpr->getType();
  12411. ValueDependent = ActiveExpr->isValueDependent();
  12412. VK = ActiveExpr->getValueKind();
  12413. OK = ActiveExpr->getObjectKind();
  12414. }
  12415. return new (Context)
  12416. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12417. CondIsTrue, resType->isDependentType(), ValueDependent);
  12418. }
  12419. //===----------------------------------------------------------------------===//
  12420. // Clang Extensions.
  12421. //===----------------------------------------------------------------------===//
  12422. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12423. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12424. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12425. if (LangOpts.CPlusPlus) {
  12426. MangleNumberingContext *MCtx;
  12427. Decl *ManglingContextDecl;
  12428. std::tie(MCtx, ManglingContextDecl) =
  12429. getCurrentMangleNumberContext(Block->getDeclContext());
  12430. if (MCtx) {
  12431. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12432. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12433. }
  12434. }
  12435. PushBlockScope(CurScope, Block);
  12436. CurContext->addDecl(Block);
  12437. if (CurScope)
  12438. PushDeclContext(CurScope, Block);
  12439. else
  12440. CurContext = Block;
  12441. getCurBlock()->HasImplicitReturnType = true;
  12442. // Enter a new evaluation context to insulate the block from any
  12443. // cleanups from the enclosing full-expression.
  12444. PushExpressionEvaluationContext(
  12445. ExpressionEvaluationContext::PotentiallyEvaluated);
  12446. }
  12447. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12448. Scope *CurScope) {
  12449. assert(ParamInfo.getIdentifier() == nullptr &&
  12450. "block-id should have no identifier!");
  12451. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12452. BlockScopeInfo *CurBlock = getCurBlock();
  12453. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12454. QualType T = Sig->getType();
  12455. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12456. // in turn, make the block expression contain unexpanded parameter packs.
  12457. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12458. // Drop the parameters.
  12459. FunctionProtoType::ExtProtoInfo EPI;
  12460. EPI.HasTrailingReturn = false;
  12461. EPI.TypeQuals.addConst();
  12462. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12463. Sig = Context.getTrivialTypeSourceInfo(T);
  12464. }
  12465. // GetTypeForDeclarator always produces a function type for a block
  12466. // literal signature. Furthermore, it is always a FunctionProtoType
  12467. // unless the function was written with a typedef.
  12468. assert(T->isFunctionType() &&
  12469. "GetTypeForDeclarator made a non-function block signature");
  12470. // Look for an explicit signature in that function type.
  12471. FunctionProtoTypeLoc ExplicitSignature;
  12472. if ((ExplicitSignature = Sig->getTypeLoc()
  12473. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12474. // Check whether that explicit signature was synthesized by
  12475. // GetTypeForDeclarator. If so, don't save that as part of the
  12476. // written signature.
  12477. if (ExplicitSignature.getLocalRangeBegin() ==
  12478. ExplicitSignature.getLocalRangeEnd()) {
  12479. // This would be much cheaper if we stored TypeLocs instead of
  12480. // TypeSourceInfos.
  12481. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12482. unsigned Size = Result.getFullDataSize();
  12483. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12484. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12485. ExplicitSignature = FunctionProtoTypeLoc();
  12486. }
  12487. }
  12488. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12489. CurBlock->FunctionType = T;
  12490. const FunctionType *Fn = T->getAs<FunctionType>();
  12491. QualType RetTy = Fn->getReturnType();
  12492. bool isVariadic =
  12493. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12494. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12495. // Context.DependentTy is used as a placeholder for a missing block
  12496. // return type. TODO: what should we do with declarators like:
  12497. // ^ * { ... }
  12498. // If the answer is "apply template argument deduction"....
  12499. if (RetTy != Context.DependentTy) {
  12500. CurBlock->ReturnType = RetTy;
  12501. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12502. CurBlock->HasImplicitReturnType = false;
  12503. }
  12504. // Push block parameters from the declarator if we had them.
  12505. SmallVector<ParmVarDecl*, 8> Params;
  12506. if (ExplicitSignature) {
  12507. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12508. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12509. if (Param->getIdentifier() == nullptr &&
  12510. !Param->isImplicit() &&
  12511. !Param->isInvalidDecl() &&
  12512. !getLangOpts().CPlusPlus)
  12513. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12514. Params.push_back(Param);
  12515. }
  12516. // Fake up parameter variables if we have a typedef, like
  12517. // ^ fntype { ... }
  12518. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12519. for (const auto &I : Fn->param_types()) {
  12520. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12521. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12522. Params.push_back(Param);
  12523. }
  12524. }
  12525. // Set the parameters on the block decl.
  12526. if (!Params.empty()) {
  12527. CurBlock->TheDecl->setParams(Params);
  12528. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12529. /*CheckParameterNames=*/false);
  12530. }
  12531. // Finally we can process decl attributes.
  12532. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12533. // Put the parameter variables in scope.
  12534. for (auto AI : CurBlock->TheDecl->parameters()) {
  12535. AI->setOwningFunction(CurBlock->TheDecl);
  12536. // If this has an identifier, add it to the scope stack.
  12537. if (AI->getIdentifier()) {
  12538. CheckShadow(CurBlock->TheScope, AI);
  12539. PushOnScopeChains(AI, CurBlock->TheScope);
  12540. }
  12541. }
  12542. }
  12543. /// ActOnBlockError - If there is an error parsing a block, this callback
  12544. /// is invoked to pop the information about the block from the action impl.
  12545. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12546. // Leave the expression-evaluation context.
  12547. DiscardCleanupsInEvaluationContext();
  12548. PopExpressionEvaluationContext();
  12549. // Pop off CurBlock, handle nested blocks.
  12550. PopDeclContext();
  12551. PopFunctionScopeInfo();
  12552. }
  12553. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12554. /// literal was successfully completed. ^(int x){...}
  12555. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12556. Stmt *Body, Scope *CurScope) {
  12557. // If blocks are disabled, emit an error.
  12558. if (!LangOpts.Blocks)
  12559. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12560. // Leave the expression-evaluation context.
  12561. if (hasAnyUnrecoverableErrorsInThisFunction())
  12562. DiscardCleanupsInEvaluationContext();
  12563. assert(!Cleanup.exprNeedsCleanups() &&
  12564. "cleanups within block not correctly bound!");
  12565. PopExpressionEvaluationContext();
  12566. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12567. BlockDecl *BD = BSI->TheDecl;
  12568. if (BSI->HasImplicitReturnType)
  12569. deduceClosureReturnType(*BSI);
  12570. QualType RetTy = Context.VoidTy;
  12571. if (!BSI->ReturnType.isNull())
  12572. RetTy = BSI->ReturnType;
  12573. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12574. QualType BlockTy;
  12575. // If the user wrote a function type in some form, try to use that.
  12576. if (!BSI->FunctionType.isNull()) {
  12577. const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
  12578. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12579. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12580. // Turn protoless block types into nullary block types.
  12581. if (isa<FunctionNoProtoType>(FTy)) {
  12582. FunctionProtoType::ExtProtoInfo EPI;
  12583. EPI.ExtInfo = Ext;
  12584. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12585. // Otherwise, if we don't need to change anything about the function type,
  12586. // preserve its sugar structure.
  12587. } else if (FTy->getReturnType() == RetTy &&
  12588. (!NoReturn || FTy->getNoReturnAttr())) {
  12589. BlockTy = BSI->FunctionType;
  12590. // Otherwise, make the minimal modifications to the function type.
  12591. } else {
  12592. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12593. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12594. EPI.TypeQuals = Qualifiers();
  12595. EPI.ExtInfo = Ext;
  12596. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12597. }
  12598. // If we don't have a function type, just build one from nothing.
  12599. } else {
  12600. FunctionProtoType::ExtProtoInfo EPI;
  12601. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12602. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12603. }
  12604. DiagnoseUnusedParameters(BD->parameters());
  12605. BlockTy = Context.getBlockPointerType(BlockTy);
  12606. // If needed, diagnose invalid gotos and switches in the block.
  12607. if (getCurFunction()->NeedsScopeChecking() &&
  12608. !PP.isCodeCompletionEnabled())
  12609. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12610. BD->setBody(cast<CompoundStmt>(Body));
  12611. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12612. DiagnoseUnguardedAvailabilityViolations(BD);
  12613. // Try to apply the named return value optimization. We have to check again
  12614. // if we can do this, though, because blocks keep return statements around
  12615. // to deduce an implicit return type.
  12616. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12617. !BD->isDependentContext())
  12618. computeNRVO(Body, BSI);
  12619. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  12620. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  12621. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  12622. NTCUK_Destruct|NTCUK_Copy);
  12623. PopDeclContext();
  12624. // Pop the block scope now but keep it alive to the end of this function.
  12625. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12626. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12627. // Set the captured variables on the block.
  12628. SmallVector<BlockDecl::Capture, 4> Captures;
  12629. for (Capture &Cap : BSI->Captures) {
  12630. if (Cap.isInvalid() || Cap.isThisCapture())
  12631. continue;
  12632. VarDecl *Var = Cap.getVariable();
  12633. Expr *CopyExpr = nullptr;
  12634. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12635. if (const RecordType *Record =
  12636. Cap.getCaptureType()->getAs<RecordType>()) {
  12637. // The capture logic needs the destructor, so make sure we mark it.
  12638. // Usually this is unnecessary because most local variables have
  12639. // their destructors marked at declaration time, but parameters are
  12640. // an exception because it's technically only the call site that
  12641. // actually requires the destructor.
  12642. if (isa<ParmVarDecl>(Var))
  12643. FinalizeVarWithDestructor(Var, Record);
  12644. // Enter a separate potentially-evaluated context while building block
  12645. // initializers to isolate their cleanups from those of the block
  12646. // itself.
  12647. // FIXME: Is this appropriate even when the block itself occurs in an
  12648. // unevaluated operand?
  12649. EnterExpressionEvaluationContext EvalContext(
  12650. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12651. SourceLocation Loc = Cap.getLocation();
  12652. ExprResult Result = BuildDeclarationNameExpr(
  12653. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12654. // According to the blocks spec, the capture of a variable from
  12655. // the stack requires a const copy constructor. This is not true
  12656. // of the copy/move done to move a __block variable to the heap.
  12657. if (!Result.isInvalid() &&
  12658. !Result.get()->getType().isConstQualified()) {
  12659. Result = ImpCastExprToType(Result.get(),
  12660. Result.get()->getType().withConst(),
  12661. CK_NoOp, VK_LValue);
  12662. }
  12663. if (!Result.isInvalid()) {
  12664. Result = PerformCopyInitialization(
  12665. InitializedEntity::InitializeBlock(Var->getLocation(),
  12666. Cap.getCaptureType(), false),
  12667. Loc, Result.get());
  12668. }
  12669. // Build a full-expression copy expression if initialization
  12670. // succeeded and used a non-trivial constructor. Recover from
  12671. // errors by pretending that the copy isn't necessary.
  12672. if (!Result.isInvalid() &&
  12673. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12674. ->isTrivial()) {
  12675. Result = MaybeCreateExprWithCleanups(Result);
  12676. CopyExpr = Result.get();
  12677. }
  12678. }
  12679. }
  12680. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12681. CopyExpr);
  12682. Captures.push_back(NewCap);
  12683. }
  12684. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12685. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12686. // If the block isn't obviously global, i.e. it captures anything at
  12687. // all, then we need to do a few things in the surrounding context:
  12688. if (Result->getBlockDecl()->hasCaptures()) {
  12689. // First, this expression has a new cleanup object.
  12690. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12691. Cleanup.setExprNeedsCleanups(true);
  12692. // It also gets a branch-protected scope if any of the captured
  12693. // variables needs destruction.
  12694. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12695. const VarDecl *var = CI.getVariable();
  12696. if (var->getType().isDestructedType() != QualType::DK_none) {
  12697. setFunctionHasBranchProtectedScope();
  12698. break;
  12699. }
  12700. }
  12701. }
  12702. if (getCurFunction())
  12703. getCurFunction()->addBlock(BD);
  12704. return Result;
  12705. }
  12706. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12707. SourceLocation RPLoc) {
  12708. TypeSourceInfo *TInfo;
  12709. GetTypeFromParser(Ty, &TInfo);
  12710. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12711. }
  12712. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12713. Expr *E, TypeSourceInfo *TInfo,
  12714. SourceLocation RPLoc) {
  12715. Expr *OrigExpr = E;
  12716. bool IsMS = false;
  12717. // CUDA device code does not support varargs.
  12718. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12719. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12720. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12721. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12722. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12723. }
  12724. }
  12725. // NVPTX does not support va_arg expression.
  12726. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12727. Context.getTargetInfo().getTriple().isNVPTX())
  12728. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12729. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12730. // as Microsoft ABI on an actual Microsoft platform, where
  12731. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12732. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12733. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12734. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12735. if (Context.hasSameType(MSVaListType, E->getType())) {
  12736. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12737. return ExprError();
  12738. IsMS = true;
  12739. }
  12740. }
  12741. // Get the va_list type
  12742. QualType VaListType = Context.getBuiltinVaListType();
  12743. if (!IsMS) {
  12744. if (VaListType->isArrayType()) {
  12745. // Deal with implicit array decay; for example, on x86-64,
  12746. // va_list is an array, but it's supposed to decay to
  12747. // a pointer for va_arg.
  12748. VaListType = Context.getArrayDecayedType(VaListType);
  12749. // Make sure the input expression also decays appropriately.
  12750. ExprResult Result = UsualUnaryConversions(E);
  12751. if (Result.isInvalid())
  12752. return ExprError();
  12753. E = Result.get();
  12754. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12755. // If va_list is a record type and we are compiling in C++ mode,
  12756. // check the argument using reference binding.
  12757. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12758. Context, Context.getLValueReferenceType(VaListType), false);
  12759. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12760. if (Init.isInvalid())
  12761. return ExprError();
  12762. E = Init.getAs<Expr>();
  12763. } else {
  12764. // Otherwise, the va_list argument must be an l-value because
  12765. // it is modified by va_arg.
  12766. if (!E->isTypeDependent() &&
  12767. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12768. return ExprError();
  12769. }
  12770. }
  12771. if (!IsMS && !E->isTypeDependent() &&
  12772. !Context.hasSameType(VaListType, E->getType()))
  12773. return ExprError(
  12774. Diag(E->getBeginLoc(),
  12775. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12776. << OrigExpr->getType() << E->getSourceRange());
  12777. if (!TInfo->getType()->isDependentType()) {
  12778. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12779. diag::err_second_parameter_to_va_arg_incomplete,
  12780. TInfo->getTypeLoc()))
  12781. return ExprError();
  12782. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12783. TInfo->getType(),
  12784. diag::err_second_parameter_to_va_arg_abstract,
  12785. TInfo->getTypeLoc()))
  12786. return ExprError();
  12787. if (!TInfo->getType().isPODType(Context)) {
  12788. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12789. TInfo->getType()->isObjCLifetimeType()
  12790. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12791. : diag::warn_second_parameter_to_va_arg_not_pod)
  12792. << TInfo->getType()
  12793. << TInfo->getTypeLoc().getSourceRange();
  12794. }
  12795. // Check for va_arg where arguments of the given type will be promoted
  12796. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12797. QualType PromoteType;
  12798. if (TInfo->getType()->isPromotableIntegerType()) {
  12799. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12800. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12801. PromoteType = QualType();
  12802. }
  12803. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12804. PromoteType = Context.DoubleTy;
  12805. if (!PromoteType.isNull())
  12806. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12807. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12808. << TInfo->getType()
  12809. << PromoteType
  12810. << TInfo->getTypeLoc().getSourceRange());
  12811. }
  12812. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12813. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12814. }
  12815. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12816. // The type of __null will be int or long, depending on the size of
  12817. // pointers on the target.
  12818. QualType Ty;
  12819. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12820. if (pw == Context.getTargetInfo().getIntWidth())
  12821. Ty = Context.IntTy;
  12822. else if (pw == Context.getTargetInfo().getLongWidth())
  12823. Ty = Context.LongTy;
  12824. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12825. Ty = Context.LongLongTy;
  12826. else {
  12827. llvm_unreachable("I don't know size of pointer!");
  12828. }
  12829. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12830. }
  12831. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12832. SourceLocation BuiltinLoc,
  12833. SourceLocation RPLoc) {
  12834. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12835. }
  12836. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12837. SourceLocation BuiltinLoc,
  12838. SourceLocation RPLoc,
  12839. DeclContext *ParentContext) {
  12840. return new (Context)
  12841. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12842. }
  12843. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12844. bool Diagnose) {
  12845. if (!getLangOpts().ObjC)
  12846. return false;
  12847. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12848. if (!PT)
  12849. return false;
  12850. if (!PT->isObjCIdType()) {
  12851. // Check if the destination is the 'NSString' interface.
  12852. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12853. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12854. return false;
  12855. }
  12856. // Ignore any parens, implicit casts (should only be
  12857. // array-to-pointer decays), and not-so-opaque values. The last is
  12858. // important for making this trigger for property assignments.
  12859. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12860. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12861. if (OV->getSourceExpr())
  12862. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12863. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12864. if (!SL || !SL->isAscii())
  12865. return false;
  12866. if (Diagnose) {
  12867. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12868. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12869. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12870. }
  12871. return true;
  12872. }
  12873. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12874. const Expr *SrcExpr) {
  12875. if (!DstType->isFunctionPointerType() ||
  12876. !SrcExpr->getType()->isFunctionType())
  12877. return false;
  12878. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12879. if (!DRE)
  12880. return false;
  12881. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12882. if (!FD)
  12883. return false;
  12884. return !S.checkAddressOfFunctionIsAvailable(FD,
  12885. /*Complain=*/true,
  12886. SrcExpr->getBeginLoc());
  12887. }
  12888. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12889. SourceLocation Loc,
  12890. QualType DstType, QualType SrcType,
  12891. Expr *SrcExpr, AssignmentAction Action,
  12892. bool *Complained) {
  12893. if (Complained)
  12894. *Complained = false;
  12895. // Decode the result (notice that AST's are still created for extensions).
  12896. bool CheckInferredResultType = false;
  12897. bool isInvalid = false;
  12898. unsigned DiagKind = 0;
  12899. FixItHint Hint;
  12900. ConversionFixItGenerator ConvHints;
  12901. bool MayHaveConvFixit = false;
  12902. bool MayHaveFunctionDiff = false;
  12903. const ObjCInterfaceDecl *IFace = nullptr;
  12904. const ObjCProtocolDecl *PDecl = nullptr;
  12905. switch (ConvTy) {
  12906. case Compatible:
  12907. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12908. return false;
  12909. case PointerToInt:
  12910. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12911. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12912. MayHaveConvFixit = true;
  12913. break;
  12914. case IntToPointer:
  12915. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12916. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12917. MayHaveConvFixit = true;
  12918. break;
  12919. case IncompatiblePointer:
  12920. if (Action == AA_Passing_CFAudited)
  12921. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12922. else if (SrcType->isFunctionPointerType() &&
  12923. DstType->isFunctionPointerType())
  12924. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12925. else
  12926. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12927. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12928. SrcType->isObjCObjectPointerType();
  12929. if (Hint.isNull() && !CheckInferredResultType) {
  12930. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12931. }
  12932. else if (CheckInferredResultType) {
  12933. SrcType = SrcType.getUnqualifiedType();
  12934. DstType = DstType.getUnqualifiedType();
  12935. }
  12936. MayHaveConvFixit = true;
  12937. break;
  12938. case IncompatiblePointerSign:
  12939. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12940. break;
  12941. case FunctionVoidPointer:
  12942. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12943. break;
  12944. case IncompatiblePointerDiscardsQualifiers: {
  12945. // Perform array-to-pointer decay if necessary.
  12946. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12947. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12948. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12949. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12950. DiagKind = diag::err_typecheck_incompatible_address_space;
  12951. break;
  12952. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12953. DiagKind = diag::err_typecheck_incompatible_ownership;
  12954. break;
  12955. }
  12956. llvm_unreachable("unknown error case for discarding qualifiers!");
  12957. // fallthrough
  12958. }
  12959. case CompatiblePointerDiscardsQualifiers:
  12960. // If the qualifiers lost were because we were applying the
  12961. // (deprecated) C++ conversion from a string literal to a char*
  12962. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12963. // Ideally, this check would be performed in
  12964. // checkPointerTypesForAssignment. However, that would require a
  12965. // bit of refactoring (so that the second argument is an
  12966. // expression, rather than a type), which should be done as part
  12967. // of a larger effort to fix checkPointerTypesForAssignment for
  12968. // C++ semantics.
  12969. if (getLangOpts().CPlusPlus &&
  12970. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12971. return false;
  12972. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12973. break;
  12974. case IncompatibleNestedPointerQualifiers:
  12975. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12976. break;
  12977. case IncompatibleNestedPointerAddressSpaceMismatch:
  12978. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12979. break;
  12980. case IntToBlockPointer:
  12981. DiagKind = diag::err_int_to_block_pointer;
  12982. break;
  12983. case IncompatibleBlockPointer:
  12984. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12985. break;
  12986. case IncompatibleObjCQualifiedId: {
  12987. if (SrcType->isObjCQualifiedIdType()) {
  12988. const ObjCObjectPointerType *srcOPT =
  12989. SrcType->castAs<ObjCObjectPointerType>();
  12990. for (auto *srcProto : srcOPT->quals()) {
  12991. PDecl = srcProto;
  12992. break;
  12993. }
  12994. if (const ObjCInterfaceType *IFaceT =
  12995. DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  12996. IFace = IFaceT->getDecl();
  12997. }
  12998. else if (DstType->isObjCQualifiedIdType()) {
  12999. const ObjCObjectPointerType *dstOPT =
  13000. DstType->castAs<ObjCObjectPointerType>();
  13001. for (auto *dstProto : dstOPT->quals()) {
  13002. PDecl = dstProto;
  13003. break;
  13004. }
  13005. if (const ObjCInterfaceType *IFaceT =
  13006. SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  13007. IFace = IFaceT->getDecl();
  13008. }
  13009. DiagKind = diag::warn_incompatible_qualified_id;
  13010. break;
  13011. }
  13012. case IncompatibleVectors:
  13013. DiagKind = diag::warn_incompatible_vectors;
  13014. break;
  13015. case IncompatibleObjCWeakRef:
  13016. DiagKind = diag::err_arc_weak_unavailable_assign;
  13017. break;
  13018. case Incompatible:
  13019. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  13020. if (Complained)
  13021. *Complained = true;
  13022. return true;
  13023. }
  13024. DiagKind = diag::err_typecheck_convert_incompatible;
  13025. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  13026. MayHaveConvFixit = true;
  13027. isInvalid = true;
  13028. MayHaveFunctionDiff = true;
  13029. break;
  13030. }
  13031. QualType FirstType, SecondType;
  13032. switch (Action) {
  13033. case AA_Assigning:
  13034. case AA_Initializing:
  13035. // The destination type comes first.
  13036. FirstType = DstType;
  13037. SecondType = SrcType;
  13038. break;
  13039. case AA_Returning:
  13040. case AA_Passing:
  13041. case AA_Passing_CFAudited:
  13042. case AA_Converting:
  13043. case AA_Sending:
  13044. case AA_Casting:
  13045. // The source type comes first.
  13046. FirstType = SrcType;
  13047. SecondType = DstType;
  13048. break;
  13049. }
  13050. PartialDiagnostic FDiag = PDiag(DiagKind);
  13051. if (Action == AA_Passing_CFAudited)
  13052. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  13053. else
  13054. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  13055. // If we can fix the conversion, suggest the FixIts.
  13056. assert(ConvHints.isNull() || Hint.isNull());
  13057. if (!ConvHints.isNull()) {
  13058. for (FixItHint &H : ConvHints.Hints)
  13059. FDiag << H;
  13060. } else {
  13061. FDiag << Hint;
  13062. }
  13063. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  13064. if (MayHaveFunctionDiff)
  13065. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  13066. Diag(Loc, FDiag);
  13067. if (DiagKind == diag::warn_incompatible_qualified_id &&
  13068. PDecl && IFace && !IFace->hasDefinition())
  13069. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  13070. << IFace << PDecl;
  13071. if (SecondType == Context.OverloadTy)
  13072. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  13073. FirstType, /*TakingAddress=*/true);
  13074. if (CheckInferredResultType)
  13075. EmitRelatedResultTypeNote(SrcExpr);
  13076. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  13077. EmitRelatedResultTypeNoteForReturn(DstType);
  13078. if (Complained)
  13079. *Complained = true;
  13080. return isInvalid;
  13081. }
  13082. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13083. llvm::APSInt *Result) {
  13084. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  13085. public:
  13086. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13087. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  13088. }
  13089. } Diagnoser;
  13090. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  13091. }
  13092. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13093. llvm::APSInt *Result,
  13094. unsigned DiagID,
  13095. bool AllowFold) {
  13096. class IDDiagnoser : public VerifyICEDiagnoser {
  13097. unsigned DiagID;
  13098. public:
  13099. IDDiagnoser(unsigned DiagID)
  13100. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  13101. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13102. S.Diag(Loc, DiagID) << SR;
  13103. }
  13104. } Diagnoser(DiagID);
  13105. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  13106. }
  13107. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  13108. SourceRange SR) {
  13109. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  13110. }
  13111. ExprResult
  13112. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  13113. VerifyICEDiagnoser &Diagnoser,
  13114. bool AllowFold) {
  13115. SourceLocation DiagLoc = E->getBeginLoc();
  13116. if (getLangOpts().CPlusPlus11) {
  13117. // C++11 [expr.const]p5:
  13118. // If an expression of literal class type is used in a context where an
  13119. // integral constant expression is required, then that class type shall
  13120. // have a single non-explicit conversion function to an integral or
  13121. // unscoped enumeration type
  13122. ExprResult Converted;
  13123. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  13124. public:
  13125. CXX11ConvertDiagnoser(bool Silent)
  13126. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  13127. Silent, true) {}
  13128. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  13129. QualType T) override {
  13130. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  13131. }
  13132. SemaDiagnosticBuilder diagnoseIncomplete(
  13133. Sema &S, SourceLocation Loc, QualType T) override {
  13134. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  13135. }
  13136. SemaDiagnosticBuilder diagnoseExplicitConv(
  13137. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13138. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  13139. }
  13140. SemaDiagnosticBuilder noteExplicitConv(
  13141. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13142. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13143. << ConvTy->isEnumeralType() << ConvTy;
  13144. }
  13145. SemaDiagnosticBuilder diagnoseAmbiguous(
  13146. Sema &S, SourceLocation Loc, QualType T) override {
  13147. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  13148. }
  13149. SemaDiagnosticBuilder noteAmbiguous(
  13150. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13151. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13152. << ConvTy->isEnumeralType() << ConvTy;
  13153. }
  13154. SemaDiagnosticBuilder diagnoseConversion(
  13155. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13156. llvm_unreachable("conversion functions are permitted");
  13157. }
  13158. } ConvertDiagnoser(Diagnoser.Suppress);
  13159. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  13160. ConvertDiagnoser);
  13161. if (Converted.isInvalid())
  13162. return Converted;
  13163. E = Converted.get();
  13164. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  13165. return ExprError();
  13166. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  13167. // An ICE must be of integral or unscoped enumeration type.
  13168. if (!Diagnoser.Suppress)
  13169. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13170. return ExprError();
  13171. }
  13172. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  13173. // in the non-ICE case.
  13174. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  13175. if (Result)
  13176. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  13177. if (!isa<ConstantExpr>(E))
  13178. E = ConstantExpr::Create(Context, E);
  13179. return E;
  13180. }
  13181. Expr::EvalResult EvalResult;
  13182. SmallVector<PartialDiagnosticAt, 8> Notes;
  13183. EvalResult.Diag = &Notes;
  13184. // Try to evaluate the expression, and produce diagnostics explaining why it's
  13185. // not a constant expression as a side-effect.
  13186. bool Folded =
  13187. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  13188. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  13189. if (!isa<ConstantExpr>(E))
  13190. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  13191. // In C++11, we can rely on diagnostics being produced for any expression
  13192. // which is not a constant expression. If no diagnostics were produced, then
  13193. // this is a constant expression.
  13194. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  13195. if (Result)
  13196. *Result = EvalResult.Val.getInt();
  13197. return E;
  13198. }
  13199. // If our only note is the usual "invalid subexpression" note, just point
  13200. // the caret at its location rather than producing an essentially
  13201. // redundant note.
  13202. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  13203. diag::note_invalid_subexpr_in_const_expr) {
  13204. DiagLoc = Notes[0].first;
  13205. Notes.clear();
  13206. }
  13207. if (!Folded || !AllowFold) {
  13208. if (!Diagnoser.Suppress) {
  13209. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13210. for (const PartialDiagnosticAt &Note : Notes)
  13211. Diag(Note.first, Note.second);
  13212. }
  13213. return ExprError();
  13214. }
  13215. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  13216. for (const PartialDiagnosticAt &Note : Notes)
  13217. Diag(Note.first, Note.second);
  13218. if (Result)
  13219. *Result = EvalResult.Val.getInt();
  13220. return E;
  13221. }
  13222. namespace {
  13223. // Handle the case where we conclude a expression which we speculatively
  13224. // considered to be unevaluated is actually evaluated.
  13225. class TransformToPE : public TreeTransform<TransformToPE> {
  13226. typedef TreeTransform<TransformToPE> BaseTransform;
  13227. public:
  13228. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  13229. // Make sure we redo semantic analysis
  13230. bool AlwaysRebuild() { return true; }
  13231. bool ReplacingOriginal() { return true; }
  13232. // We need to special-case DeclRefExprs referring to FieldDecls which
  13233. // are not part of a member pointer formation; normal TreeTransforming
  13234. // doesn't catch this case because of the way we represent them in the AST.
  13235. // FIXME: This is a bit ugly; is it really the best way to handle this
  13236. // case?
  13237. //
  13238. // Error on DeclRefExprs referring to FieldDecls.
  13239. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  13240. if (isa<FieldDecl>(E->getDecl()) &&
  13241. !SemaRef.isUnevaluatedContext())
  13242. return SemaRef.Diag(E->getLocation(),
  13243. diag::err_invalid_non_static_member_use)
  13244. << E->getDecl() << E->getSourceRange();
  13245. return BaseTransform::TransformDeclRefExpr(E);
  13246. }
  13247. // Exception: filter out member pointer formation
  13248. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  13249. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  13250. return E;
  13251. return BaseTransform::TransformUnaryOperator(E);
  13252. }
  13253. // The body of a lambda-expression is in a separate expression evaluation
  13254. // context so never needs to be transformed.
  13255. // FIXME: Ideally we wouldn't transform the closure type either, and would
  13256. // just recreate the capture expressions and lambda expression.
  13257. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  13258. return SkipLambdaBody(E, Body);
  13259. }
  13260. };
  13261. }
  13262. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  13263. assert(isUnevaluatedContext() &&
  13264. "Should only transform unevaluated expressions");
  13265. ExprEvalContexts.back().Context =
  13266. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  13267. if (isUnevaluatedContext())
  13268. return E;
  13269. return TransformToPE(*this).TransformExpr(E);
  13270. }
  13271. void
  13272. Sema::PushExpressionEvaluationContext(
  13273. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  13274. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13275. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  13276. LambdaContextDecl, ExprContext);
  13277. Cleanup.reset();
  13278. if (!MaybeODRUseExprs.empty())
  13279. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  13280. }
  13281. void
  13282. Sema::PushExpressionEvaluationContext(
  13283. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  13284. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13285. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  13286. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  13287. }
  13288. namespace {
  13289. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  13290. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  13291. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  13292. if (E->getOpcode() == UO_Deref)
  13293. return CheckPossibleDeref(S, E->getSubExpr());
  13294. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  13295. return CheckPossibleDeref(S, E->getBase());
  13296. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  13297. return CheckPossibleDeref(S, E->getBase());
  13298. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  13299. QualType Inner;
  13300. QualType Ty = E->getType();
  13301. if (const auto *Ptr = Ty->getAs<PointerType>())
  13302. Inner = Ptr->getPointeeType();
  13303. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  13304. Inner = Arr->getElementType();
  13305. else
  13306. return nullptr;
  13307. if (Inner->hasAttr(attr::NoDeref))
  13308. return E;
  13309. }
  13310. return nullptr;
  13311. }
  13312. } // namespace
  13313. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  13314. for (const Expr *E : Rec.PossibleDerefs) {
  13315. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  13316. if (DeclRef) {
  13317. const ValueDecl *Decl = DeclRef->getDecl();
  13318. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  13319. << Decl->getName() << E->getSourceRange();
  13320. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  13321. } else {
  13322. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  13323. << E->getSourceRange();
  13324. }
  13325. }
  13326. Rec.PossibleDerefs.clear();
  13327. }
  13328. /// Check whether E, which is either a discarded-value expression or an
  13329. /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
  13330. /// and if so, remove it from the list of volatile-qualified assignments that
  13331. /// we are going to warn are deprecated.
  13332. void Sema::CheckUnusedVolatileAssignment(Expr *E) {
  13333. if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
  13334. return;
  13335. // Note: ignoring parens here is not justified by the standard rules, but
  13336. // ignoring parentheses seems like a more reasonable approach, and this only
  13337. // drives a deprecation warning so doesn't affect conformance.
  13338. if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
  13339. if (BO->getOpcode() == BO_Assign) {
  13340. auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
  13341. LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
  13342. LHSs.end());
  13343. }
  13344. }
  13345. }
  13346. void Sema::PopExpressionEvaluationContext() {
  13347. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  13348. unsigned NumTypos = Rec.NumTypos;
  13349. if (!Rec.Lambdas.empty()) {
  13350. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  13351. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  13352. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  13353. unsigned D;
  13354. if (Rec.isUnevaluated()) {
  13355. // C++11 [expr.prim.lambda]p2:
  13356. // A lambda-expression shall not appear in an unevaluated operand
  13357. // (Clause 5).
  13358. D = diag::err_lambda_unevaluated_operand;
  13359. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  13360. // C++1y [expr.const]p2:
  13361. // A conditional-expression e is a core constant expression unless the
  13362. // evaluation of e, following the rules of the abstract machine, would
  13363. // evaluate [...] a lambda-expression.
  13364. D = diag::err_lambda_in_constant_expression;
  13365. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  13366. // C++17 [expr.prim.lamda]p2:
  13367. // A lambda-expression shall not appear [...] in a template-argument.
  13368. D = diag::err_lambda_in_invalid_context;
  13369. } else
  13370. llvm_unreachable("Couldn't infer lambda error message.");
  13371. for (const auto *L : Rec.Lambdas)
  13372. Diag(L->getBeginLoc(), D);
  13373. }
  13374. }
  13375. WarnOnPendingNoDerefs(Rec);
  13376. // Warn on any volatile-qualified simple-assignments that are not discarded-
  13377. // value expressions nor unevaluated operands (those cases get removed from
  13378. // this list by CheckUnusedVolatileAssignment).
  13379. for (auto *BO : Rec.VolatileAssignmentLHSs)
  13380. Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
  13381. << BO->getType();
  13382. // When are coming out of an unevaluated context, clear out any
  13383. // temporaries that we may have created as part of the evaluation of
  13384. // the expression in that context: they aren't relevant because they
  13385. // will never be constructed.
  13386. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  13387. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  13388. ExprCleanupObjects.end());
  13389. Cleanup = Rec.ParentCleanup;
  13390. CleanupVarDeclMarking();
  13391. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  13392. // Otherwise, merge the contexts together.
  13393. } else {
  13394. Cleanup.mergeFrom(Rec.ParentCleanup);
  13395. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  13396. Rec.SavedMaybeODRUseExprs.end());
  13397. }
  13398. // Pop the current expression evaluation context off the stack.
  13399. ExprEvalContexts.pop_back();
  13400. // The global expression evaluation context record is never popped.
  13401. ExprEvalContexts.back().NumTypos += NumTypos;
  13402. }
  13403. void Sema::DiscardCleanupsInEvaluationContext() {
  13404. ExprCleanupObjects.erase(
  13405. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  13406. ExprCleanupObjects.end());
  13407. Cleanup.reset();
  13408. MaybeODRUseExprs.clear();
  13409. }
  13410. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13411. ExprResult Result = CheckPlaceholderExpr(E);
  13412. if (Result.isInvalid())
  13413. return ExprError();
  13414. E = Result.get();
  13415. if (!E->getType()->isVariablyModifiedType())
  13416. return E;
  13417. return TransformToPotentiallyEvaluated(E);
  13418. }
  13419. /// Are we in a context that is potentially constant evaluated per C++20
  13420. /// [expr.const]p12?
  13421. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13422. /// C++2a [expr.const]p12:
  13423. // An expression or conversion is potentially constant evaluated if it is
  13424. switch (SemaRef.ExprEvalContexts.back().Context) {
  13425. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13426. // -- a manifestly constant-evaluated expression,
  13427. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13428. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13429. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13430. // -- a potentially-evaluated expression,
  13431. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13432. // -- an immediate subexpression of a braced-init-list,
  13433. // -- [FIXME] an expression of the form & cast-expression that occurs
  13434. // within a templated entity
  13435. // -- a subexpression of one of the above that is not a subexpression of
  13436. // a nested unevaluated operand.
  13437. return true;
  13438. case Sema::ExpressionEvaluationContext::Unevaluated:
  13439. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13440. // Expressions in this context are never evaluated.
  13441. return false;
  13442. }
  13443. llvm_unreachable("Invalid context");
  13444. }
  13445. /// Return true if this function has a calling convention that requires mangling
  13446. /// in the size of the parameter pack.
  13447. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  13448. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  13449. // we don't need parameter type sizes.
  13450. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  13451. if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
  13452. TT.getArch() != llvm::Triple::x86_64))
  13453. return false;
  13454. // If this is C++ and this isn't an extern "C" function, parameters do not
  13455. // need to be complete. In this case, C++ mangling will apply, which doesn't
  13456. // use the size of the parameters.
  13457. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  13458. return false;
  13459. // Stdcall, fastcall, and vectorcall need this special treatment.
  13460. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13461. switch (CC) {
  13462. case CC_X86StdCall:
  13463. case CC_X86FastCall:
  13464. case CC_X86VectorCall:
  13465. return true;
  13466. default:
  13467. break;
  13468. }
  13469. return false;
  13470. }
  13471. /// Require that all of the parameter types of function be complete. Normally,
  13472. /// parameter types are only required to be complete when a function is called
  13473. /// or defined, but to mangle functions with certain calling conventions, the
  13474. /// mangler needs to know the size of the parameter list. In this situation,
  13475. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  13476. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  13477. /// result in a linker error. Clang doesn't implement this behavior, and instead
  13478. /// attempts to error at compile time.
  13479. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  13480. SourceLocation Loc) {
  13481. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  13482. FunctionDecl *FD;
  13483. ParmVarDecl *Param;
  13484. public:
  13485. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  13486. : FD(FD), Param(Param) {}
  13487. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13488. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13489. StringRef CCName;
  13490. switch (CC) {
  13491. case CC_X86StdCall:
  13492. CCName = "stdcall";
  13493. break;
  13494. case CC_X86FastCall:
  13495. CCName = "fastcall";
  13496. break;
  13497. case CC_X86VectorCall:
  13498. CCName = "vectorcall";
  13499. break;
  13500. default:
  13501. llvm_unreachable("CC does not need mangling");
  13502. }
  13503. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  13504. << Param->getDeclName() << FD->getDeclName() << CCName;
  13505. }
  13506. };
  13507. for (ParmVarDecl *Param : FD->parameters()) {
  13508. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  13509. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  13510. }
  13511. }
  13512. namespace {
  13513. enum class OdrUseContext {
  13514. /// Declarations in this context are not odr-used.
  13515. None,
  13516. /// Declarations in this context are formally odr-used, but this is a
  13517. /// dependent context.
  13518. Dependent,
  13519. /// Declarations in this context are odr-used but not actually used (yet).
  13520. FormallyOdrUsed,
  13521. /// Declarations in this context are used.
  13522. Used
  13523. };
  13524. }
  13525. /// Are we within a context in which references to resolved functions or to
  13526. /// variables result in odr-use?
  13527. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13528. OdrUseContext Result;
  13529. switch (SemaRef.ExprEvalContexts.back().Context) {
  13530. case Sema::ExpressionEvaluationContext::Unevaluated:
  13531. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13532. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13533. return OdrUseContext::None;
  13534. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13535. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13536. Result = OdrUseContext::Used;
  13537. break;
  13538. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13539. Result = OdrUseContext::FormallyOdrUsed;
  13540. break;
  13541. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13542. // A default argument formally results in odr-use, but doesn't actually
  13543. // result in a use in any real sense until it itself is used.
  13544. Result = OdrUseContext::FormallyOdrUsed;
  13545. break;
  13546. }
  13547. if (SemaRef.CurContext->isDependentContext())
  13548. return OdrUseContext::Dependent;
  13549. return Result;
  13550. }
  13551. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13552. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13553. return Func->isConstexpr() &&
  13554. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13555. }
  13556. /// Mark a function referenced, and check whether it is odr-used
  13557. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13558. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13559. bool MightBeOdrUse) {
  13560. assert(Func && "No function?");
  13561. Func->setReferenced();
  13562. // Recursive functions aren't really used until they're used from some other
  13563. // context.
  13564. bool IsRecursiveCall = CurContext == Func;
  13565. // C++11 [basic.def.odr]p3:
  13566. // A function whose name appears as a potentially-evaluated expression is
  13567. // odr-used if it is the unique lookup result or the selected member of a
  13568. // set of overloaded functions [...].
  13569. //
  13570. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13571. // can just check that here.
  13572. OdrUseContext OdrUse =
  13573. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13574. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13575. OdrUse = OdrUseContext::FormallyOdrUsed;
  13576. // Trivial default constructors and destructors are never actually used.
  13577. // FIXME: What about other special members?
  13578. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  13579. OdrUse == OdrUseContext::Used) {
  13580. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  13581. if (Constructor->isDefaultConstructor())
  13582. OdrUse = OdrUseContext::FormallyOdrUsed;
  13583. if (isa<CXXDestructorDecl>(Func))
  13584. OdrUse = OdrUseContext::FormallyOdrUsed;
  13585. }
  13586. // C++20 [expr.const]p12:
  13587. // A function [...] is needed for constant evaluation if it is [...] a
  13588. // constexpr function that is named by an expression that is potentially
  13589. // constant evaluated
  13590. bool NeededForConstantEvaluation =
  13591. isPotentiallyConstantEvaluatedContext(*this) &&
  13592. isImplicitlyDefinableConstexprFunction(Func);
  13593. // Determine whether we require a function definition to exist, per
  13594. // C++11 [temp.inst]p3:
  13595. // Unless a function template specialization has been explicitly
  13596. // instantiated or explicitly specialized, the function template
  13597. // specialization is implicitly instantiated when the specialization is
  13598. // referenced in a context that requires a function definition to exist.
  13599. // C++20 [temp.inst]p7:
  13600. // The existence of a definition of a [...] function is considered to
  13601. // affect the semantics of the program if the [...] function is needed for
  13602. // constant evaluation by an expression
  13603. // C++20 [basic.def.odr]p10:
  13604. // Every program shall contain exactly one definition of every non-inline
  13605. // function or variable that is odr-used in that program outside of a
  13606. // discarded statement
  13607. // C++20 [special]p1:
  13608. // The implementation will implicitly define [defaulted special members]
  13609. // if they are odr-used or needed for constant evaluation.
  13610. //
  13611. // Note that we skip the implicit instantiation of templates that are only
  13612. // used in unused default arguments or by recursive calls to themselves.
  13613. // This is formally non-conforming, but seems reasonable in practice.
  13614. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13615. NeededForConstantEvaluation);
  13616. // C++14 [temp.expl.spec]p6:
  13617. // If a template [...] is explicitly specialized then that specialization
  13618. // shall be declared before the first use of that specialization that would
  13619. // cause an implicit instantiation to take place, in every translation unit
  13620. // in which such a use occurs
  13621. if (NeedDefinition &&
  13622. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13623. Func->getMemberSpecializationInfo()))
  13624. checkSpecializationVisibility(Loc, Func);
  13625. // C++14 [except.spec]p17:
  13626. // An exception-specification is considered to be needed when:
  13627. // - the function is odr-used or, if it appears in an unevaluated operand,
  13628. // would be odr-used if the expression were potentially-evaluated;
  13629. //
  13630. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13631. // function is a pure virtual function we're calling, and in that case the
  13632. // function was selected by overload resolution and we need to resolve its
  13633. // exception specification for a different reason.
  13634. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13635. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13636. ResolveExceptionSpec(Loc, FPT);
  13637. if (getLangOpts().CUDA)
  13638. CheckCUDACall(Loc, Func);
  13639. // If we need a definition, try to create one.
  13640. if (NeedDefinition && !Func->getBody()) {
  13641. runWithSufficientStackSpace(Loc, [&] {
  13642. if (CXXConstructorDecl *Constructor =
  13643. dyn_cast<CXXConstructorDecl>(Func)) {
  13644. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13645. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13646. if (Constructor->isDefaultConstructor()) {
  13647. if (Constructor->isTrivial() &&
  13648. !Constructor->hasAttr<DLLExportAttr>())
  13649. return;
  13650. DefineImplicitDefaultConstructor(Loc, Constructor);
  13651. } else if (Constructor->isCopyConstructor()) {
  13652. DefineImplicitCopyConstructor(Loc, Constructor);
  13653. } else if (Constructor->isMoveConstructor()) {
  13654. DefineImplicitMoveConstructor(Loc, Constructor);
  13655. }
  13656. } else if (Constructor->getInheritedConstructor()) {
  13657. DefineInheritingConstructor(Loc, Constructor);
  13658. }
  13659. } else if (CXXDestructorDecl *Destructor =
  13660. dyn_cast<CXXDestructorDecl>(Func)) {
  13661. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13662. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13663. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13664. return;
  13665. DefineImplicitDestructor(Loc, Destructor);
  13666. }
  13667. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13668. MarkVTableUsed(Loc, Destructor->getParent());
  13669. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13670. if (MethodDecl->isOverloadedOperator() &&
  13671. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13672. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13673. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13674. if (MethodDecl->isCopyAssignmentOperator())
  13675. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13676. else if (MethodDecl->isMoveAssignmentOperator())
  13677. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13678. }
  13679. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13680. MethodDecl->getParent()->isLambda()) {
  13681. CXXConversionDecl *Conversion =
  13682. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13683. if (Conversion->isLambdaToBlockPointerConversion())
  13684. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13685. else
  13686. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13687. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13688. MarkVTableUsed(Loc, MethodDecl->getParent());
  13689. }
  13690. // Implicit instantiation of function templates and member functions of
  13691. // class templates.
  13692. if (Func->isImplicitlyInstantiable()) {
  13693. TemplateSpecializationKind TSK =
  13694. Func->getTemplateSpecializationKindForInstantiation();
  13695. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13696. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13697. if (FirstInstantiation) {
  13698. PointOfInstantiation = Loc;
  13699. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13700. } else if (TSK != TSK_ImplicitInstantiation) {
  13701. // Use the point of use as the point of instantiation, instead of the
  13702. // point of explicit instantiation (which we track as the actual point
  13703. // of instantiation). This gives better backtraces in diagnostics.
  13704. PointOfInstantiation = Loc;
  13705. }
  13706. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13707. Func->isConstexpr()) {
  13708. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13709. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13710. CodeSynthesisContexts.size())
  13711. PendingLocalImplicitInstantiations.push_back(
  13712. std::make_pair(Func, PointOfInstantiation));
  13713. else if (Func->isConstexpr())
  13714. // Do not defer instantiations of constexpr functions, to avoid the
  13715. // expression evaluator needing to call back into Sema if it sees a
  13716. // call to such a function.
  13717. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13718. else {
  13719. Func->setInstantiationIsPending(true);
  13720. PendingInstantiations.push_back(
  13721. std::make_pair(Func, PointOfInstantiation));
  13722. // Notify the consumer that a function was implicitly instantiated.
  13723. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13724. }
  13725. }
  13726. } else {
  13727. // Walk redefinitions, as some of them may be instantiable.
  13728. for (auto i : Func->redecls()) {
  13729. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13730. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13731. }
  13732. }
  13733. });
  13734. }
  13735. // If this is the first "real" use, act on that.
  13736. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13737. // Keep track of used but undefined functions.
  13738. if (!Func->isDefined()) {
  13739. if (mightHaveNonExternalLinkage(Func))
  13740. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13741. else if (Func->getMostRecentDecl()->isInlined() &&
  13742. !LangOpts.GNUInline &&
  13743. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13744. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13745. else if (isExternalWithNoLinkageType(Func))
  13746. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13747. }
  13748. // Some x86 Windows calling conventions mangle the size of the parameter
  13749. // pack into the name. Computing the size of the parameters requires the
  13750. // parameter types to be complete. Check that now.
  13751. if (funcHasParameterSizeMangling(*this, Func))
  13752. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  13753. Func->markUsed(Context);
  13754. }
  13755. if (LangOpts.OpenMP) {
  13756. markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
  13757. if (LangOpts.OpenMPIsDevice)
  13758. checkOpenMPDeviceFunction(Loc, Func);
  13759. else
  13760. checkOpenMPHostFunction(Loc, Func);
  13761. }
  13762. }
  13763. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13764. /// MarkVariableReferenced since it does additional checks and then
  13765. /// calls MarkVarDeclODRUsed.
  13766. /// If the variable must be captured:
  13767. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13768. /// - else capture it in the DeclContext that maps to the
  13769. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13770. static void
  13771. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13772. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13773. // Keep track of used but undefined variables.
  13774. // FIXME: We shouldn't suppress this warning for static data members.
  13775. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13776. (!Var->isExternallyVisible() || Var->isInline() ||
  13777. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13778. !(Var->isStaticDataMember() && Var->hasInit())) {
  13779. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13780. if (old.isInvalid())
  13781. old = Loc;
  13782. }
  13783. QualType CaptureType, DeclRefType;
  13784. if (SemaRef.LangOpts.OpenMP)
  13785. SemaRef.tryCaptureOpenMPLambdas(Var);
  13786. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13787. /*EllipsisLoc*/ SourceLocation(),
  13788. /*BuildAndDiagnose*/ true,
  13789. CaptureType, DeclRefType,
  13790. FunctionScopeIndexToStopAt);
  13791. Var->markUsed(SemaRef.Context);
  13792. }
  13793. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13794. SourceLocation Loc,
  13795. unsigned CapturingScopeIndex) {
  13796. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13797. }
  13798. static void
  13799. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13800. ValueDecl *var, DeclContext *DC) {
  13801. DeclContext *VarDC = var->getDeclContext();
  13802. // If the parameter still belongs to the translation unit, then
  13803. // we're actually just using one parameter in the declaration of
  13804. // the next.
  13805. if (isa<ParmVarDecl>(var) &&
  13806. isa<TranslationUnitDecl>(VarDC))
  13807. return;
  13808. // For C code, don't diagnose about capture if we're not actually in code
  13809. // right now; it's impossible to write a non-constant expression outside of
  13810. // function context, so we'll get other (more useful) diagnostics later.
  13811. //
  13812. // For C++, things get a bit more nasty... it would be nice to suppress this
  13813. // diagnostic for certain cases like using a local variable in an array bound
  13814. // for a member of a local class, but the correct predicate is not obvious.
  13815. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13816. return;
  13817. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13818. unsigned ContextKind = 3; // unknown
  13819. if (isa<CXXMethodDecl>(VarDC) &&
  13820. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13821. ContextKind = 2;
  13822. } else if (isa<FunctionDecl>(VarDC)) {
  13823. ContextKind = 0;
  13824. } else if (isa<BlockDecl>(VarDC)) {
  13825. ContextKind = 1;
  13826. }
  13827. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13828. << var << ValueKind << ContextKind << VarDC;
  13829. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13830. << var;
  13831. // FIXME: Add additional diagnostic info about class etc. which prevents
  13832. // capture.
  13833. }
  13834. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13835. bool &SubCapturesAreNested,
  13836. QualType &CaptureType,
  13837. QualType &DeclRefType) {
  13838. // Check whether we've already captured it.
  13839. if (CSI->CaptureMap.count(Var)) {
  13840. // If we found a capture, any subcaptures are nested.
  13841. SubCapturesAreNested = true;
  13842. // Retrieve the capture type for this variable.
  13843. CaptureType = CSI->getCapture(Var).getCaptureType();
  13844. // Compute the type of an expression that refers to this variable.
  13845. DeclRefType = CaptureType.getNonReferenceType();
  13846. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13847. // are mutable in the sense that user can change their value - they are
  13848. // private instances of the captured declarations.
  13849. const Capture &Cap = CSI->getCapture(Var);
  13850. if (Cap.isCopyCapture() &&
  13851. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13852. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13853. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13854. DeclRefType.addConst();
  13855. return true;
  13856. }
  13857. return false;
  13858. }
  13859. // Only block literals, captured statements, and lambda expressions can
  13860. // capture; other scopes don't work.
  13861. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13862. SourceLocation Loc,
  13863. const bool Diagnose, Sema &S) {
  13864. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13865. return getLambdaAwareParentOfDeclContext(DC);
  13866. else if (Var->hasLocalStorage()) {
  13867. if (Diagnose)
  13868. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13869. }
  13870. return nullptr;
  13871. }
  13872. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13873. // certain types of variables (unnamed, variably modified types etc.)
  13874. // so check for eligibility.
  13875. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13876. SourceLocation Loc,
  13877. const bool Diagnose, Sema &S) {
  13878. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13879. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13880. // Lambdas are not allowed to capture unnamed variables
  13881. // (e.g. anonymous unions).
  13882. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13883. // assuming that's the intent.
  13884. if (IsLambda && !Var->getDeclName()) {
  13885. if (Diagnose) {
  13886. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13887. S.Diag(Var->getLocation(), diag::note_declared_at);
  13888. }
  13889. return false;
  13890. }
  13891. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13892. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13893. if (Diagnose) {
  13894. S.Diag(Loc, diag::err_ref_vm_type);
  13895. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13896. << Var->getDeclName();
  13897. }
  13898. return false;
  13899. }
  13900. // Prohibit structs with flexible array members too.
  13901. // We cannot capture what is in the tail end of the struct.
  13902. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13903. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13904. if (Diagnose) {
  13905. if (IsBlock)
  13906. S.Diag(Loc, diag::err_ref_flexarray_type);
  13907. else
  13908. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13909. << Var->getDeclName();
  13910. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13911. << Var->getDeclName();
  13912. }
  13913. return false;
  13914. }
  13915. }
  13916. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13917. // Lambdas and captured statements are not allowed to capture __block
  13918. // variables; they don't support the expected semantics.
  13919. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13920. if (Diagnose) {
  13921. S.Diag(Loc, diag::err_capture_block_variable)
  13922. << Var->getDeclName() << !IsLambda;
  13923. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13924. << Var->getDeclName();
  13925. }
  13926. return false;
  13927. }
  13928. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13929. if (S.getLangOpts().OpenCL && IsBlock &&
  13930. Var->getType()->isBlockPointerType()) {
  13931. if (Diagnose)
  13932. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13933. return false;
  13934. }
  13935. return true;
  13936. }
  13937. // Returns true if the capture by block was successful.
  13938. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13939. SourceLocation Loc,
  13940. const bool BuildAndDiagnose,
  13941. QualType &CaptureType,
  13942. QualType &DeclRefType,
  13943. const bool Nested,
  13944. Sema &S, bool Invalid) {
  13945. bool ByRef = false;
  13946. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13947. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13948. // (decayed to pointers).
  13949. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13950. if (BuildAndDiagnose) {
  13951. S.Diag(Loc, diag::err_ref_array_type);
  13952. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13953. << Var->getDeclName();
  13954. Invalid = true;
  13955. } else {
  13956. return false;
  13957. }
  13958. }
  13959. // Forbid the block-capture of autoreleasing variables.
  13960. if (!Invalid &&
  13961. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13962. if (BuildAndDiagnose) {
  13963. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13964. << /*block*/ 0;
  13965. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13966. << Var->getDeclName();
  13967. Invalid = true;
  13968. } else {
  13969. return false;
  13970. }
  13971. }
  13972. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13973. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13974. QualType PointeeTy = PT->getPointeeType();
  13975. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13976. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13977. !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
  13978. if (BuildAndDiagnose) {
  13979. SourceLocation VarLoc = Var->getLocation();
  13980. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13981. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13982. }
  13983. }
  13984. }
  13985. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13986. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13987. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13988. // Block capture by reference does not change the capture or
  13989. // declaration reference types.
  13990. ByRef = true;
  13991. } else {
  13992. // Block capture by copy introduces 'const'.
  13993. CaptureType = CaptureType.getNonReferenceType().withConst();
  13994. DeclRefType = CaptureType;
  13995. }
  13996. // Actually capture the variable.
  13997. if (BuildAndDiagnose)
  13998. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  13999. CaptureType, Invalid);
  14000. return !Invalid;
  14001. }
  14002. /// Capture the given variable in the captured region.
  14003. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  14004. VarDecl *Var,
  14005. SourceLocation Loc,
  14006. const bool BuildAndDiagnose,
  14007. QualType &CaptureType,
  14008. QualType &DeclRefType,
  14009. const bool RefersToCapturedVariable,
  14010. Sema &S, bool Invalid) {
  14011. // By default, capture variables by reference.
  14012. bool ByRef = true;
  14013. // Using an LValue reference type is consistent with Lambdas (see below).
  14014. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  14015. if (S.isOpenMPCapturedDecl(Var)) {
  14016. bool HasConst = DeclRefType.isConstQualified();
  14017. DeclRefType = DeclRefType.getUnqualifiedType();
  14018. // Don't lose diagnostics about assignments to const.
  14019. if (HasConst)
  14020. DeclRefType.addConst();
  14021. }
  14022. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  14023. RSI->OpenMPCaptureLevel);
  14024. }
  14025. if (ByRef)
  14026. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  14027. else
  14028. CaptureType = DeclRefType;
  14029. // Actually capture the variable.
  14030. if (BuildAndDiagnose)
  14031. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  14032. Loc, SourceLocation(), CaptureType, Invalid);
  14033. return !Invalid;
  14034. }
  14035. /// Capture the given variable in the lambda.
  14036. static bool captureInLambda(LambdaScopeInfo *LSI,
  14037. VarDecl *Var,
  14038. SourceLocation Loc,
  14039. const bool BuildAndDiagnose,
  14040. QualType &CaptureType,
  14041. QualType &DeclRefType,
  14042. const bool RefersToCapturedVariable,
  14043. const Sema::TryCaptureKind Kind,
  14044. SourceLocation EllipsisLoc,
  14045. const bool IsTopScope,
  14046. Sema &S, bool Invalid) {
  14047. // Determine whether we are capturing by reference or by value.
  14048. bool ByRef = false;
  14049. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  14050. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  14051. } else {
  14052. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  14053. }
  14054. // Compute the type of the field that will capture this variable.
  14055. if (ByRef) {
  14056. // C++11 [expr.prim.lambda]p15:
  14057. // An entity is captured by reference if it is implicitly or
  14058. // explicitly captured but not captured by copy. It is
  14059. // unspecified whether additional unnamed non-static data
  14060. // members are declared in the closure type for entities
  14061. // captured by reference.
  14062. //
  14063. // FIXME: It is not clear whether we want to build an lvalue reference
  14064. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  14065. // to do the former, while EDG does the latter. Core issue 1249 will
  14066. // clarify, but for now we follow GCC because it's a more permissive and
  14067. // easily defensible position.
  14068. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  14069. } else {
  14070. // C++11 [expr.prim.lambda]p14:
  14071. // For each entity captured by copy, an unnamed non-static
  14072. // data member is declared in the closure type. The
  14073. // declaration order of these members is unspecified. The type
  14074. // of such a data member is the type of the corresponding
  14075. // captured entity if the entity is not a reference to an
  14076. // object, or the referenced type otherwise. [Note: If the
  14077. // captured entity is a reference to a function, the
  14078. // corresponding data member is also a reference to a
  14079. // function. - end note ]
  14080. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  14081. if (!RefType->getPointeeType()->isFunctionType())
  14082. CaptureType = RefType->getPointeeType();
  14083. }
  14084. // Forbid the lambda copy-capture of autoreleasing variables.
  14085. if (!Invalid &&
  14086. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  14087. if (BuildAndDiagnose) {
  14088. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  14089. S.Diag(Var->getLocation(), diag::note_previous_decl)
  14090. << Var->getDeclName();
  14091. Invalid = true;
  14092. } else {
  14093. return false;
  14094. }
  14095. }
  14096. // Make sure that by-copy captures are of a complete and non-abstract type.
  14097. if (!Invalid && BuildAndDiagnose) {
  14098. if (!CaptureType->isDependentType() &&
  14099. S.RequireCompleteType(Loc, CaptureType,
  14100. diag::err_capture_of_incomplete_type,
  14101. Var->getDeclName()))
  14102. Invalid = true;
  14103. else if (S.RequireNonAbstractType(Loc, CaptureType,
  14104. diag::err_capture_of_abstract_type))
  14105. Invalid = true;
  14106. }
  14107. }
  14108. // Compute the type of a reference to this captured variable.
  14109. if (ByRef)
  14110. DeclRefType = CaptureType.getNonReferenceType();
  14111. else {
  14112. // C++ [expr.prim.lambda]p5:
  14113. // The closure type for a lambda-expression has a public inline
  14114. // function call operator [...]. This function call operator is
  14115. // declared const (9.3.1) if and only if the lambda-expression's
  14116. // parameter-declaration-clause is not followed by mutable.
  14117. DeclRefType = CaptureType.getNonReferenceType();
  14118. if (!LSI->Mutable && !CaptureType->isReferenceType())
  14119. DeclRefType.addConst();
  14120. }
  14121. // Add the capture.
  14122. if (BuildAndDiagnose)
  14123. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  14124. Loc, EllipsisLoc, CaptureType, Invalid);
  14125. return !Invalid;
  14126. }
  14127. bool Sema::tryCaptureVariable(
  14128. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  14129. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  14130. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  14131. // An init-capture is notionally from the context surrounding its
  14132. // declaration, but its parent DC is the lambda class.
  14133. DeclContext *VarDC = Var->getDeclContext();
  14134. if (Var->isInitCapture())
  14135. VarDC = VarDC->getParent();
  14136. DeclContext *DC = CurContext;
  14137. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  14138. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  14139. // We need to sync up the Declaration Context with the
  14140. // FunctionScopeIndexToStopAt
  14141. if (FunctionScopeIndexToStopAt) {
  14142. unsigned FSIndex = FunctionScopes.size() - 1;
  14143. while (FSIndex != MaxFunctionScopesIndex) {
  14144. DC = getLambdaAwareParentOfDeclContext(DC);
  14145. --FSIndex;
  14146. }
  14147. }
  14148. // If the variable is declared in the current context, there is no need to
  14149. // capture it.
  14150. if (VarDC == DC) return true;
  14151. // Capture global variables if it is required to use private copy of this
  14152. // variable.
  14153. bool IsGlobal = !Var->hasLocalStorage();
  14154. if (IsGlobal &&
  14155. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  14156. MaxFunctionScopesIndex)))
  14157. return true;
  14158. Var = Var->getCanonicalDecl();
  14159. // Walk up the stack to determine whether we can capture the variable,
  14160. // performing the "simple" checks that don't depend on type. We stop when
  14161. // we've either hit the declared scope of the variable or find an existing
  14162. // capture of that variable. We start from the innermost capturing-entity
  14163. // (the DC) and ensure that all intervening capturing-entities
  14164. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  14165. // declcontext can either capture the variable or have already captured
  14166. // the variable.
  14167. CaptureType = Var->getType();
  14168. DeclRefType = CaptureType.getNonReferenceType();
  14169. bool Nested = false;
  14170. bool Explicit = (Kind != TryCapture_Implicit);
  14171. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  14172. do {
  14173. // Only block literals, captured statements, and lambda expressions can
  14174. // capture; other scopes don't work.
  14175. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  14176. ExprLoc,
  14177. BuildAndDiagnose,
  14178. *this);
  14179. // We need to check for the parent *first* because, if we *have*
  14180. // private-captured a global variable, we need to recursively capture it in
  14181. // intermediate blocks, lambdas, etc.
  14182. if (!ParentDC) {
  14183. if (IsGlobal) {
  14184. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  14185. break;
  14186. }
  14187. return true;
  14188. }
  14189. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  14190. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  14191. // Check whether we've already captured it.
  14192. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  14193. DeclRefType)) {
  14194. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  14195. break;
  14196. }
  14197. // If we are instantiating a generic lambda call operator body,
  14198. // we do not want to capture new variables. What was captured
  14199. // during either a lambdas transformation or initial parsing
  14200. // should be used.
  14201. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  14202. if (BuildAndDiagnose) {
  14203. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14204. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  14205. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14206. Diag(Var->getLocation(), diag::note_previous_decl)
  14207. << Var->getDeclName();
  14208. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  14209. } else
  14210. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  14211. }
  14212. return true;
  14213. }
  14214. // Try to capture variable-length arrays types.
  14215. if (Var->getType()->isVariablyModifiedType()) {
  14216. // We're going to walk down into the type and look for VLA
  14217. // expressions.
  14218. QualType QTy = Var->getType();
  14219. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14220. QTy = PVD->getOriginalType();
  14221. captureVariablyModifiedType(Context, QTy, CSI);
  14222. }
  14223. if (getLangOpts().OpenMP) {
  14224. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14225. // OpenMP private variables should not be captured in outer scope, so
  14226. // just break here. Similarly, global variables that are captured in a
  14227. // target region should not be captured outside the scope of the region.
  14228. if (RSI->CapRegionKind == CR_OpenMP) {
  14229. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  14230. // If the variable is private (i.e. not captured) and has variably
  14231. // modified type, we still need to capture the type for correct
  14232. // codegen in all regions, associated with the construct. Currently,
  14233. // it is captured in the innermost captured region only.
  14234. if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
  14235. QualType QTy = Var->getType();
  14236. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14237. QTy = PVD->getOriginalType();
  14238. for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
  14239. I < E; ++I) {
  14240. auto *OuterRSI = cast<CapturedRegionScopeInfo>(
  14241. FunctionScopes[FunctionScopesIndex - I]);
  14242. assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
  14243. "Wrong number of captured regions associated with the "
  14244. "OpenMP construct.");
  14245. captureVariablyModifiedType(Context, QTy, OuterRSI);
  14246. }
  14247. }
  14248. bool IsTargetCap = !IsOpenMPPrivateDecl &&
  14249. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  14250. // When we detect target captures we are looking from inside the
  14251. // target region, therefore we need to propagate the capture from the
  14252. // enclosing region. Therefore, the capture is not initially nested.
  14253. if (IsTargetCap)
  14254. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  14255. if (IsTargetCap || IsOpenMPPrivateDecl) {
  14256. Nested = !IsTargetCap;
  14257. DeclRefType = DeclRefType.getUnqualifiedType();
  14258. CaptureType = Context.getLValueReferenceType(DeclRefType);
  14259. break;
  14260. }
  14261. }
  14262. }
  14263. }
  14264. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  14265. // No capture-default, and this is not an explicit capture
  14266. // so cannot capture this variable.
  14267. if (BuildAndDiagnose) {
  14268. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14269. Diag(Var->getLocation(), diag::note_previous_decl)
  14270. << Var->getDeclName();
  14271. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  14272. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  14273. diag::note_lambda_decl);
  14274. // FIXME: If we error out because an outer lambda can not implicitly
  14275. // capture a variable that an inner lambda explicitly captures, we
  14276. // should have the inner lambda do the explicit capture - because
  14277. // it makes for cleaner diagnostics later. This would purely be done
  14278. // so that the diagnostic does not misleadingly claim that a variable
  14279. // can not be captured by a lambda implicitly even though it is captured
  14280. // explicitly. Suggestion:
  14281. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  14282. // at the function head
  14283. // - cache the StartingDeclContext - this must be a lambda
  14284. // - captureInLambda in the innermost lambda the variable.
  14285. }
  14286. return true;
  14287. }
  14288. FunctionScopesIndex--;
  14289. DC = ParentDC;
  14290. Explicit = false;
  14291. } while (!VarDC->Equals(DC));
  14292. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  14293. // computing the type of the capture at each step, checking type-specific
  14294. // requirements, and adding captures if requested.
  14295. // If the variable had already been captured previously, we start capturing
  14296. // at the lambda nested within that one.
  14297. bool Invalid = false;
  14298. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  14299. ++I) {
  14300. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  14301. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  14302. // certain types of variables (unnamed, variably modified types etc.)
  14303. // so check for eligibility.
  14304. if (!Invalid)
  14305. Invalid =
  14306. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  14307. // After encountering an error, if we're actually supposed to capture, keep
  14308. // capturing in nested contexts to suppress any follow-on diagnostics.
  14309. if (Invalid && !BuildAndDiagnose)
  14310. return true;
  14311. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  14312. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14313. DeclRefType, Nested, *this, Invalid);
  14314. Nested = true;
  14315. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14316. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  14317. CaptureType, DeclRefType, Nested,
  14318. *this, Invalid);
  14319. Nested = true;
  14320. } else {
  14321. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14322. Invalid =
  14323. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14324. DeclRefType, Nested, Kind, EllipsisLoc,
  14325. /*IsTopScope*/ I == N - 1, *this, Invalid);
  14326. Nested = true;
  14327. }
  14328. if (Invalid && !BuildAndDiagnose)
  14329. return true;
  14330. }
  14331. return Invalid;
  14332. }
  14333. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  14334. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  14335. QualType CaptureType;
  14336. QualType DeclRefType;
  14337. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  14338. /*BuildAndDiagnose=*/true, CaptureType,
  14339. DeclRefType, nullptr);
  14340. }
  14341. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  14342. QualType CaptureType;
  14343. QualType DeclRefType;
  14344. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14345. /*BuildAndDiagnose=*/false, CaptureType,
  14346. DeclRefType, nullptr);
  14347. }
  14348. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  14349. QualType CaptureType;
  14350. QualType DeclRefType;
  14351. // Determine whether we can capture this variable.
  14352. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14353. /*BuildAndDiagnose=*/false, CaptureType,
  14354. DeclRefType, nullptr))
  14355. return QualType();
  14356. return DeclRefType;
  14357. }
  14358. namespace {
  14359. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  14360. // The produced TemplateArgumentListInfo* points to data stored within this
  14361. // object, so should only be used in contexts where the pointer will not be
  14362. // used after the CopiedTemplateArgs object is destroyed.
  14363. class CopiedTemplateArgs {
  14364. bool HasArgs;
  14365. TemplateArgumentListInfo TemplateArgStorage;
  14366. public:
  14367. template<typename RefExpr>
  14368. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  14369. if (HasArgs)
  14370. E->copyTemplateArgumentsInto(TemplateArgStorage);
  14371. }
  14372. operator TemplateArgumentListInfo*()
  14373. #ifdef __has_cpp_attribute
  14374. #if __has_cpp_attribute(clang::lifetimebound)
  14375. [[clang::lifetimebound]]
  14376. #endif
  14377. #endif
  14378. {
  14379. return HasArgs ? &TemplateArgStorage : nullptr;
  14380. }
  14381. };
  14382. }
  14383. /// Walk the set of potential results of an expression and mark them all as
  14384. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  14385. ///
  14386. /// \return A new expression if we found any potential results, ExprEmpty() if
  14387. /// not, and ExprError() if we diagnosed an error.
  14388. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  14389. NonOdrUseReason NOUR) {
  14390. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  14391. // an object that satisfies the requirements for appearing in a
  14392. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  14393. // is immediately applied." This function handles the lvalue-to-rvalue
  14394. // conversion part.
  14395. //
  14396. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  14397. // transform it into the relevant kind of non-odr-use node and rebuild the
  14398. // tree of nodes leading to it.
  14399. //
  14400. // This is a mini-TreeTransform that only transforms a restricted subset of
  14401. // nodes (and only certain operands of them).
  14402. // Rebuild a subexpression.
  14403. auto Rebuild = [&](Expr *Sub) {
  14404. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  14405. };
  14406. // Check whether a potential result satisfies the requirements of NOUR.
  14407. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  14408. // Any entity other than a VarDecl is always odr-used whenever it's named
  14409. // in a potentially-evaluated expression.
  14410. auto *VD = dyn_cast<VarDecl>(D);
  14411. if (!VD)
  14412. return true;
  14413. // C++2a [basic.def.odr]p4:
  14414. // A variable x whose name appears as a potentially-evalauted expression
  14415. // e is odr-used by e unless
  14416. // -- x is a reference that is usable in constant expressions, or
  14417. // -- x is a variable of non-reference type that is usable in constant
  14418. // expressions and has no mutable subobjects, and e is an element of
  14419. // the set of potential results of an expression of
  14420. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14421. // conversion is applied, or
  14422. // -- x is a variable of non-reference type, and e is an element of the
  14423. // set of potential results of a discarded-value expression to which
  14424. // the lvalue-to-rvalue conversion is not applied
  14425. //
  14426. // We check the first bullet and the "potentially-evaluated" condition in
  14427. // BuildDeclRefExpr. We check the type requirements in the second bullet
  14428. // in CheckLValueToRValueConversionOperand below.
  14429. switch (NOUR) {
  14430. case NOUR_None:
  14431. case NOUR_Unevaluated:
  14432. llvm_unreachable("unexpected non-odr-use-reason");
  14433. case NOUR_Constant:
  14434. // Constant references were handled when they were built.
  14435. if (VD->getType()->isReferenceType())
  14436. return true;
  14437. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  14438. if (RD->hasMutableFields())
  14439. return true;
  14440. if (!VD->isUsableInConstantExpressions(S.Context))
  14441. return true;
  14442. break;
  14443. case NOUR_Discarded:
  14444. if (VD->getType()->isReferenceType())
  14445. return true;
  14446. break;
  14447. }
  14448. return false;
  14449. };
  14450. // Mark that this expression does not constitute an odr-use.
  14451. auto MarkNotOdrUsed = [&] {
  14452. S.MaybeODRUseExprs.erase(E);
  14453. if (LambdaScopeInfo *LSI = S.getCurLambda())
  14454. LSI->markVariableExprAsNonODRUsed(E);
  14455. };
  14456. // C++2a [basic.def.odr]p2:
  14457. // The set of potential results of an expression e is defined as follows:
  14458. switch (E->getStmtClass()) {
  14459. // -- If e is an id-expression, ...
  14460. case Expr::DeclRefExprClass: {
  14461. auto *DRE = cast<DeclRefExpr>(E);
  14462. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  14463. break;
  14464. // Rebuild as a non-odr-use DeclRefExpr.
  14465. MarkNotOdrUsed();
  14466. return DeclRefExpr::Create(
  14467. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  14468. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  14469. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  14470. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  14471. }
  14472. case Expr::FunctionParmPackExprClass: {
  14473. auto *FPPE = cast<FunctionParmPackExpr>(E);
  14474. // If any of the declarations in the pack is odr-used, then the expression
  14475. // as a whole constitutes an odr-use.
  14476. for (VarDecl *D : *FPPE)
  14477. if (IsPotentialResultOdrUsed(D))
  14478. return ExprEmpty();
  14479. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  14480. // nothing cares about whether we marked this as an odr-use, but it might
  14481. // be useful for non-compiler tools.
  14482. MarkNotOdrUsed();
  14483. break;
  14484. }
  14485. // -- If e is a subscripting operation with an array operand...
  14486. case Expr::ArraySubscriptExprClass: {
  14487. auto *ASE = cast<ArraySubscriptExpr>(E);
  14488. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  14489. if (!OldBase->getType()->isArrayType())
  14490. break;
  14491. ExprResult Base = Rebuild(OldBase);
  14492. if (!Base.isUsable())
  14493. return Base;
  14494. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  14495. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  14496. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  14497. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  14498. ASE->getRBracketLoc());
  14499. }
  14500. case Expr::MemberExprClass: {
  14501. auto *ME = cast<MemberExpr>(E);
  14502. // -- If e is a class member access expression [...] naming a non-static
  14503. // data member...
  14504. if (isa<FieldDecl>(ME->getMemberDecl())) {
  14505. ExprResult Base = Rebuild(ME->getBase());
  14506. if (!Base.isUsable())
  14507. return Base;
  14508. return MemberExpr::Create(
  14509. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  14510. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  14511. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  14512. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  14513. ME->getObjectKind(), ME->isNonOdrUse());
  14514. }
  14515. if (ME->getMemberDecl()->isCXXInstanceMember())
  14516. break;
  14517. // -- If e is a class member access expression naming a static data member,
  14518. // ...
  14519. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  14520. break;
  14521. // Rebuild as a non-odr-use MemberExpr.
  14522. MarkNotOdrUsed();
  14523. return MemberExpr::Create(
  14524. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  14525. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  14526. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  14527. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  14528. return ExprEmpty();
  14529. }
  14530. case Expr::BinaryOperatorClass: {
  14531. auto *BO = cast<BinaryOperator>(E);
  14532. Expr *LHS = BO->getLHS();
  14533. Expr *RHS = BO->getRHS();
  14534. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  14535. if (BO->getOpcode() == BO_PtrMemD) {
  14536. ExprResult Sub = Rebuild(LHS);
  14537. if (!Sub.isUsable())
  14538. return Sub;
  14539. LHS = Sub.get();
  14540. // -- If e is a comma expression, ...
  14541. } else if (BO->getOpcode() == BO_Comma) {
  14542. ExprResult Sub = Rebuild(RHS);
  14543. if (!Sub.isUsable())
  14544. return Sub;
  14545. RHS = Sub.get();
  14546. } else {
  14547. break;
  14548. }
  14549. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  14550. LHS, RHS);
  14551. }
  14552. // -- If e has the form (e1)...
  14553. case Expr::ParenExprClass: {
  14554. auto *PE = cast<ParenExpr>(E);
  14555. ExprResult Sub = Rebuild(PE->getSubExpr());
  14556. if (!Sub.isUsable())
  14557. return Sub;
  14558. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  14559. }
  14560. // -- If e is a glvalue conditional expression, ...
  14561. // We don't apply this to a binary conditional operator. FIXME: Should we?
  14562. case Expr::ConditionalOperatorClass: {
  14563. auto *CO = cast<ConditionalOperator>(E);
  14564. ExprResult LHS = Rebuild(CO->getLHS());
  14565. if (LHS.isInvalid())
  14566. return ExprError();
  14567. ExprResult RHS = Rebuild(CO->getRHS());
  14568. if (RHS.isInvalid())
  14569. return ExprError();
  14570. if (!LHS.isUsable() && !RHS.isUsable())
  14571. return ExprEmpty();
  14572. if (!LHS.isUsable())
  14573. LHS = CO->getLHS();
  14574. if (!RHS.isUsable())
  14575. RHS = CO->getRHS();
  14576. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  14577. CO->getCond(), LHS.get(), RHS.get());
  14578. }
  14579. // [Clang extension]
  14580. // -- If e has the form __extension__ e1...
  14581. case Expr::UnaryOperatorClass: {
  14582. auto *UO = cast<UnaryOperator>(E);
  14583. if (UO->getOpcode() != UO_Extension)
  14584. break;
  14585. ExprResult Sub = Rebuild(UO->getSubExpr());
  14586. if (!Sub.isUsable())
  14587. return Sub;
  14588. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  14589. Sub.get());
  14590. }
  14591. // [Clang extension]
  14592. // -- If e has the form _Generic(...), the set of potential results is the
  14593. // union of the sets of potential results of the associated expressions.
  14594. case Expr::GenericSelectionExprClass: {
  14595. auto *GSE = cast<GenericSelectionExpr>(E);
  14596. SmallVector<Expr *, 4> AssocExprs;
  14597. bool AnyChanged = false;
  14598. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  14599. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  14600. if (AssocExpr.isInvalid())
  14601. return ExprError();
  14602. if (AssocExpr.isUsable()) {
  14603. AssocExprs.push_back(AssocExpr.get());
  14604. AnyChanged = true;
  14605. } else {
  14606. AssocExprs.push_back(OrigAssocExpr);
  14607. }
  14608. }
  14609. return AnyChanged ? S.CreateGenericSelectionExpr(
  14610. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  14611. GSE->getRParenLoc(), GSE->getControllingExpr(),
  14612. GSE->getAssocTypeSourceInfos(), AssocExprs)
  14613. : ExprEmpty();
  14614. }
  14615. // [Clang extension]
  14616. // -- If e has the form __builtin_choose_expr(...), the set of potential
  14617. // results is the union of the sets of potential results of the
  14618. // second and third subexpressions.
  14619. case Expr::ChooseExprClass: {
  14620. auto *CE = cast<ChooseExpr>(E);
  14621. ExprResult LHS = Rebuild(CE->getLHS());
  14622. if (LHS.isInvalid())
  14623. return ExprError();
  14624. ExprResult RHS = Rebuild(CE->getLHS());
  14625. if (RHS.isInvalid())
  14626. return ExprError();
  14627. if (!LHS.get() && !RHS.get())
  14628. return ExprEmpty();
  14629. if (!LHS.isUsable())
  14630. LHS = CE->getLHS();
  14631. if (!RHS.isUsable())
  14632. RHS = CE->getRHS();
  14633. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  14634. RHS.get(), CE->getRParenLoc());
  14635. }
  14636. // Step through non-syntactic nodes.
  14637. case Expr::ConstantExprClass: {
  14638. auto *CE = cast<ConstantExpr>(E);
  14639. ExprResult Sub = Rebuild(CE->getSubExpr());
  14640. if (!Sub.isUsable())
  14641. return Sub;
  14642. return ConstantExpr::Create(S.Context, Sub.get());
  14643. }
  14644. // We could mostly rely on the recursive rebuilding to rebuild implicit
  14645. // casts, but not at the top level, so rebuild them here.
  14646. case Expr::ImplicitCastExprClass: {
  14647. auto *ICE = cast<ImplicitCastExpr>(E);
  14648. // Only step through the narrow set of cast kinds we expect to encounter.
  14649. // Anything else suggests we've left the region in which potential results
  14650. // can be found.
  14651. switch (ICE->getCastKind()) {
  14652. case CK_NoOp:
  14653. case CK_DerivedToBase:
  14654. case CK_UncheckedDerivedToBase: {
  14655. ExprResult Sub = Rebuild(ICE->getSubExpr());
  14656. if (!Sub.isUsable())
  14657. return Sub;
  14658. CXXCastPath Path(ICE->path());
  14659. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  14660. ICE->getValueKind(), &Path);
  14661. }
  14662. default:
  14663. break;
  14664. }
  14665. break;
  14666. }
  14667. default:
  14668. break;
  14669. }
  14670. // Can't traverse through this node. Nothing to do.
  14671. return ExprEmpty();
  14672. }
  14673. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  14674. // Check whether the operand is or contains an object of non-trivial C union
  14675. // type.
  14676. if (E->getType().isVolatileQualified() &&
  14677. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  14678. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  14679. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  14680. Sema::NTCUC_LValueToRValueVolatile,
  14681. NTCUK_Destruct|NTCUK_Copy);
  14682. // C++2a [basic.def.odr]p4:
  14683. // [...] an expression of non-volatile-qualified non-class type to which
  14684. // the lvalue-to-rvalue conversion is applied [...]
  14685. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  14686. return E;
  14687. ExprResult Result =
  14688. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  14689. if (Result.isInvalid())
  14690. return ExprError();
  14691. return Result.get() ? Result : E;
  14692. }
  14693. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  14694. Res = CorrectDelayedTyposInExpr(Res);
  14695. if (!Res.isUsable())
  14696. return Res;
  14697. // If a constant-expression is a reference to a variable where we delay
  14698. // deciding whether it is an odr-use, just assume we will apply the
  14699. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  14700. // (a non-type template argument), we have special handling anyway.
  14701. return CheckLValueToRValueConversionOperand(Res.get());
  14702. }
  14703. void Sema::CleanupVarDeclMarking() {
  14704. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  14705. // call.
  14706. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  14707. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  14708. for (Expr *E : LocalMaybeODRUseExprs) {
  14709. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  14710. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  14711. DRE->getLocation(), *this);
  14712. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  14713. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  14714. *this);
  14715. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  14716. for (VarDecl *VD : *FP)
  14717. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  14718. } else {
  14719. llvm_unreachable("Unexpected expression");
  14720. }
  14721. }
  14722. assert(MaybeODRUseExprs.empty() &&
  14723. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  14724. }
  14725. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  14726. VarDecl *Var, Expr *E) {
  14727. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  14728. isa<FunctionParmPackExpr>(E)) &&
  14729. "Invalid Expr argument to DoMarkVarDeclReferenced");
  14730. Var->setReferenced();
  14731. if (Var->isInvalidDecl())
  14732. return;
  14733. auto *MSI = Var->getMemberSpecializationInfo();
  14734. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  14735. : Var->getTemplateSpecializationKind();
  14736. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  14737. bool UsableInConstantExpr =
  14738. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  14739. // C++20 [expr.const]p12:
  14740. // A variable [...] is needed for constant evaluation if it is [...] a
  14741. // variable whose name appears as a potentially constant evaluated
  14742. // expression that is either a contexpr variable or is of non-volatile
  14743. // const-qualified integral type or of reference type
  14744. bool NeededForConstantEvaluation =
  14745. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  14746. bool NeedDefinition =
  14747. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  14748. VarTemplateSpecializationDecl *VarSpec =
  14749. dyn_cast<VarTemplateSpecializationDecl>(Var);
  14750. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  14751. "Can't instantiate a partial template specialization.");
  14752. // If this might be a member specialization of a static data member, check
  14753. // the specialization is visible. We already did the checks for variable
  14754. // template specializations when we created them.
  14755. if (NeedDefinition && TSK != TSK_Undeclared &&
  14756. !isa<VarTemplateSpecializationDecl>(Var))
  14757. SemaRef.checkSpecializationVisibility(Loc, Var);
  14758. // Perform implicit instantiation of static data members, static data member
  14759. // templates of class templates, and variable template specializations. Delay
  14760. // instantiations of variable templates, except for those that could be used
  14761. // in a constant expression.
  14762. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  14763. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  14764. // instantiation declaration if a variable is usable in a constant
  14765. // expression (among other cases).
  14766. bool TryInstantiating =
  14767. TSK == TSK_ImplicitInstantiation ||
  14768. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  14769. if (TryInstantiating) {
  14770. SourceLocation PointOfInstantiation =
  14771. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  14772. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  14773. if (FirstInstantiation) {
  14774. PointOfInstantiation = Loc;
  14775. if (MSI)
  14776. MSI->setPointOfInstantiation(PointOfInstantiation);
  14777. else
  14778. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  14779. }
  14780. bool InstantiationDependent = false;
  14781. bool IsNonDependent =
  14782. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  14783. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  14784. : true;
  14785. // Do not instantiate specializations that are still type-dependent.
  14786. if (IsNonDependent) {
  14787. if (UsableInConstantExpr) {
  14788. // Do not defer instantiations of variables that could be used in a
  14789. // constant expression.
  14790. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  14791. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  14792. });
  14793. } else if (FirstInstantiation ||
  14794. isa<VarTemplateSpecializationDecl>(Var)) {
  14795. // FIXME: For a specialization of a variable template, we don't
  14796. // distinguish between "declaration and type implicitly instantiated"
  14797. // and "implicit instantiation of definition requested", so we have
  14798. // no direct way to avoid enqueueing the pending instantiation
  14799. // multiple times.
  14800. SemaRef.PendingInstantiations
  14801. .push_back(std::make_pair(Var, PointOfInstantiation));
  14802. }
  14803. }
  14804. }
  14805. }
  14806. // C++2a [basic.def.odr]p4:
  14807. // A variable x whose name appears as a potentially-evaluated expression e
  14808. // is odr-used by e unless
  14809. // -- x is a reference that is usable in constant expressions
  14810. // -- x is a variable of non-reference type that is usable in constant
  14811. // expressions and has no mutable subobjects [FIXME], and e is an
  14812. // element of the set of potential results of an expression of
  14813. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14814. // conversion is applied
  14815. // -- x is a variable of non-reference type, and e is an element of the set
  14816. // of potential results of a discarded-value expression to which the
  14817. // lvalue-to-rvalue conversion is not applied [FIXME]
  14818. //
  14819. // We check the first part of the second bullet here, and
  14820. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  14821. // FIXME: To get the third bullet right, we need to delay this even for
  14822. // variables that are not usable in constant expressions.
  14823. // If we already know this isn't an odr-use, there's nothing more to do.
  14824. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  14825. if (DRE->isNonOdrUse())
  14826. return;
  14827. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  14828. if (ME->isNonOdrUse())
  14829. return;
  14830. switch (OdrUse) {
  14831. case OdrUseContext::None:
  14832. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  14833. "missing non-odr-use marking for unevaluated decl ref");
  14834. break;
  14835. case OdrUseContext::FormallyOdrUsed:
  14836. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14837. // behavior.
  14838. break;
  14839. case OdrUseContext::Used:
  14840. // If we might later find that this expression isn't actually an odr-use,
  14841. // delay the marking.
  14842. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  14843. SemaRef.MaybeODRUseExprs.insert(E);
  14844. else
  14845. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  14846. break;
  14847. case OdrUseContext::Dependent:
  14848. // If this is a dependent context, we don't need to mark variables as
  14849. // odr-used, but we may still need to track them for lambda capture.
  14850. // FIXME: Do we also need to do this inside dependent typeid expressions
  14851. // (which are modeled as unevaluated at this point)?
  14852. const bool RefersToEnclosingScope =
  14853. (SemaRef.CurContext != Var->getDeclContext() &&
  14854. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14855. if (RefersToEnclosingScope) {
  14856. LambdaScopeInfo *const LSI =
  14857. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14858. if (LSI && (!LSI->CallOperator ||
  14859. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14860. // If a variable could potentially be odr-used, defer marking it so
  14861. // until we finish analyzing the full expression for any
  14862. // lvalue-to-rvalue
  14863. // or discarded value conversions that would obviate odr-use.
  14864. // Add it to the list of potential captures that will be analyzed
  14865. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14866. // unless the variable is a reference that was initialized by a constant
  14867. // expression (this will never need to be captured or odr-used).
  14868. //
  14869. // FIXME: We can simplify this a lot after implementing P0588R1.
  14870. assert(E && "Capture variable should be used in an expression.");
  14871. if (!Var->getType()->isReferenceType() ||
  14872. !Var->isUsableInConstantExpressions(SemaRef.Context))
  14873. LSI->addPotentialCapture(E->IgnoreParens());
  14874. }
  14875. }
  14876. break;
  14877. }
  14878. }
  14879. /// Mark a variable referenced, and check whether it is odr-used
  14880. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14881. /// used directly for normal expressions referring to VarDecl.
  14882. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14883. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14884. }
  14885. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14886. Decl *D, Expr *E, bool MightBeOdrUse) {
  14887. if (SemaRef.isInOpenMPDeclareTargetContext())
  14888. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14889. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14890. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14891. return;
  14892. }
  14893. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14894. // If this is a call to a method via a cast, also mark the method in the
  14895. // derived class used in case codegen can devirtualize the call.
  14896. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14897. if (!ME)
  14898. return;
  14899. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14900. if (!MD)
  14901. return;
  14902. // Only attempt to devirtualize if this is truly a virtual call.
  14903. bool IsVirtualCall = MD->isVirtual() &&
  14904. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14905. if (!IsVirtualCall)
  14906. return;
  14907. // If it's possible to devirtualize the call, mark the called function
  14908. // referenced.
  14909. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14910. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14911. if (DM)
  14912. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14913. }
  14914. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14915. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14916. // TODO: update this with DR# once a defect report is filed.
  14917. // C++11 defect. The address of a pure member should not be an ODR use, even
  14918. // if it's a qualified reference.
  14919. bool OdrUse = true;
  14920. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14921. if (Method->isVirtual() &&
  14922. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14923. OdrUse = false;
  14924. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14925. }
  14926. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14927. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14928. // C++11 [basic.def.odr]p2:
  14929. // A non-overloaded function whose name appears as a potentially-evaluated
  14930. // expression or a member of a set of candidate functions, if selected by
  14931. // overload resolution when referred to from a potentially-evaluated
  14932. // expression, is odr-used, unless it is a pure virtual function and its
  14933. // name is not explicitly qualified.
  14934. bool MightBeOdrUse = true;
  14935. if (E->performsVirtualDispatch(getLangOpts())) {
  14936. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14937. if (Method->isPure())
  14938. MightBeOdrUse = false;
  14939. }
  14940. SourceLocation Loc =
  14941. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14942. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14943. }
  14944. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14945. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14946. for (VarDecl *VD : *E)
  14947. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14948. }
  14949. /// Perform marking for a reference to an arbitrary declaration. It
  14950. /// marks the declaration referenced, and performs odr-use checking for
  14951. /// functions and variables. This method should not be used when building a
  14952. /// normal expression which refers to a variable.
  14953. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14954. bool MightBeOdrUse) {
  14955. if (MightBeOdrUse) {
  14956. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14957. MarkVariableReferenced(Loc, VD);
  14958. return;
  14959. }
  14960. }
  14961. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14962. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14963. return;
  14964. }
  14965. D->setReferenced();
  14966. }
  14967. namespace {
  14968. // Mark all of the declarations used by a type as referenced.
  14969. // FIXME: Not fully implemented yet! We need to have a better understanding
  14970. // of when we're entering a context we should not recurse into.
  14971. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14972. // TreeTransforms rebuilding the type in a new context. Rather than
  14973. // duplicating the TreeTransform logic, we should consider reusing it here.
  14974. // Currently that causes problems when rebuilding LambdaExprs.
  14975. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14976. Sema &S;
  14977. SourceLocation Loc;
  14978. public:
  14979. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14980. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14981. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14982. };
  14983. }
  14984. bool MarkReferencedDecls::TraverseTemplateArgument(
  14985. const TemplateArgument &Arg) {
  14986. {
  14987. // A non-type template argument is a constant-evaluated context.
  14988. EnterExpressionEvaluationContext Evaluated(
  14989. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14990. if (Arg.getKind() == TemplateArgument::Declaration) {
  14991. if (Decl *D = Arg.getAsDecl())
  14992. S.MarkAnyDeclReferenced(Loc, D, true);
  14993. } else if (Arg.getKind() == TemplateArgument::Expression) {
  14994. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  14995. }
  14996. }
  14997. return Inherited::TraverseTemplateArgument(Arg);
  14998. }
  14999. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  15000. MarkReferencedDecls Marker(*this, Loc);
  15001. Marker.TraverseType(T);
  15002. }
  15003. namespace {
  15004. /// Helper class that marks all of the declarations referenced by
  15005. /// potentially-evaluated subexpressions as "referenced".
  15006. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  15007. Sema &S;
  15008. bool SkipLocalVariables;
  15009. public:
  15010. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  15011. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  15012. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  15013. void VisitDeclRefExpr(DeclRefExpr *E) {
  15014. // If we were asked not to visit local variables, don't.
  15015. if (SkipLocalVariables) {
  15016. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  15017. if (VD->hasLocalStorage())
  15018. return;
  15019. }
  15020. S.MarkDeclRefReferenced(E);
  15021. }
  15022. void VisitMemberExpr(MemberExpr *E) {
  15023. S.MarkMemberReferenced(E);
  15024. Inherited::VisitMemberExpr(E);
  15025. }
  15026. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  15027. S.MarkFunctionReferenced(
  15028. E->getBeginLoc(),
  15029. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  15030. Visit(E->getSubExpr());
  15031. }
  15032. void VisitCXXNewExpr(CXXNewExpr *E) {
  15033. if (E->getOperatorNew())
  15034. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  15035. if (E->getOperatorDelete())
  15036. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  15037. Inherited::VisitCXXNewExpr(E);
  15038. }
  15039. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  15040. if (E->getOperatorDelete())
  15041. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  15042. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  15043. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  15044. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  15045. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  15046. }
  15047. Inherited::VisitCXXDeleteExpr(E);
  15048. }
  15049. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  15050. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  15051. Inherited::VisitCXXConstructExpr(E);
  15052. }
  15053. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  15054. Visit(E->getExpr());
  15055. }
  15056. };
  15057. }
  15058. /// Mark any declarations that appear within this expression or any
  15059. /// potentially-evaluated subexpressions as "referenced".
  15060. ///
  15061. /// \param SkipLocalVariables If true, don't mark local variables as
  15062. /// 'referenced'.
  15063. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  15064. bool SkipLocalVariables) {
  15065. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  15066. }
  15067. /// Emit a diagnostic that describes an effect on the run-time behavior
  15068. /// of the program being compiled.
  15069. ///
  15070. /// This routine emits the given diagnostic when the code currently being
  15071. /// type-checked is "potentially evaluated", meaning that there is a
  15072. /// possibility that the code will actually be executable. Code in sizeof()
  15073. /// expressions, code used only during overload resolution, etc., are not
  15074. /// potentially evaluated. This routine will suppress such diagnostics or,
  15075. /// in the absolutely nutty case of potentially potentially evaluated
  15076. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  15077. /// later.
  15078. ///
  15079. /// This routine should be used for all diagnostics that describe the run-time
  15080. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  15081. /// Failure to do so will likely result in spurious diagnostics or failures
  15082. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  15083. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  15084. const PartialDiagnostic &PD) {
  15085. switch (ExprEvalContexts.back().Context) {
  15086. case ExpressionEvaluationContext::Unevaluated:
  15087. case ExpressionEvaluationContext::UnevaluatedList:
  15088. case ExpressionEvaluationContext::UnevaluatedAbstract:
  15089. case ExpressionEvaluationContext::DiscardedStatement:
  15090. // The argument will never be evaluated, so don't complain.
  15091. break;
  15092. case ExpressionEvaluationContext::ConstantEvaluated:
  15093. // Relevant diagnostics should be produced by constant evaluation.
  15094. break;
  15095. case ExpressionEvaluationContext::PotentiallyEvaluated:
  15096. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  15097. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  15098. FunctionScopes.back()->PossiblyUnreachableDiags.
  15099. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  15100. return true;
  15101. }
  15102. // The initializer of a constexpr variable or of the first declaration of a
  15103. // static data member is not syntactically a constant evaluated constant,
  15104. // but nonetheless is always required to be a constant expression, so we
  15105. // can skip diagnosing.
  15106. // FIXME: Using the mangling context here is a hack.
  15107. if (auto *VD = dyn_cast_or_null<VarDecl>(
  15108. ExprEvalContexts.back().ManglingContextDecl)) {
  15109. if (VD->isConstexpr() ||
  15110. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  15111. break;
  15112. // FIXME: For any other kind of variable, we should build a CFG for its
  15113. // initializer and check whether the context in question is reachable.
  15114. }
  15115. Diag(Loc, PD);
  15116. return true;
  15117. }
  15118. return false;
  15119. }
  15120. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  15121. const PartialDiagnostic &PD) {
  15122. return DiagRuntimeBehavior(
  15123. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  15124. }
  15125. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  15126. CallExpr *CE, FunctionDecl *FD) {
  15127. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  15128. return false;
  15129. // If we're inside a decltype's expression, don't check for a valid return
  15130. // type or construct temporaries until we know whether this is the last call.
  15131. if (ExprEvalContexts.back().ExprContext ==
  15132. ExpressionEvaluationContextRecord::EK_Decltype) {
  15133. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  15134. return false;
  15135. }
  15136. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  15137. FunctionDecl *FD;
  15138. CallExpr *CE;
  15139. public:
  15140. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  15141. : FD(FD), CE(CE) { }
  15142. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  15143. if (!FD) {
  15144. S.Diag(Loc, diag::err_call_incomplete_return)
  15145. << T << CE->getSourceRange();
  15146. return;
  15147. }
  15148. S.Diag(Loc, diag::err_call_function_incomplete_return)
  15149. << CE->getSourceRange() << FD->getDeclName() << T;
  15150. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  15151. << FD->getDeclName();
  15152. }
  15153. } Diagnoser(FD, CE);
  15154. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  15155. return true;
  15156. return false;
  15157. }
  15158. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  15159. // will prevent this condition from triggering, which is what we want.
  15160. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  15161. SourceLocation Loc;
  15162. unsigned diagnostic = diag::warn_condition_is_assignment;
  15163. bool IsOrAssign = false;
  15164. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  15165. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  15166. return;
  15167. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  15168. // Greylist some idioms by putting them into a warning subcategory.
  15169. if (ObjCMessageExpr *ME
  15170. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  15171. Selector Sel = ME->getSelector();
  15172. // self = [<foo> init...]
  15173. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  15174. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15175. // <foo> = [<bar> nextObject]
  15176. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  15177. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15178. }
  15179. Loc = Op->getOperatorLoc();
  15180. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  15181. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  15182. return;
  15183. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  15184. Loc = Op->getOperatorLoc();
  15185. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  15186. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  15187. else {
  15188. // Not an assignment.
  15189. return;
  15190. }
  15191. Diag(Loc, diagnostic) << E->getSourceRange();
  15192. SourceLocation Open = E->getBeginLoc();
  15193. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  15194. Diag(Loc, diag::note_condition_assign_silence)
  15195. << FixItHint::CreateInsertion(Open, "(")
  15196. << FixItHint::CreateInsertion(Close, ")");
  15197. if (IsOrAssign)
  15198. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  15199. << FixItHint::CreateReplacement(Loc, "!=");
  15200. else
  15201. Diag(Loc, diag::note_condition_assign_to_comparison)
  15202. << FixItHint::CreateReplacement(Loc, "==");
  15203. }
  15204. /// Redundant parentheses over an equality comparison can indicate
  15205. /// that the user intended an assignment used as condition.
  15206. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  15207. // Don't warn if the parens came from a macro.
  15208. SourceLocation parenLoc = ParenE->getBeginLoc();
  15209. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  15210. return;
  15211. // Don't warn for dependent expressions.
  15212. if (ParenE->isTypeDependent())
  15213. return;
  15214. Expr *E = ParenE->IgnoreParens();
  15215. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  15216. if (opE->getOpcode() == BO_EQ &&
  15217. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  15218. == Expr::MLV_Valid) {
  15219. SourceLocation Loc = opE->getOperatorLoc();
  15220. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  15221. SourceRange ParenERange = ParenE->getSourceRange();
  15222. Diag(Loc, diag::note_equality_comparison_silence)
  15223. << FixItHint::CreateRemoval(ParenERange.getBegin())
  15224. << FixItHint::CreateRemoval(ParenERange.getEnd());
  15225. Diag(Loc, diag::note_equality_comparison_to_assign)
  15226. << FixItHint::CreateReplacement(Loc, "=");
  15227. }
  15228. }
  15229. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  15230. bool IsConstexpr) {
  15231. DiagnoseAssignmentAsCondition(E);
  15232. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  15233. DiagnoseEqualityWithExtraParens(parenE);
  15234. ExprResult result = CheckPlaceholderExpr(E);
  15235. if (result.isInvalid()) return ExprError();
  15236. E = result.get();
  15237. if (!E->isTypeDependent()) {
  15238. if (getLangOpts().CPlusPlus)
  15239. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  15240. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  15241. if (ERes.isInvalid())
  15242. return ExprError();
  15243. E = ERes.get();
  15244. QualType T = E->getType();
  15245. if (!T->isScalarType()) { // C99 6.8.4.1p1
  15246. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  15247. << T << E->getSourceRange();
  15248. return ExprError();
  15249. }
  15250. CheckBoolLikeConversion(E, Loc);
  15251. }
  15252. return E;
  15253. }
  15254. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  15255. Expr *SubExpr, ConditionKind CK) {
  15256. // Empty conditions are valid in for-statements.
  15257. if (!SubExpr)
  15258. return ConditionResult();
  15259. ExprResult Cond;
  15260. switch (CK) {
  15261. case ConditionKind::Boolean:
  15262. Cond = CheckBooleanCondition(Loc, SubExpr);
  15263. break;
  15264. case ConditionKind::ConstexprIf:
  15265. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  15266. break;
  15267. case ConditionKind::Switch:
  15268. Cond = CheckSwitchCondition(Loc, SubExpr);
  15269. break;
  15270. }
  15271. if (Cond.isInvalid())
  15272. return ConditionError();
  15273. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  15274. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  15275. if (!FullExpr.get())
  15276. return ConditionError();
  15277. return ConditionResult(*this, nullptr, FullExpr,
  15278. CK == ConditionKind::ConstexprIf);
  15279. }
  15280. namespace {
  15281. /// A visitor for rebuilding a call to an __unknown_any expression
  15282. /// to have an appropriate type.
  15283. struct RebuildUnknownAnyFunction
  15284. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  15285. Sema &S;
  15286. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  15287. ExprResult VisitStmt(Stmt *S) {
  15288. llvm_unreachable("unexpected statement!");
  15289. }
  15290. ExprResult VisitExpr(Expr *E) {
  15291. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  15292. << E->getSourceRange();
  15293. return ExprError();
  15294. }
  15295. /// Rebuild an expression which simply semantically wraps another
  15296. /// expression which it shares the type and value kind of.
  15297. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15298. ExprResult SubResult = Visit(E->getSubExpr());
  15299. if (SubResult.isInvalid()) return ExprError();
  15300. Expr *SubExpr = SubResult.get();
  15301. E->setSubExpr(SubExpr);
  15302. E->setType(SubExpr->getType());
  15303. E->setValueKind(SubExpr->getValueKind());
  15304. assert(E->getObjectKind() == OK_Ordinary);
  15305. return E;
  15306. }
  15307. ExprResult VisitParenExpr(ParenExpr *E) {
  15308. return rebuildSugarExpr(E);
  15309. }
  15310. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15311. return rebuildSugarExpr(E);
  15312. }
  15313. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15314. ExprResult SubResult = Visit(E->getSubExpr());
  15315. if (SubResult.isInvalid()) return ExprError();
  15316. Expr *SubExpr = SubResult.get();
  15317. E->setSubExpr(SubExpr);
  15318. E->setType(S.Context.getPointerType(SubExpr->getType()));
  15319. assert(E->getValueKind() == VK_RValue);
  15320. assert(E->getObjectKind() == OK_Ordinary);
  15321. return E;
  15322. }
  15323. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  15324. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  15325. E->setType(VD->getType());
  15326. assert(E->getValueKind() == VK_RValue);
  15327. if (S.getLangOpts().CPlusPlus &&
  15328. !(isa<CXXMethodDecl>(VD) &&
  15329. cast<CXXMethodDecl>(VD)->isInstance()))
  15330. E->setValueKind(VK_LValue);
  15331. return E;
  15332. }
  15333. ExprResult VisitMemberExpr(MemberExpr *E) {
  15334. return resolveDecl(E, E->getMemberDecl());
  15335. }
  15336. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15337. return resolveDecl(E, E->getDecl());
  15338. }
  15339. };
  15340. }
  15341. /// Given a function expression of unknown-any type, try to rebuild it
  15342. /// to have a function type.
  15343. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  15344. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  15345. if (Result.isInvalid()) return ExprError();
  15346. return S.DefaultFunctionArrayConversion(Result.get());
  15347. }
  15348. namespace {
  15349. /// A visitor for rebuilding an expression of type __unknown_anytype
  15350. /// into one which resolves the type directly on the referring
  15351. /// expression. Strict preservation of the original source
  15352. /// structure is not a goal.
  15353. struct RebuildUnknownAnyExpr
  15354. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  15355. Sema &S;
  15356. /// The current destination type.
  15357. QualType DestType;
  15358. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  15359. : S(S), DestType(CastType) {}
  15360. ExprResult VisitStmt(Stmt *S) {
  15361. llvm_unreachable("unexpected statement!");
  15362. }
  15363. ExprResult VisitExpr(Expr *E) {
  15364. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15365. << E->getSourceRange();
  15366. return ExprError();
  15367. }
  15368. ExprResult VisitCallExpr(CallExpr *E);
  15369. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  15370. /// Rebuild an expression which simply semantically wraps another
  15371. /// expression which it shares the type and value kind of.
  15372. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15373. ExprResult SubResult = Visit(E->getSubExpr());
  15374. if (SubResult.isInvalid()) return ExprError();
  15375. Expr *SubExpr = SubResult.get();
  15376. E->setSubExpr(SubExpr);
  15377. E->setType(SubExpr->getType());
  15378. E->setValueKind(SubExpr->getValueKind());
  15379. assert(E->getObjectKind() == OK_Ordinary);
  15380. return E;
  15381. }
  15382. ExprResult VisitParenExpr(ParenExpr *E) {
  15383. return rebuildSugarExpr(E);
  15384. }
  15385. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15386. return rebuildSugarExpr(E);
  15387. }
  15388. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15389. const PointerType *Ptr = DestType->getAs<PointerType>();
  15390. if (!Ptr) {
  15391. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  15392. << E->getSourceRange();
  15393. return ExprError();
  15394. }
  15395. if (isa<CallExpr>(E->getSubExpr())) {
  15396. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  15397. << E->getSourceRange();
  15398. return ExprError();
  15399. }
  15400. assert(E->getValueKind() == VK_RValue);
  15401. assert(E->getObjectKind() == OK_Ordinary);
  15402. E->setType(DestType);
  15403. // Build the sub-expression as if it were an object of the pointee type.
  15404. DestType = Ptr->getPointeeType();
  15405. ExprResult SubResult = Visit(E->getSubExpr());
  15406. if (SubResult.isInvalid()) return ExprError();
  15407. E->setSubExpr(SubResult.get());
  15408. return E;
  15409. }
  15410. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  15411. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  15412. ExprResult VisitMemberExpr(MemberExpr *E) {
  15413. return resolveDecl(E, E->getMemberDecl());
  15414. }
  15415. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15416. return resolveDecl(E, E->getDecl());
  15417. }
  15418. };
  15419. }
  15420. /// Rebuilds a call expression which yielded __unknown_anytype.
  15421. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  15422. Expr *CalleeExpr = E->getCallee();
  15423. enum FnKind {
  15424. FK_MemberFunction,
  15425. FK_FunctionPointer,
  15426. FK_BlockPointer
  15427. };
  15428. FnKind Kind;
  15429. QualType CalleeType = CalleeExpr->getType();
  15430. if (CalleeType == S.Context.BoundMemberTy) {
  15431. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  15432. Kind = FK_MemberFunction;
  15433. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  15434. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  15435. CalleeType = Ptr->getPointeeType();
  15436. Kind = FK_FunctionPointer;
  15437. } else {
  15438. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  15439. Kind = FK_BlockPointer;
  15440. }
  15441. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  15442. // Verify that this is a legal result type of a function.
  15443. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15444. unsigned diagID = diag::err_func_returning_array_function;
  15445. if (Kind == FK_BlockPointer)
  15446. diagID = diag::err_block_returning_array_function;
  15447. S.Diag(E->getExprLoc(), diagID)
  15448. << DestType->isFunctionType() << DestType;
  15449. return ExprError();
  15450. }
  15451. // Otherwise, go ahead and set DestType as the call's result.
  15452. E->setType(DestType.getNonLValueExprType(S.Context));
  15453. E->setValueKind(Expr::getValueKindForType(DestType));
  15454. assert(E->getObjectKind() == OK_Ordinary);
  15455. // Rebuild the function type, replacing the result type with DestType.
  15456. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  15457. if (Proto) {
  15458. // __unknown_anytype(...) is a special case used by the debugger when
  15459. // it has no idea what a function's signature is.
  15460. //
  15461. // We want to build this call essentially under the K&R
  15462. // unprototyped rules, but making a FunctionNoProtoType in C++
  15463. // would foul up all sorts of assumptions. However, we cannot
  15464. // simply pass all arguments as variadic arguments, nor can we
  15465. // portably just call the function under a non-variadic type; see
  15466. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  15467. // However, it turns out that in practice it is generally safe to
  15468. // call a function declared as "A foo(B,C,D);" under the prototype
  15469. // "A foo(B,C,D,...);". The only known exception is with the
  15470. // Windows ABI, where any variadic function is implicitly cdecl
  15471. // regardless of its normal CC. Therefore we change the parameter
  15472. // types to match the types of the arguments.
  15473. //
  15474. // This is a hack, but it is far superior to moving the
  15475. // corresponding target-specific code from IR-gen to Sema/AST.
  15476. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  15477. SmallVector<QualType, 8> ArgTypes;
  15478. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  15479. ArgTypes.reserve(E->getNumArgs());
  15480. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  15481. Expr *Arg = E->getArg(i);
  15482. QualType ArgType = Arg->getType();
  15483. if (E->isLValue()) {
  15484. ArgType = S.Context.getLValueReferenceType(ArgType);
  15485. } else if (E->isXValue()) {
  15486. ArgType = S.Context.getRValueReferenceType(ArgType);
  15487. }
  15488. ArgTypes.push_back(ArgType);
  15489. }
  15490. ParamTypes = ArgTypes;
  15491. }
  15492. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  15493. Proto->getExtProtoInfo());
  15494. } else {
  15495. DestType = S.Context.getFunctionNoProtoType(DestType,
  15496. FnType->getExtInfo());
  15497. }
  15498. // Rebuild the appropriate pointer-to-function type.
  15499. switch (Kind) {
  15500. case FK_MemberFunction:
  15501. // Nothing to do.
  15502. break;
  15503. case FK_FunctionPointer:
  15504. DestType = S.Context.getPointerType(DestType);
  15505. break;
  15506. case FK_BlockPointer:
  15507. DestType = S.Context.getBlockPointerType(DestType);
  15508. break;
  15509. }
  15510. // Finally, we can recurse.
  15511. ExprResult CalleeResult = Visit(CalleeExpr);
  15512. if (!CalleeResult.isUsable()) return ExprError();
  15513. E->setCallee(CalleeResult.get());
  15514. // Bind a temporary if necessary.
  15515. return S.MaybeBindToTemporary(E);
  15516. }
  15517. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  15518. // Verify that this is a legal result type of a call.
  15519. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15520. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  15521. << DestType->isFunctionType() << DestType;
  15522. return ExprError();
  15523. }
  15524. // Rewrite the method result type if available.
  15525. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  15526. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  15527. Method->setReturnType(DestType);
  15528. }
  15529. // Change the type of the message.
  15530. E->setType(DestType.getNonReferenceType());
  15531. E->setValueKind(Expr::getValueKindForType(DestType));
  15532. return S.MaybeBindToTemporary(E);
  15533. }
  15534. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  15535. // The only case we should ever see here is a function-to-pointer decay.
  15536. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  15537. assert(E->getValueKind() == VK_RValue);
  15538. assert(E->getObjectKind() == OK_Ordinary);
  15539. E->setType(DestType);
  15540. // Rebuild the sub-expression as the pointee (function) type.
  15541. DestType = DestType->castAs<PointerType>()->getPointeeType();
  15542. ExprResult Result = Visit(E->getSubExpr());
  15543. if (!Result.isUsable()) return ExprError();
  15544. E->setSubExpr(Result.get());
  15545. return E;
  15546. } else if (E->getCastKind() == CK_LValueToRValue) {
  15547. assert(E->getValueKind() == VK_RValue);
  15548. assert(E->getObjectKind() == OK_Ordinary);
  15549. assert(isa<BlockPointerType>(E->getType()));
  15550. E->setType(DestType);
  15551. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  15552. DestType = S.Context.getLValueReferenceType(DestType);
  15553. ExprResult Result = Visit(E->getSubExpr());
  15554. if (!Result.isUsable()) return ExprError();
  15555. E->setSubExpr(Result.get());
  15556. return E;
  15557. } else {
  15558. llvm_unreachable("Unhandled cast type!");
  15559. }
  15560. }
  15561. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  15562. ExprValueKind ValueKind = VK_LValue;
  15563. QualType Type = DestType;
  15564. // We know how to make this work for certain kinds of decls:
  15565. // - functions
  15566. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  15567. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  15568. DestType = Ptr->getPointeeType();
  15569. ExprResult Result = resolveDecl(E, VD);
  15570. if (Result.isInvalid()) return ExprError();
  15571. return S.ImpCastExprToType(Result.get(), Type,
  15572. CK_FunctionToPointerDecay, VK_RValue);
  15573. }
  15574. if (!Type->isFunctionType()) {
  15575. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  15576. << VD << E->getSourceRange();
  15577. return ExprError();
  15578. }
  15579. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  15580. // We must match the FunctionDecl's type to the hack introduced in
  15581. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  15582. // type. See the lengthy commentary in that routine.
  15583. QualType FDT = FD->getType();
  15584. const FunctionType *FnType = FDT->castAs<FunctionType>();
  15585. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  15586. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  15587. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  15588. SourceLocation Loc = FD->getLocation();
  15589. FunctionDecl *NewFD = FunctionDecl::Create(
  15590. S.Context, FD->getDeclContext(), Loc, Loc,
  15591. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  15592. SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
  15593. /*ConstexprKind*/ CSK_unspecified);
  15594. if (FD->getQualifier())
  15595. NewFD->setQualifierInfo(FD->getQualifierLoc());
  15596. SmallVector<ParmVarDecl*, 16> Params;
  15597. for (const auto &AI : FT->param_types()) {
  15598. ParmVarDecl *Param =
  15599. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  15600. Param->setScopeInfo(0, Params.size());
  15601. Params.push_back(Param);
  15602. }
  15603. NewFD->setParams(Params);
  15604. DRE->setDecl(NewFD);
  15605. VD = DRE->getDecl();
  15606. }
  15607. }
  15608. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  15609. if (MD->isInstance()) {
  15610. ValueKind = VK_RValue;
  15611. Type = S.Context.BoundMemberTy;
  15612. }
  15613. // Function references aren't l-values in C.
  15614. if (!S.getLangOpts().CPlusPlus)
  15615. ValueKind = VK_RValue;
  15616. // - variables
  15617. } else if (isa<VarDecl>(VD)) {
  15618. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  15619. Type = RefTy->getPointeeType();
  15620. } else if (Type->isFunctionType()) {
  15621. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  15622. << VD << E->getSourceRange();
  15623. return ExprError();
  15624. }
  15625. // - nothing else
  15626. } else {
  15627. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  15628. << VD << E->getSourceRange();
  15629. return ExprError();
  15630. }
  15631. // Modifying the declaration like this is friendly to IR-gen but
  15632. // also really dangerous.
  15633. VD->setType(DestType);
  15634. E->setType(Type);
  15635. E->setValueKind(ValueKind);
  15636. return E;
  15637. }
  15638. /// Check a cast of an unknown-any type. We intentionally only
  15639. /// trigger this for C-style casts.
  15640. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  15641. Expr *CastExpr, CastKind &CastKind,
  15642. ExprValueKind &VK, CXXCastPath &Path) {
  15643. // The type we're casting to must be either void or complete.
  15644. if (!CastType->isVoidType() &&
  15645. RequireCompleteType(TypeRange.getBegin(), CastType,
  15646. diag::err_typecheck_cast_to_incomplete))
  15647. return ExprError();
  15648. // Rewrite the casted expression from scratch.
  15649. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  15650. if (!result.isUsable()) return ExprError();
  15651. CastExpr = result.get();
  15652. VK = CastExpr->getValueKind();
  15653. CastKind = CK_NoOp;
  15654. return CastExpr;
  15655. }
  15656. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  15657. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  15658. }
  15659. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  15660. Expr *arg, QualType &paramType) {
  15661. // If the syntactic form of the argument is not an explicit cast of
  15662. // any sort, just do default argument promotion.
  15663. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  15664. if (!castArg) {
  15665. ExprResult result = DefaultArgumentPromotion(arg);
  15666. if (result.isInvalid()) return ExprError();
  15667. paramType = result.get()->getType();
  15668. return result;
  15669. }
  15670. // Otherwise, use the type that was written in the explicit cast.
  15671. assert(!arg->hasPlaceholderType());
  15672. paramType = castArg->getTypeAsWritten();
  15673. // Copy-initialize a parameter of that type.
  15674. InitializedEntity entity =
  15675. InitializedEntity::InitializeParameter(Context, paramType,
  15676. /*consumed*/ false);
  15677. return PerformCopyInitialization(entity, callLoc, arg);
  15678. }
  15679. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  15680. Expr *orig = E;
  15681. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  15682. while (true) {
  15683. E = E->IgnoreParenImpCasts();
  15684. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  15685. E = call->getCallee();
  15686. diagID = diag::err_uncasted_call_of_unknown_any;
  15687. } else {
  15688. break;
  15689. }
  15690. }
  15691. SourceLocation loc;
  15692. NamedDecl *d;
  15693. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  15694. loc = ref->getLocation();
  15695. d = ref->getDecl();
  15696. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  15697. loc = mem->getMemberLoc();
  15698. d = mem->getMemberDecl();
  15699. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  15700. diagID = diag::err_uncasted_call_of_unknown_any;
  15701. loc = msg->getSelectorStartLoc();
  15702. d = msg->getMethodDecl();
  15703. if (!d) {
  15704. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  15705. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  15706. << orig->getSourceRange();
  15707. return ExprError();
  15708. }
  15709. } else {
  15710. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15711. << E->getSourceRange();
  15712. return ExprError();
  15713. }
  15714. S.Diag(loc, diagID) << d << orig->getSourceRange();
  15715. // Never recoverable.
  15716. return ExprError();
  15717. }
  15718. /// Check for operands with placeholder types and complain if found.
  15719. /// Returns ExprError() if there was an error and no recovery was possible.
  15720. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  15721. if (!getLangOpts().CPlusPlus) {
  15722. // C cannot handle TypoExpr nodes on either side of a binop because it
  15723. // doesn't handle dependent types properly, so make sure any TypoExprs have
  15724. // been dealt with before checking the operands.
  15725. ExprResult Result = CorrectDelayedTyposInExpr(E);
  15726. if (!Result.isUsable()) return ExprError();
  15727. E = Result.get();
  15728. }
  15729. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  15730. if (!placeholderType) return E;
  15731. switch (placeholderType->getKind()) {
  15732. // Overloaded expressions.
  15733. case BuiltinType::Overload: {
  15734. // Try to resolve a single function template specialization.
  15735. // This is obligatory.
  15736. ExprResult Result = E;
  15737. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  15738. return Result;
  15739. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  15740. // leaves Result unchanged on failure.
  15741. Result = E;
  15742. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  15743. return Result;
  15744. // If that failed, try to recover with a call.
  15745. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  15746. /*complain*/ true);
  15747. return Result;
  15748. }
  15749. // Bound member functions.
  15750. case BuiltinType::BoundMember: {
  15751. ExprResult result = E;
  15752. const Expr *BME = E->IgnoreParens();
  15753. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  15754. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  15755. if (isa<CXXPseudoDestructorExpr>(BME)) {
  15756. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  15757. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  15758. if (ME->getMemberNameInfo().getName().getNameKind() ==
  15759. DeclarationName::CXXDestructorName)
  15760. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  15761. }
  15762. tryToRecoverWithCall(result, PD,
  15763. /*complain*/ true);
  15764. return result;
  15765. }
  15766. // ARC unbridged casts.
  15767. case BuiltinType::ARCUnbridgedCast: {
  15768. Expr *realCast = stripARCUnbridgedCast(E);
  15769. diagnoseARCUnbridgedCast(realCast);
  15770. return realCast;
  15771. }
  15772. // Expressions of unknown type.
  15773. case BuiltinType::UnknownAny:
  15774. return diagnoseUnknownAnyExpr(*this, E);
  15775. // Pseudo-objects.
  15776. case BuiltinType::PseudoObject:
  15777. return checkPseudoObjectRValue(E);
  15778. case BuiltinType::BuiltinFn: {
  15779. // Accept __noop without parens by implicitly converting it to a call expr.
  15780. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  15781. if (DRE) {
  15782. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  15783. if (FD->getBuiltinID() == Builtin::BI__noop) {
  15784. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  15785. CK_BuiltinFnToFnPtr)
  15786. .get();
  15787. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  15788. VK_RValue, SourceLocation());
  15789. }
  15790. }
  15791. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  15792. return ExprError();
  15793. }
  15794. // Expressions of unknown type.
  15795. case BuiltinType::OMPArraySection:
  15796. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15797. return ExprError();
  15798. // Everything else should be impossible.
  15799. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15800. case BuiltinType::Id:
  15801. #include "clang/Basic/OpenCLImageTypes.def"
  15802. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15803. case BuiltinType::Id:
  15804. #include "clang/Basic/OpenCLExtensionTypes.def"
  15805. #define SVE_TYPE(Name, Id, SingletonId) \
  15806. case BuiltinType::Id:
  15807. #include "clang/Basic/AArch64SVEACLETypes.def"
  15808. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15809. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15810. #include "clang/AST/BuiltinTypes.def"
  15811. break;
  15812. }
  15813. llvm_unreachable("invalid placeholder type!");
  15814. }
  15815. bool Sema::CheckCaseExpression(Expr *E) {
  15816. if (E->isTypeDependent())
  15817. return true;
  15818. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15819. return E->getType()->isIntegralOrEnumerationType();
  15820. return false;
  15821. }
  15822. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15823. ExprResult
  15824. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15825. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15826. "Unknown Objective-C Boolean value!");
  15827. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15828. if (!Context.getBOOLDecl()) {
  15829. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15830. Sema::LookupOrdinaryName);
  15831. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15832. NamedDecl *ND = Result.getFoundDecl();
  15833. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15834. Context.setBOOLDecl(TD);
  15835. }
  15836. }
  15837. if (Context.getBOOLDecl())
  15838. BoolT = Context.getBOOLType();
  15839. return new (Context)
  15840. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15841. }
  15842. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15843. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15844. SourceLocation RParen) {
  15845. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15846. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15847. return Spec.getPlatform() == Platform;
  15848. });
  15849. VersionTuple Version;
  15850. if (Spec != AvailSpecs.end())
  15851. Version = Spec->getVersion();
  15852. // The use of `@available` in the enclosing function should be analyzed to
  15853. // warn when it's used inappropriately (i.e. not if(@available)).
  15854. if (getCurFunctionOrMethodDecl())
  15855. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15856. else if (getCurBlock() || getCurLambda())
  15857. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15858. return new (Context)
  15859. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15860. }