SemaExpr.cpp 698 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019
  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) || Opc == BO_And || Opc == BO_Or;
  6701. // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
  6702. // not any of the logical operators. Bitwise-xor is commonly used as a
  6703. // logical-xor because there is no logical-xor operator. The logical
  6704. // operators, including uses of xor, have a high false positive rate for
  6705. // precedence warnings.
  6706. }
  6707. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6708. /// expression, either using a built-in or overloaded operator,
  6709. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6710. /// expression.
  6711. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6712. Expr **RHSExprs) {
  6713. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6714. E = E->IgnoreImpCasts();
  6715. E = E->IgnoreConversionOperator();
  6716. E = E->IgnoreImpCasts();
  6717. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6718. E = MTE->GetTemporaryExpr();
  6719. E = E->IgnoreImpCasts();
  6720. }
  6721. // Built-in binary operator.
  6722. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6723. if (IsArithmeticOp(OP->getOpcode())) {
  6724. *Opcode = OP->getOpcode();
  6725. *RHSExprs = OP->getRHS();
  6726. return true;
  6727. }
  6728. }
  6729. // Overloaded operator.
  6730. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6731. if (Call->getNumArgs() != 2)
  6732. return false;
  6733. // Make sure this is really a binary operator that is safe to pass into
  6734. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6735. OverloadedOperatorKind OO = Call->getOperator();
  6736. if (OO < OO_Plus || OO > OO_Arrow ||
  6737. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6738. return false;
  6739. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6740. if (IsArithmeticOp(OpKind)) {
  6741. *Opcode = OpKind;
  6742. *RHSExprs = Call->getArg(1);
  6743. return true;
  6744. }
  6745. }
  6746. return false;
  6747. }
  6748. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6749. /// or is a logical expression such as (x==y) which has int type, but is
  6750. /// commonly interpreted as boolean.
  6751. static bool ExprLooksBoolean(Expr *E) {
  6752. E = E->IgnoreParenImpCasts();
  6753. if (E->getType()->isBooleanType())
  6754. return true;
  6755. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6756. return OP->isComparisonOp() || OP->isLogicalOp();
  6757. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6758. return OP->getOpcode() == UO_LNot;
  6759. if (E->getType()->isPointerType())
  6760. return true;
  6761. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6762. // type"s (commonly pointer-to-members)?
  6763. return false;
  6764. }
  6765. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6766. /// and binary operator are mixed in a way that suggests the programmer assumed
  6767. /// the conditional operator has higher precedence, for example:
  6768. /// "int x = a + someBinaryCondition ? 1 : 2".
  6769. static void DiagnoseConditionalPrecedence(Sema &Self,
  6770. SourceLocation OpLoc,
  6771. Expr *Condition,
  6772. Expr *LHSExpr,
  6773. Expr *RHSExpr) {
  6774. BinaryOperatorKind CondOpcode;
  6775. Expr *CondRHS;
  6776. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6777. return;
  6778. if (!ExprLooksBoolean(CondRHS))
  6779. return;
  6780. // The condition is an arithmetic binary expression, with a right-
  6781. // hand side that looks boolean, so warn.
  6782. unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
  6783. ? diag::warn_precedence_bitwise_conditional
  6784. : diag::warn_precedence_conditional;
  6785. Self.Diag(OpLoc, DiagID)
  6786. << Condition->getSourceRange()
  6787. << BinaryOperator::getOpcodeStr(CondOpcode);
  6788. SuggestParentheses(
  6789. Self, OpLoc,
  6790. Self.PDiag(diag::note_precedence_silence)
  6791. << BinaryOperator::getOpcodeStr(CondOpcode),
  6792. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6793. SuggestParentheses(Self, OpLoc,
  6794. Self.PDiag(diag::note_precedence_conditional_first),
  6795. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6796. }
  6797. /// Compute the nullability of a conditional expression.
  6798. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6799. QualType LHSTy, QualType RHSTy,
  6800. ASTContext &Ctx) {
  6801. if (!ResTy->isAnyPointerType())
  6802. return ResTy;
  6803. auto GetNullability = [&Ctx](QualType Ty) {
  6804. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6805. if (Kind)
  6806. return *Kind;
  6807. return NullabilityKind::Unspecified;
  6808. };
  6809. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6810. NullabilityKind MergedKind;
  6811. // Compute nullability of a binary conditional expression.
  6812. if (IsBin) {
  6813. if (LHSKind == NullabilityKind::NonNull)
  6814. MergedKind = NullabilityKind::NonNull;
  6815. else
  6816. MergedKind = RHSKind;
  6817. // Compute nullability of a normal conditional expression.
  6818. } else {
  6819. if (LHSKind == NullabilityKind::Nullable ||
  6820. RHSKind == NullabilityKind::Nullable)
  6821. MergedKind = NullabilityKind::Nullable;
  6822. else if (LHSKind == NullabilityKind::NonNull)
  6823. MergedKind = RHSKind;
  6824. else if (RHSKind == NullabilityKind::NonNull)
  6825. MergedKind = LHSKind;
  6826. else
  6827. MergedKind = NullabilityKind::Unspecified;
  6828. }
  6829. // Return if ResTy already has the correct nullability.
  6830. if (GetNullability(ResTy) == MergedKind)
  6831. return ResTy;
  6832. // Strip all nullability from ResTy.
  6833. while (ResTy->getNullability(Ctx))
  6834. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6835. // Create a new AttributedType with the new nullability kind.
  6836. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6837. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6838. }
  6839. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6840. /// in the case of a the GNU conditional expr extension.
  6841. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6842. SourceLocation ColonLoc,
  6843. Expr *CondExpr, Expr *LHSExpr,
  6844. Expr *RHSExpr) {
  6845. if (!getLangOpts().CPlusPlus) {
  6846. // C cannot handle TypoExpr nodes in the condition because it
  6847. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6848. // been dealt with before checking the operands.
  6849. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6850. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6851. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6852. if (!CondResult.isUsable())
  6853. return ExprError();
  6854. if (LHSExpr) {
  6855. if (!LHSResult.isUsable())
  6856. return ExprError();
  6857. }
  6858. if (!RHSResult.isUsable())
  6859. return ExprError();
  6860. CondExpr = CondResult.get();
  6861. LHSExpr = LHSResult.get();
  6862. RHSExpr = RHSResult.get();
  6863. }
  6864. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6865. // was the condition.
  6866. OpaqueValueExpr *opaqueValue = nullptr;
  6867. Expr *commonExpr = nullptr;
  6868. if (!LHSExpr) {
  6869. commonExpr = CondExpr;
  6870. // Lower out placeholder types first. This is important so that we don't
  6871. // try to capture a placeholder. This happens in few cases in C++; such
  6872. // as Objective-C++'s dictionary subscripting syntax.
  6873. if (commonExpr->hasPlaceholderType()) {
  6874. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6875. if (!result.isUsable()) return ExprError();
  6876. commonExpr = result.get();
  6877. }
  6878. // We usually want to apply unary conversions *before* saving, except
  6879. // in the special case of a C++ l-value conditional.
  6880. if (!(getLangOpts().CPlusPlus
  6881. && !commonExpr->isTypeDependent()
  6882. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6883. && commonExpr->isGLValue()
  6884. && commonExpr->isOrdinaryOrBitFieldObject()
  6885. && RHSExpr->isOrdinaryOrBitFieldObject()
  6886. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6887. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6888. if (commonRes.isInvalid())
  6889. return ExprError();
  6890. commonExpr = commonRes.get();
  6891. }
  6892. // If the common expression is a class or array prvalue, materialize it
  6893. // so that we can safely refer to it multiple times.
  6894. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6895. commonExpr->getType()->isArrayType())) {
  6896. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6897. if (MatExpr.isInvalid())
  6898. return ExprError();
  6899. commonExpr = MatExpr.get();
  6900. }
  6901. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6902. commonExpr->getType(),
  6903. commonExpr->getValueKind(),
  6904. commonExpr->getObjectKind(),
  6905. commonExpr);
  6906. LHSExpr = CondExpr = opaqueValue;
  6907. }
  6908. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6909. ExprValueKind VK = VK_RValue;
  6910. ExprObjectKind OK = OK_Ordinary;
  6911. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6912. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6913. VK, OK, QuestionLoc);
  6914. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6915. RHS.isInvalid())
  6916. return ExprError();
  6917. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6918. RHS.get());
  6919. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6920. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6921. Context);
  6922. if (!commonExpr)
  6923. return new (Context)
  6924. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6925. RHS.get(), result, VK, OK);
  6926. return new (Context) BinaryConditionalOperator(
  6927. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6928. ColonLoc, result, VK, OK);
  6929. }
  6930. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6931. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6932. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6933. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6934. // FIXME: add a couple examples in this comment.
  6935. static Sema::AssignConvertType
  6936. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6937. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6938. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6939. // get the "pointed to" type (ignoring qualifiers at the top level)
  6940. const Type *lhptee, *rhptee;
  6941. Qualifiers lhq, rhq;
  6942. std::tie(lhptee, lhq) =
  6943. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6944. std::tie(rhptee, rhq) =
  6945. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6946. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6947. // C99 6.5.16.1p1: This following citation is common to constraints
  6948. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6949. // qualifiers of the type *pointed to* by the right;
  6950. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6951. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6952. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6953. // Ignore lifetime for further calculation.
  6954. lhq.removeObjCLifetime();
  6955. rhq.removeObjCLifetime();
  6956. }
  6957. if (!lhq.compatiblyIncludes(rhq)) {
  6958. // Treat address-space mismatches as fatal.
  6959. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6960. return Sema::IncompatiblePointerDiscardsQualifiers;
  6961. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6962. // and from void*.
  6963. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6964. .compatiblyIncludes(
  6965. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6966. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6967. ; // keep old
  6968. // Treat lifetime mismatches as fatal.
  6969. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6970. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6971. // For GCC/MS compatibility, other qualifier mismatches are treated
  6972. // as still compatible in C.
  6973. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6974. }
  6975. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6976. // incomplete type and the other is a pointer to a qualified or unqualified
  6977. // version of void...
  6978. if (lhptee->isVoidType()) {
  6979. if (rhptee->isIncompleteOrObjectType())
  6980. return ConvTy;
  6981. // As an extension, we allow cast to/from void* to function pointer.
  6982. assert(rhptee->isFunctionType());
  6983. return Sema::FunctionVoidPointer;
  6984. }
  6985. if (rhptee->isVoidType()) {
  6986. if (lhptee->isIncompleteOrObjectType())
  6987. return ConvTy;
  6988. // As an extension, we allow cast to/from void* to function pointer.
  6989. assert(lhptee->isFunctionType());
  6990. return Sema::FunctionVoidPointer;
  6991. }
  6992. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6993. // unqualified versions of compatible types, ...
  6994. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6995. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6996. // Check if the pointee types are compatible ignoring the sign.
  6997. // We explicitly check for char so that we catch "char" vs
  6998. // "unsigned char" on systems where "char" is unsigned.
  6999. if (lhptee->isCharType())
  7000. ltrans = S.Context.UnsignedCharTy;
  7001. else if (lhptee->hasSignedIntegerRepresentation())
  7002. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  7003. if (rhptee->isCharType())
  7004. rtrans = S.Context.UnsignedCharTy;
  7005. else if (rhptee->hasSignedIntegerRepresentation())
  7006. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  7007. if (ltrans == rtrans) {
  7008. // Types are compatible ignoring the sign. Qualifier incompatibility
  7009. // takes priority over sign incompatibility because the sign
  7010. // warning can be disabled.
  7011. if (ConvTy != Sema::Compatible)
  7012. return ConvTy;
  7013. return Sema::IncompatiblePointerSign;
  7014. }
  7015. // If we are a multi-level pointer, it's possible that our issue is simply
  7016. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  7017. // the eventual target type is the same and the pointers have the same
  7018. // level of indirection, this must be the issue.
  7019. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  7020. do {
  7021. std::tie(lhptee, lhq) =
  7022. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  7023. std::tie(rhptee, rhq) =
  7024. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  7025. // Inconsistent address spaces at this point is invalid, even if the
  7026. // address spaces would be compatible.
  7027. // FIXME: This doesn't catch address space mismatches for pointers of
  7028. // different nesting levels, like:
  7029. // __local int *** a;
  7030. // int ** b = a;
  7031. // It's not clear how to actually determine when such pointers are
  7032. // invalidly incompatible.
  7033. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  7034. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  7035. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  7036. if (lhptee == rhptee)
  7037. return Sema::IncompatibleNestedPointerQualifiers;
  7038. }
  7039. // General pointer incompatibility takes priority over qualifiers.
  7040. return Sema::IncompatiblePointer;
  7041. }
  7042. if (!S.getLangOpts().CPlusPlus &&
  7043. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  7044. return Sema::IncompatiblePointer;
  7045. return ConvTy;
  7046. }
  7047. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  7048. /// block pointer types are compatible or whether a block and normal pointer
  7049. /// are compatible. It is more restrict than comparing two function pointer
  7050. // types.
  7051. static Sema::AssignConvertType
  7052. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  7053. QualType RHSType) {
  7054. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  7055. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  7056. QualType lhptee, rhptee;
  7057. // get the "pointed to" type (ignoring qualifiers at the top level)
  7058. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  7059. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  7060. // In C++, the types have to match exactly.
  7061. if (S.getLangOpts().CPlusPlus)
  7062. return Sema::IncompatibleBlockPointer;
  7063. Sema::AssignConvertType ConvTy = Sema::Compatible;
  7064. // For blocks we enforce that qualifiers are identical.
  7065. Qualifiers LQuals = lhptee.getLocalQualifiers();
  7066. Qualifiers RQuals = rhptee.getLocalQualifiers();
  7067. if (S.getLangOpts().OpenCL) {
  7068. LQuals.removeAddressSpace();
  7069. RQuals.removeAddressSpace();
  7070. }
  7071. if (LQuals != RQuals)
  7072. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  7073. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  7074. // assignment.
  7075. // The current behavior is similar to C++ lambdas. A block might be
  7076. // assigned to a variable iff its return type and parameters are compatible
  7077. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  7078. // an assignment. Presumably it should behave in way that a function pointer
  7079. // assignment does in C, so for each parameter and return type:
  7080. // * CVR and address space of LHS should be a superset of CVR and address
  7081. // space of RHS.
  7082. // * unqualified types should be compatible.
  7083. if (S.getLangOpts().OpenCL) {
  7084. if (!S.Context.typesAreBlockPointerCompatible(
  7085. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  7086. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  7087. return Sema::IncompatibleBlockPointer;
  7088. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  7089. return Sema::IncompatibleBlockPointer;
  7090. return ConvTy;
  7091. }
  7092. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  7093. /// for assignment compatibility.
  7094. static Sema::AssignConvertType
  7095. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  7096. QualType RHSType) {
  7097. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  7098. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  7099. if (LHSType->isObjCBuiltinType()) {
  7100. // Class is not compatible with ObjC object pointers.
  7101. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  7102. !RHSType->isObjCQualifiedClassType())
  7103. return Sema::IncompatiblePointer;
  7104. return Sema::Compatible;
  7105. }
  7106. if (RHSType->isObjCBuiltinType()) {
  7107. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  7108. !LHSType->isObjCQualifiedClassType())
  7109. return Sema::IncompatiblePointer;
  7110. return Sema::Compatible;
  7111. }
  7112. QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  7113. QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  7114. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  7115. // make an exception for id<P>
  7116. !LHSType->isObjCQualifiedIdType())
  7117. return Sema::CompatiblePointerDiscardsQualifiers;
  7118. if (S.Context.typesAreCompatible(LHSType, RHSType))
  7119. return Sema::Compatible;
  7120. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  7121. return Sema::IncompatibleObjCQualifiedId;
  7122. return Sema::IncompatiblePointer;
  7123. }
  7124. Sema::AssignConvertType
  7125. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  7126. QualType LHSType, QualType RHSType) {
  7127. // Fake up an opaque expression. We don't actually care about what
  7128. // cast operations are required, so if CheckAssignmentConstraints
  7129. // adds casts to this they'll be wasted, but fortunately that doesn't
  7130. // usually happen on valid code.
  7131. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  7132. ExprResult RHSPtr = &RHSExpr;
  7133. CastKind K;
  7134. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  7135. }
  7136. /// This helper function returns true if QT is a vector type that has element
  7137. /// type ElementType.
  7138. static bool isVector(QualType QT, QualType ElementType) {
  7139. if (const VectorType *VT = QT->getAs<VectorType>())
  7140. return VT->getElementType() == ElementType;
  7141. return false;
  7142. }
  7143. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  7144. /// has code to accommodate several GCC extensions when type checking
  7145. /// pointers. Here are some objectionable examples that GCC considers warnings:
  7146. ///
  7147. /// int a, *pint;
  7148. /// short *pshort;
  7149. /// struct foo *pfoo;
  7150. ///
  7151. /// pint = pshort; // warning: assignment from incompatible pointer type
  7152. /// a = pint; // warning: assignment makes integer from pointer without a cast
  7153. /// pint = a; // warning: assignment makes pointer from integer without a cast
  7154. /// pint = pfoo; // warning: assignment from incompatible pointer type
  7155. ///
  7156. /// As a result, the code for dealing with pointers is more complex than the
  7157. /// C99 spec dictates.
  7158. ///
  7159. /// Sets 'Kind' for any result kind except Incompatible.
  7160. Sema::AssignConvertType
  7161. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  7162. CastKind &Kind, bool ConvertRHS) {
  7163. QualType RHSType = RHS.get()->getType();
  7164. QualType OrigLHSType = LHSType;
  7165. // Get canonical types. We're not formatting these types, just comparing
  7166. // them.
  7167. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  7168. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  7169. // Common case: no conversion required.
  7170. if (LHSType == RHSType) {
  7171. Kind = CK_NoOp;
  7172. return Compatible;
  7173. }
  7174. // If we have an atomic type, try a non-atomic assignment, then just add an
  7175. // atomic qualification step.
  7176. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  7177. Sema::AssignConvertType result =
  7178. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  7179. if (result != Compatible)
  7180. return result;
  7181. if (Kind != CK_NoOp && ConvertRHS)
  7182. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  7183. Kind = CK_NonAtomicToAtomic;
  7184. return Compatible;
  7185. }
  7186. // If the left-hand side is a reference type, then we are in a
  7187. // (rare!) case where we've allowed the use of references in C,
  7188. // e.g., as a parameter type in a built-in function. In this case,
  7189. // just make sure that the type referenced is compatible with the
  7190. // right-hand side type. The caller is responsible for adjusting
  7191. // LHSType so that the resulting expression does not have reference
  7192. // type.
  7193. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7194. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7195. Kind = CK_LValueBitCast;
  7196. return Compatible;
  7197. }
  7198. return Incompatible;
  7199. }
  7200. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7201. // to the same ExtVector type.
  7202. if (LHSType->isExtVectorType()) {
  7203. if (RHSType->isExtVectorType())
  7204. return Incompatible;
  7205. if (RHSType->isArithmeticType()) {
  7206. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7207. if (ConvertRHS)
  7208. RHS = prepareVectorSplat(LHSType, RHS.get());
  7209. Kind = CK_VectorSplat;
  7210. return Compatible;
  7211. }
  7212. }
  7213. // Conversions to or from vector type.
  7214. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7215. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7216. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7217. // vector type and vice versa
  7218. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7219. Kind = CK_BitCast;
  7220. return Compatible;
  7221. }
  7222. // If we are allowing lax vector conversions, and LHS and RHS are both
  7223. // vectors, the total size only needs to be the same. This is a bitcast;
  7224. // no bits are changed but the result type is different.
  7225. if (isLaxVectorConversion(RHSType, LHSType)) {
  7226. Kind = CK_BitCast;
  7227. return IncompatibleVectors;
  7228. }
  7229. }
  7230. // When the RHS comes from another lax conversion (e.g. binops between
  7231. // scalars and vectors) the result is canonicalized as a vector. When the
  7232. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7233. // the case where LHS is a scalar.
  7234. if (LHSType->isScalarType()) {
  7235. const VectorType *VecType = RHSType->getAs<VectorType>();
  7236. if (VecType && VecType->getNumElements() == 1 &&
  7237. isLaxVectorConversion(RHSType, LHSType)) {
  7238. ExprResult *VecExpr = &RHS;
  7239. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7240. Kind = CK_BitCast;
  7241. return Compatible;
  7242. }
  7243. }
  7244. return Incompatible;
  7245. }
  7246. // Diagnose attempts to convert between __float128 and long double where
  7247. // such conversions currently can't be handled.
  7248. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7249. return Incompatible;
  7250. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7251. // discards the imaginary part.
  7252. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7253. !LHSType->getAs<ComplexType>())
  7254. return Incompatible;
  7255. // Arithmetic conversions.
  7256. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7257. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7258. if (ConvertRHS)
  7259. Kind = PrepareScalarCast(RHS, LHSType);
  7260. return Compatible;
  7261. }
  7262. // Conversions to normal pointers.
  7263. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7264. // U* -> T*
  7265. if (isa<PointerType>(RHSType)) {
  7266. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7267. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7268. if (AddrSpaceL != AddrSpaceR)
  7269. Kind = CK_AddressSpaceConversion;
  7270. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7271. Kind = CK_NoOp;
  7272. else
  7273. Kind = CK_BitCast;
  7274. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7275. }
  7276. // int -> T*
  7277. if (RHSType->isIntegerType()) {
  7278. Kind = CK_IntegralToPointer; // FIXME: null?
  7279. return IntToPointer;
  7280. }
  7281. // C pointers are not compatible with ObjC object pointers,
  7282. // with two exceptions:
  7283. if (isa<ObjCObjectPointerType>(RHSType)) {
  7284. // - conversions to void*
  7285. if (LHSPointer->getPointeeType()->isVoidType()) {
  7286. Kind = CK_BitCast;
  7287. return Compatible;
  7288. }
  7289. // - conversions from 'Class' to the redefinition type
  7290. if (RHSType->isObjCClassType() &&
  7291. Context.hasSameType(LHSType,
  7292. Context.getObjCClassRedefinitionType())) {
  7293. Kind = CK_BitCast;
  7294. return Compatible;
  7295. }
  7296. Kind = CK_BitCast;
  7297. return IncompatiblePointer;
  7298. }
  7299. // U^ -> void*
  7300. if (RHSType->getAs<BlockPointerType>()) {
  7301. if (LHSPointer->getPointeeType()->isVoidType()) {
  7302. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7303. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7304. ->getPointeeType()
  7305. .getAddressSpace();
  7306. Kind =
  7307. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7308. return Compatible;
  7309. }
  7310. }
  7311. return Incompatible;
  7312. }
  7313. // Conversions to block pointers.
  7314. if (isa<BlockPointerType>(LHSType)) {
  7315. // U^ -> T^
  7316. if (RHSType->isBlockPointerType()) {
  7317. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7318. ->getPointeeType()
  7319. .getAddressSpace();
  7320. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7321. ->getPointeeType()
  7322. .getAddressSpace();
  7323. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7324. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7325. }
  7326. // int or null -> T^
  7327. if (RHSType->isIntegerType()) {
  7328. Kind = CK_IntegralToPointer; // FIXME: null
  7329. return IntToBlockPointer;
  7330. }
  7331. // id -> T^
  7332. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7333. Kind = CK_AnyPointerToBlockPointerCast;
  7334. return Compatible;
  7335. }
  7336. // void* -> T^
  7337. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7338. if (RHSPT->getPointeeType()->isVoidType()) {
  7339. Kind = CK_AnyPointerToBlockPointerCast;
  7340. return Compatible;
  7341. }
  7342. return Incompatible;
  7343. }
  7344. // Conversions to Objective-C pointers.
  7345. if (isa<ObjCObjectPointerType>(LHSType)) {
  7346. // A* -> B*
  7347. if (RHSType->isObjCObjectPointerType()) {
  7348. Kind = CK_BitCast;
  7349. Sema::AssignConvertType result =
  7350. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7351. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7352. result == Compatible &&
  7353. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7354. result = IncompatibleObjCWeakRef;
  7355. return result;
  7356. }
  7357. // int or null -> A*
  7358. if (RHSType->isIntegerType()) {
  7359. Kind = CK_IntegralToPointer; // FIXME: null
  7360. return IntToPointer;
  7361. }
  7362. // In general, C pointers are not compatible with ObjC object pointers,
  7363. // with two exceptions:
  7364. if (isa<PointerType>(RHSType)) {
  7365. Kind = CK_CPointerToObjCPointerCast;
  7366. // - conversions from 'void*'
  7367. if (RHSType->isVoidPointerType()) {
  7368. return Compatible;
  7369. }
  7370. // - conversions to 'Class' from its redefinition type
  7371. if (LHSType->isObjCClassType() &&
  7372. Context.hasSameType(RHSType,
  7373. Context.getObjCClassRedefinitionType())) {
  7374. return Compatible;
  7375. }
  7376. return IncompatiblePointer;
  7377. }
  7378. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7379. if (RHSType->isBlockPointerType() &&
  7380. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7381. if (ConvertRHS)
  7382. maybeExtendBlockObject(RHS);
  7383. Kind = CK_BlockPointerToObjCPointerCast;
  7384. return Compatible;
  7385. }
  7386. return Incompatible;
  7387. }
  7388. // Conversions from pointers that are not covered by the above.
  7389. if (isa<PointerType>(RHSType)) {
  7390. // T* -> _Bool
  7391. if (LHSType == Context.BoolTy) {
  7392. Kind = CK_PointerToBoolean;
  7393. return Compatible;
  7394. }
  7395. // T* -> int
  7396. if (LHSType->isIntegerType()) {
  7397. Kind = CK_PointerToIntegral;
  7398. return PointerToInt;
  7399. }
  7400. return Incompatible;
  7401. }
  7402. // Conversions from Objective-C pointers that are not covered by the above.
  7403. if (isa<ObjCObjectPointerType>(RHSType)) {
  7404. // T* -> _Bool
  7405. if (LHSType == Context.BoolTy) {
  7406. Kind = CK_PointerToBoolean;
  7407. return Compatible;
  7408. }
  7409. // T* -> int
  7410. if (LHSType->isIntegerType()) {
  7411. Kind = CK_PointerToIntegral;
  7412. return PointerToInt;
  7413. }
  7414. return Incompatible;
  7415. }
  7416. // struct A -> struct B
  7417. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7418. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7419. Kind = CK_NoOp;
  7420. return Compatible;
  7421. }
  7422. }
  7423. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7424. Kind = CK_IntToOCLSampler;
  7425. return Compatible;
  7426. }
  7427. return Incompatible;
  7428. }
  7429. /// Constructs a transparent union from an expression that is
  7430. /// used to initialize the transparent union.
  7431. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7432. ExprResult &EResult, QualType UnionType,
  7433. FieldDecl *Field) {
  7434. // Build an initializer list that designates the appropriate member
  7435. // of the transparent union.
  7436. Expr *E = EResult.get();
  7437. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7438. E, SourceLocation());
  7439. Initializer->setType(UnionType);
  7440. Initializer->setInitializedFieldInUnion(Field);
  7441. // Build a compound literal constructing a value of the transparent
  7442. // union type from this initializer list.
  7443. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7444. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7445. VK_RValue, Initializer, false);
  7446. }
  7447. Sema::AssignConvertType
  7448. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7449. ExprResult &RHS) {
  7450. QualType RHSType = RHS.get()->getType();
  7451. // If the ArgType is a Union type, we want to handle a potential
  7452. // transparent_union GCC extension.
  7453. const RecordType *UT = ArgType->getAsUnionType();
  7454. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7455. return Incompatible;
  7456. // The field to initialize within the transparent union.
  7457. RecordDecl *UD = UT->getDecl();
  7458. FieldDecl *InitField = nullptr;
  7459. // It's compatible if the expression matches any of the fields.
  7460. for (auto *it : UD->fields()) {
  7461. if (it->getType()->isPointerType()) {
  7462. // If the transparent union contains a pointer type, we allow:
  7463. // 1) void pointer
  7464. // 2) null pointer constant
  7465. if (RHSType->isPointerType())
  7466. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7467. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7468. InitField = it;
  7469. break;
  7470. }
  7471. if (RHS.get()->isNullPointerConstant(Context,
  7472. Expr::NPC_ValueDependentIsNull)) {
  7473. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7474. CK_NullToPointer);
  7475. InitField = it;
  7476. break;
  7477. }
  7478. }
  7479. CastKind Kind;
  7480. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7481. == Compatible) {
  7482. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7483. InitField = it;
  7484. break;
  7485. }
  7486. }
  7487. if (!InitField)
  7488. return Incompatible;
  7489. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7490. return Compatible;
  7491. }
  7492. Sema::AssignConvertType
  7493. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7494. bool Diagnose,
  7495. bool DiagnoseCFAudited,
  7496. bool ConvertRHS) {
  7497. // We need to be able to tell the caller whether we diagnosed a problem, if
  7498. // they ask us to issue diagnostics.
  7499. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7500. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7501. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7502. // to put the updated value.
  7503. ExprResult LocalRHS = CallerRHS;
  7504. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7505. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7506. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7507. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7508. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7509. Diag(RHS.get()->getExprLoc(),
  7510. diag::warn_noderef_to_dereferenceable_pointer)
  7511. << RHS.get()->getSourceRange();
  7512. }
  7513. }
  7514. }
  7515. if (getLangOpts().CPlusPlus) {
  7516. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7517. // C++ 5.17p3: If the left operand is not of class type, the
  7518. // expression is implicitly converted (C++ 4) to the
  7519. // cv-unqualified type of the left operand.
  7520. QualType RHSType = RHS.get()->getType();
  7521. if (Diagnose) {
  7522. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7523. AA_Assigning);
  7524. } else {
  7525. ImplicitConversionSequence ICS =
  7526. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7527. /*SuppressUserConversions=*/false,
  7528. /*AllowExplicit=*/false,
  7529. /*InOverloadResolution=*/false,
  7530. /*CStyle=*/false,
  7531. /*AllowObjCWritebackConversion=*/false);
  7532. if (ICS.isFailure())
  7533. return Incompatible;
  7534. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7535. ICS, AA_Assigning);
  7536. }
  7537. if (RHS.isInvalid())
  7538. return Incompatible;
  7539. Sema::AssignConvertType result = Compatible;
  7540. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7541. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7542. result = IncompatibleObjCWeakRef;
  7543. return result;
  7544. }
  7545. // FIXME: Currently, we fall through and treat C++ classes like C
  7546. // structures.
  7547. // FIXME: We also fall through for atomics; not sure what should
  7548. // happen there, though.
  7549. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7550. // As a set of extensions to C, we support overloading on functions. These
  7551. // functions need to be resolved here.
  7552. DeclAccessPair DAP;
  7553. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7554. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7555. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7556. else
  7557. return Incompatible;
  7558. }
  7559. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7560. // a null pointer constant.
  7561. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7562. LHSType->isBlockPointerType()) &&
  7563. RHS.get()->isNullPointerConstant(Context,
  7564. Expr::NPC_ValueDependentIsNull)) {
  7565. if (Diagnose || ConvertRHS) {
  7566. CastKind Kind;
  7567. CXXCastPath Path;
  7568. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7569. /*IgnoreBaseAccess=*/false, Diagnose);
  7570. if (ConvertRHS)
  7571. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7572. }
  7573. return Compatible;
  7574. }
  7575. // OpenCL queue_t type assignment.
  7576. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7577. Context, Expr::NPC_ValueDependentIsNull)) {
  7578. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7579. return Compatible;
  7580. }
  7581. // This check seems unnatural, however it is necessary to ensure the proper
  7582. // conversion of functions/arrays. If the conversion were done for all
  7583. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7584. // expressions that suppress this implicit conversion (&, sizeof).
  7585. //
  7586. // Suppress this for references: C++ 8.5.3p5.
  7587. if (!LHSType->isReferenceType()) {
  7588. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7589. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7590. if (RHS.isInvalid())
  7591. return Incompatible;
  7592. }
  7593. CastKind Kind;
  7594. Sema::AssignConvertType result =
  7595. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7596. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7597. // type of the assignment expression.
  7598. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7599. // so that we can use references in built-in functions even in C.
  7600. // The getNonReferenceType() call makes sure that the resulting expression
  7601. // does not have reference type.
  7602. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7603. QualType Ty = LHSType.getNonLValueExprType(Context);
  7604. Expr *E = RHS.get();
  7605. // Check for various Objective-C errors. If we are not reporting
  7606. // diagnostics and just checking for errors, e.g., during overload
  7607. // resolution, return Incompatible to indicate the failure.
  7608. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7609. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7610. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7611. if (!Diagnose)
  7612. return Incompatible;
  7613. }
  7614. if (getLangOpts().ObjC &&
  7615. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7616. E->getType(), E, Diagnose) ||
  7617. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7618. if (!Diagnose)
  7619. return Incompatible;
  7620. // Replace the expression with a corrected version and continue so we
  7621. // can find further errors.
  7622. RHS = E;
  7623. return Compatible;
  7624. }
  7625. if (ConvertRHS)
  7626. RHS = ImpCastExprToType(E, Ty, Kind);
  7627. }
  7628. return result;
  7629. }
  7630. namespace {
  7631. /// The original operand to an operator, prior to the application of the usual
  7632. /// arithmetic conversions and converting the arguments of a builtin operator
  7633. /// candidate.
  7634. struct OriginalOperand {
  7635. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7636. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7637. Op = MTE->GetTemporaryExpr();
  7638. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7639. Op = BTE->getSubExpr();
  7640. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7641. Orig = ICE->getSubExprAsWritten();
  7642. Conversion = ICE->getConversionFunction();
  7643. }
  7644. }
  7645. QualType getType() const { return Orig->getType(); }
  7646. Expr *Orig;
  7647. NamedDecl *Conversion;
  7648. };
  7649. }
  7650. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7651. ExprResult &RHS) {
  7652. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7653. Diag(Loc, diag::err_typecheck_invalid_operands)
  7654. << OrigLHS.getType() << OrigRHS.getType()
  7655. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7656. // If a user-defined conversion was applied to either of the operands prior
  7657. // to applying the built-in operator rules, tell the user about it.
  7658. if (OrigLHS.Conversion) {
  7659. Diag(OrigLHS.Conversion->getLocation(),
  7660. diag::note_typecheck_invalid_operands_converted)
  7661. << 0 << LHS.get()->getType();
  7662. }
  7663. if (OrigRHS.Conversion) {
  7664. Diag(OrigRHS.Conversion->getLocation(),
  7665. diag::note_typecheck_invalid_operands_converted)
  7666. << 1 << RHS.get()->getType();
  7667. }
  7668. return QualType();
  7669. }
  7670. // Diagnose cases where a scalar was implicitly converted to a vector and
  7671. // diagnose the underlying types. Otherwise, diagnose the error
  7672. // as invalid vector logical operands for non-C++ cases.
  7673. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7674. ExprResult &RHS) {
  7675. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7676. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7677. bool LHSNatVec = LHSType->isVectorType();
  7678. bool RHSNatVec = RHSType->isVectorType();
  7679. if (!(LHSNatVec && RHSNatVec)) {
  7680. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7681. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7682. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7683. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7684. << Vector->getSourceRange();
  7685. return QualType();
  7686. }
  7687. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7688. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7689. << RHS.get()->getSourceRange();
  7690. return QualType();
  7691. }
  7692. /// Try to convert a value of non-vector type to a vector type by converting
  7693. /// the type to the element type of the vector and then performing a splat.
  7694. /// If the language is OpenCL, we only use conversions that promote scalar
  7695. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7696. /// for float->int.
  7697. ///
  7698. /// OpenCL V2.0 6.2.6.p2:
  7699. /// An error shall occur if any scalar operand type has greater rank
  7700. /// than the type of the vector element.
  7701. ///
  7702. /// \param scalar - if non-null, actually perform the conversions
  7703. /// \return true if the operation fails (but without diagnosing the failure)
  7704. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7705. QualType scalarTy,
  7706. QualType vectorEltTy,
  7707. QualType vectorTy,
  7708. unsigned &DiagID) {
  7709. // The conversion to apply to the scalar before splatting it,
  7710. // if necessary.
  7711. CastKind scalarCast = CK_NoOp;
  7712. if (vectorEltTy->isIntegralType(S.Context)) {
  7713. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7714. (scalarTy->isIntegerType() &&
  7715. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7716. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7717. return true;
  7718. }
  7719. if (!scalarTy->isIntegralType(S.Context))
  7720. return true;
  7721. scalarCast = CK_IntegralCast;
  7722. } else if (vectorEltTy->isRealFloatingType()) {
  7723. if (scalarTy->isRealFloatingType()) {
  7724. if (S.getLangOpts().OpenCL &&
  7725. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7726. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7727. return true;
  7728. }
  7729. scalarCast = CK_FloatingCast;
  7730. }
  7731. else if (scalarTy->isIntegralType(S.Context))
  7732. scalarCast = CK_IntegralToFloating;
  7733. else
  7734. return true;
  7735. } else {
  7736. return true;
  7737. }
  7738. // Adjust scalar if desired.
  7739. if (scalar) {
  7740. if (scalarCast != CK_NoOp)
  7741. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7742. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7743. }
  7744. return false;
  7745. }
  7746. /// Convert vector E to a vector with the same number of elements but different
  7747. /// element type.
  7748. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7749. const auto *VecTy = E->getType()->getAs<VectorType>();
  7750. assert(VecTy && "Expression E must be a vector");
  7751. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7752. VecTy->getNumElements(),
  7753. VecTy->getVectorKind());
  7754. // Look through the implicit cast. Return the subexpression if its type is
  7755. // NewVecTy.
  7756. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7757. if (ICE->getSubExpr()->getType() == NewVecTy)
  7758. return ICE->getSubExpr();
  7759. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7760. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7761. }
  7762. /// Test if a (constant) integer Int can be casted to another integer type
  7763. /// IntTy without losing precision.
  7764. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7765. QualType OtherIntTy) {
  7766. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7767. // Reject cases where the value of the Int is unknown as that would
  7768. // possibly cause truncation, but accept cases where the scalar can be
  7769. // demoted without loss of precision.
  7770. Expr::EvalResult EVResult;
  7771. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7772. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7773. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7774. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7775. if (CstInt) {
  7776. // If the scalar is constant and is of a higher order and has more active
  7777. // bits that the vector element type, reject it.
  7778. llvm::APSInt Result = EVResult.Val.getInt();
  7779. unsigned NumBits = IntSigned
  7780. ? (Result.isNegative() ? Result.getMinSignedBits()
  7781. : Result.getActiveBits())
  7782. : Result.getActiveBits();
  7783. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7784. return true;
  7785. // If the signedness of the scalar type and the vector element type
  7786. // differs and the number of bits is greater than that of the vector
  7787. // element reject it.
  7788. return (IntSigned != OtherIntSigned &&
  7789. NumBits > S.Context.getIntWidth(OtherIntTy));
  7790. }
  7791. // Reject cases where the value of the scalar is not constant and it's
  7792. // order is greater than that of the vector element type.
  7793. return (Order < 0);
  7794. }
  7795. /// Test if a (constant) integer Int can be casted to floating point type
  7796. /// FloatTy without losing precision.
  7797. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7798. QualType FloatTy) {
  7799. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7800. // Determine if the integer constant can be expressed as a floating point
  7801. // number of the appropriate type.
  7802. Expr::EvalResult EVResult;
  7803. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7804. uint64_t Bits = 0;
  7805. if (CstInt) {
  7806. // Reject constants that would be truncated if they were converted to
  7807. // the floating point type. Test by simple to/from conversion.
  7808. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7809. // could be avoided if there was a convertFromAPInt method
  7810. // which could signal back if implicit truncation occurred.
  7811. llvm::APSInt Result = EVResult.Val.getInt();
  7812. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7813. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7814. llvm::APFloat::rmTowardZero);
  7815. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7816. !IntTy->hasSignedIntegerRepresentation());
  7817. bool Ignored = false;
  7818. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7819. &Ignored);
  7820. if (Result != ConvertBack)
  7821. return true;
  7822. } else {
  7823. // Reject types that cannot be fully encoded into the mantissa of
  7824. // the float.
  7825. Bits = S.Context.getTypeSize(IntTy);
  7826. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7827. S.Context.getFloatTypeSemantics(FloatTy));
  7828. if (Bits > FloatPrec)
  7829. return true;
  7830. }
  7831. return false;
  7832. }
  7833. /// Attempt to convert and splat Scalar into a vector whose types matches
  7834. /// Vector following GCC conversion rules. The rule is that implicit
  7835. /// conversion can occur when Scalar can be casted to match Vector's element
  7836. /// type without causing truncation of Scalar.
  7837. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7838. ExprResult *Vector) {
  7839. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7840. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7841. const VectorType *VT = VectorTy->getAs<VectorType>();
  7842. assert(!isa<ExtVectorType>(VT) &&
  7843. "ExtVectorTypes should not be handled here!");
  7844. QualType VectorEltTy = VT->getElementType();
  7845. // Reject cases where the vector element type or the scalar element type are
  7846. // not integral or floating point types.
  7847. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7848. return true;
  7849. // The conversion to apply to the scalar before splatting it,
  7850. // if necessary.
  7851. CastKind ScalarCast = CK_NoOp;
  7852. // Accept cases where the vector elements are integers and the scalar is
  7853. // an integer.
  7854. // FIXME: Notionally if the scalar was a floating point value with a precise
  7855. // integral representation, we could cast it to an appropriate integer
  7856. // type and then perform the rest of the checks here. GCC will perform
  7857. // this conversion in some cases as determined by the input language.
  7858. // We should accept it on a language independent basis.
  7859. if (VectorEltTy->isIntegralType(S.Context) &&
  7860. ScalarTy->isIntegralType(S.Context) &&
  7861. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7862. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7863. return true;
  7864. ScalarCast = CK_IntegralCast;
  7865. } else if (VectorEltTy->isRealFloatingType()) {
  7866. if (ScalarTy->isRealFloatingType()) {
  7867. // Reject cases where the scalar type is not a constant and has a higher
  7868. // Order than the vector element type.
  7869. llvm::APFloat Result(0.0);
  7870. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7871. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7872. if (!CstScalar && Order < 0)
  7873. return true;
  7874. // If the scalar cannot be safely casted to the vector element type,
  7875. // reject it.
  7876. if (CstScalar) {
  7877. bool Truncated = false;
  7878. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7879. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7880. if (Truncated)
  7881. return true;
  7882. }
  7883. ScalarCast = CK_FloatingCast;
  7884. } else if (ScalarTy->isIntegralType(S.Context)) {
  7885. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7886. return true;
  7887. ScalarCast = CK_IntegralToFloating;
  7888. } else
  7889. return true;
  7890. }
  7891. // Adjust scalar if desired.
  7892. if (Scalar) {
  7893. if (ScalarCast != CK_NoOp)
  7894. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7895. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7896. }
  7897. return false;
  7898. }
  7899. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7900. SourceLocation Loc, bool IsCompAssign,
  7901. bool AllowBothBool,
  7902. bool AllowBoolConversions) {
  7903. if (!IsCompAssign) {
  7904. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7905. if (LHS.isInvalid())
  7906. return QualType();
  7907. }
  7908. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7909. if (RHS.isInvalid())
  7910. return QualType();
  7911. // For conversion purposes, we ignore any qualifiers.
  7912. // For example, "const float" and "float" are equivalent.
  7913. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7914. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7915. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7916. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7917. assert(LHSVecType || RHSVecType);
  7918. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7919. // for some operators but not others.
  7920. if (!AllowBothBool &&
  7921. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7922. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7923. return InvalidOperands(Loc, LHS, RHS);
  7924. // If the vector types are identical, return.
  7925. if (Context.hasSameType(LHSType, RHSType))
  7926. return LHSType;
  7927. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7928. if (LHSVecType && RHSVecType &&
  7929. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7930. if (isa<ExtVectorType>(LHSVecType)) {
  7931. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7932. return LHSType;
  7933. }
  7934. if (!IsCompAssign)
  7935. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7936. return RHSType;
  7937. }
  7938. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7939. // can be mixed, with the result being the non-bool type. The non-bool
  7940. // operand must have integer element type.
  7941. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7942. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7943. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7944. Context.getTypeSize(RHSVecType->getElementType()))) {
  7945. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7946. LHSVecType->getElementType()->isIntegerType() &&
  7947. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7948. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7949. return LHSType;
  7950. }
  7951. if (!IsCompAssign &&
  7952. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7953. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7954. RHSVecType->getElementType()->isIntegerType()) {
  7955. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7956. return RHSType;
  7957. }
  7958. }
  7959. // If there's a vector type and a scalar, try to convert the scalar to
  7960. // the vector element type and splat.
  7961. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7962. if (!RHSVecType) {
  7963. if (isa<ExtVectorType>(LHSVecType)) {
  7964. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7965. LHSVecType->getElementType(), LHSType,
  7966. DiagID))
  7967. return LHSType;
  7968. } else {
  7969. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7970. return LHSType;
  7971. }
  7972. }
  7973. if (!LHSVecType) {
  7974. if (isa<ExtVectorType>(RHSVecType)) {
  7975. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7976. LHSType, RHSVecType->getElementType(),
  7977. RHSType, DiagID))
  7978. return RHSType;
  7979. } else {
  7980. if (LHS.get()->getValueKind() == VK_LValue ||
  7981. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7982. return RHSType;
  7983. }
  7984. }
  7985. // FIXME: The code below also handles conversion between vectors and
  7986. // non-scalars, we should break this down into fine grained specific checks
  7987. // and emit proper diagnostics.
  7988. QualType VecType = LHSVecType ? LHSType : RHSType;
  7989. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7990. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7991. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7992. if (isLaxVectorConversion(OtherType, VecType)) {
  7993. // If we're allowing lax vector conversions, only the total (data) size
  7994. // needs to be the same. For non compound assignment, if one of the types is
  7995. // scalar, the result is always the vector type.
  7996. if (!IsCompAssign) {
  7997. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7998. return VecType;
  7999. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  8000. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  8001. // type. Note that this is already done by non-compound assignments in
  8002. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  8003. // <1 x T> -> T. The result is also a vector type.
  8004. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  8005. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  8006. ExprResult *RHSExpr = &RHS;
  8007. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  8008. return VecType;
  8009. }
  8010. }
  8011. // Okay, the expression is invalid.
  8012. // If there's a non-vector, non-real operand, diagnose that.
  8013. if ((!RHSVecType && !RHSType->isRealType()) ||
  8014. (!LHSVecType && !LHSType->isRealType())) {
  8015. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  8016. << LHSType << RHSType
  8017. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8018. return QualType();
  8019. }
  8020. // OpenCL V1.1 6.2.6.p1:
  8021. // If the operands are of more than one vector type, then an error shall
  8022. // occur. Implicit conversions between vector types are not permitted, per
  8023. // section 6.2.1.
  8024. if (getLangOpts().OpenCL &&
  8025. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  8026. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  8027. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  8028. << RHSType;
  8029. return QualType();
  8030. }
  8031. // If there is a vector type that is not a ExtVector and a scalar, we reach
  8032. // this point if scalar could not be converted to the vector's element type
  8033. // without truncation.
  8034. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  8035. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  8036. QualType Scalar = LHSVecType ? RHSType : LHSType;
  8037. QualType Vector = LHSVecType ? LHSType : RHSType;
  8038. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  8039. Diag(Loc,
  8040. diag::err_typecheck_vector_not_convertable_implict_truncation)
  8041. << ScalarOrVector << Scalar << Vector;
  8042. return QualType();
  8043. }
  8044. // Otherwise, use the generic diagnostic.
  8045. Diag(Loc, DiagID)
  8046. << LHSType << RHSType
  8047. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8048. return QualType();
  8049. }
  8050. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  8051. // expression. These are mainly cases where the null pointer is used as an
  8052. // integer instead of a pointer.
  8053. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8054. SourceLocation Loc, bool IsCompare) {
  8055. // The canonical way to check for a GNU null is with isNullPointerConstant,
  8056. // but we use a bit of a hack here for speed; this is a relatively
  8057. // hot path, and isNullPointerConstant is slow.
  8058. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  8059. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  8060. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  8061. // Avoid analyzing cases where the result will either be invalid (and
  8062. // diagnosed as such) or entirely valid and not something to warn about.
  8063. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  8064. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  8065. return;
  8066. // Comparison operations would not make sense with a null pointer no matter
  8067. // what the other expression is.
  8068. if (!IsCompare) {
  8069. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  8070. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  8071. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  8072. return;
  8073. }
  8074. // The rest of the operations only make sense with a null pointer
  8075. // if the other expression is a pointer.
  8076. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  8077. NonNullType->canDecayToPointerType())
  8078. return;
  8079. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  8080. << LHSNull /* LHS is NULL */ << NonNullType
  8081. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8082. }
  8083. static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
  8084. SourceLocation Loc) {
  8085. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  8086. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  8087. if (!LUE || !RUE)
  8088. return;
  8089. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  8090. RUE->getKind() != UETT_SizeOf)
  8091. return;
  8092. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  8093. QualType LHSTy = LHSArg->getType();
  8094. QualType RHSTy;
  8095. if (RUE->isArgumentType())
  8096. RHSTy = RUE->getArgumentType();
  8097. else
  8098. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  8099. if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
  8100. if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
  8101. return;
  8102. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  8103. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8104. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8105. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  8106. << LHSArgDecl;
  8107. }
  8108. } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
  8109. QualType ArrayElemTy = ArrayTy->getElementType();
  8110. if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
  8111. ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
  8112. ArrayElemTy->isCharType() ||
  8113. S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
  8114. return;
  8115. S.Diag(Loc, diag::warn_division_sizeof_array)
  8116. << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
  8117. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8118. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8119. S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
  8120. << LHSArgDecl;
  8121. }
  8122. S.Diag(Loc, diag::note_precedence_silence) << RHS;
  8123. }
  8124. }
  8125. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  8126. ExprResult &RHS,
  8127. SourceLocation Loc, bool IsDiv) {
  8128. // Check for division/remainder by zero.
  8129. Expr::EvalResult RHSValue;
  8130. if (!RHS.get()->isValueDependent() &&
  8131. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  8132. RHSValue.Val.getInt() == 0)
  8133. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8134. S.PDiag(diag::warn_remainder_division_by_zero)
  8135. << IsDiv << RHS.get()->getSourceRange());
  8136. }
  8137. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  8138. SourceLocation Loc,
  8139. bool IsCompAssign, bool IsDiv) {
  8140. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8141. if (LHS.get()->getType()->isVectorType() ||
  8142. RHS.get()->getType()->isVectorType())
  8143. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8144. /*AllowBothBool*/getLangOpts().AltiVec,
  8145. /*AllowBoolConversions*/false);
  8146. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8147. if (LHS.isInvalid() || RHS.isInvalid())
  8148. return QualType();
  8149. if (compType.isNull() || !compType->isArithmeticType())
  8150. return InvalidOperands(Loc, LHS, RHS);
  8151. if (IsDiv) {
  8152. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  8153. DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
  8154. }
  8155. return compType;
  8156. }
  8157. QualType Sema::CheckRemainderOperands(
  8158. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  8159. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8160. if (LHS.get()->getType()->isVectorType() ||
  8161. RHS.get()->getType()->isVectorType()) {
  8162. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8163. RHS.get()->getType()->hasIntegerRepresentation())
  8164. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8165. /*AllowBothBool*/getLangOpts().AltiVec,
  8166. /*AllowBoolConversions*/false);
  8167. return InvalidOperands(Loc, LHS, RHS);
  8168. }
  8169. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8170. if (LHS.isInvalid() || RHS.isInvalid())
  8171. return QualType();
  8172. if (compType.isNull() || !compType->isIntegerType())
  8173. return InvalidOperands(Loc, LHS, RHS);
  8174. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  8175. return compType;
  8176. }
  8177. /// Diagnose invalid arithmetic on two void pointers.
  8178. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  8179. Expr *LHSExpr, Expr *RHSExpr) {
  8180. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8181. ? diag::err_typecheck_pointer_arith_void_type
  8182. : diag::ext_gnu_void_ptr)
  8183. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  8184. << RHSExpr->getSourceRange();
  8185. }
  8186. /// Diagnose invalid arithmetic on a void pointer.
  8187. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  8188. Expr *Pointer) {
  8189. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8190. ? diag::err_typecheck_pointer_arith_void_type
  8191. : diag::ext_gnu_void_ptr)
  8192. << 0 /* one pointer */ << Pointer->getSourceRange();
  8193. }
  8194. /// Diagnose invalid arithmetic on a null pointer.
  8195. ///
  8196. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  8197. /// idiom, which we recognize as a GNU extension.
  8198. ///
  8199. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  8200. Expr *Pointer, bool IsGNUIdiom) {
  8201. if (IsGNUIdiom)
  8202. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  8203. << Pointer->getSourceRange();
  8204. else
  8205. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8206. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8207. }
  8208. /// Diagnose invalid arithmetic on two function pointers.
  8209. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8210. Expr *LHS, Expr *RHS) {
  8211. assert(LHS->getType()->isAnyPointerType());
  8212. assert(RHS->getType()->isAnyPointerType());
  8213. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8214. ? diag::err_typecheck_pointer_arith_function_type
  8215. : diag::ext_gnu_ptr_func_arith)
  8216. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8217. // We only show the second type if it differs from the first.
  8218. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8219. RHS->getType())
  8220. << RHS->getType()->getPointeeType()
  8221. << LHS->getSourceRange() << RHS->getSourceRange();
  8222. }
  8223. /// Diagnose invalid arithmetic on a function pointer.
  8224. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8225. Expr *Pointer) {
  8226. assert(Pointer->getType()->isAnyPointerType());
  8227. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8228. ? diag::err_typecheck_pointer_arith_function_type
  8229. : diag::ext_gnu_ptr_func_arith)
  8230. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8231. << 0 /* one pointer, so only one type */
  8232. << Pointer->getSourceRange();
  8233. }
  8234. /// Emit error if Operand is incomplete pointer type
  8235. ///
  8236. /// \returns True if pointer has incomplete type
  8237. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8238. Expr *Operand) {
  8239. QualType ResType = Operand->getType();
  8240. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8241. ResType = ResAtomicType->getValueType();
  8242. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8243. QualType PointeeTy = ResType->getPointeeType();
  8244. return S.RequireCompleteType(Loc, PointeeTy,
  8245. diag::err_typecheck_arithmetic_incomplete_type,
  8246. PointeeTy, Operand->getSourceRange());
  8247. }
  8248. /// Check the validity of an arithmetic pointer operand.
  8249. ///
  8250. /// If the operand has pointer type, this code will check for pointer types
  8251. /// which are invalid in arithmetic operations. These will be diagnosed
  8252. /// appropriately, including whether or not the use is supported as an
  8253. /// extension.
  8254. ///
  8255. /// \returns True when the operand is valid to use (even if as an extension).
  8256. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8257. Expr *Operand) {
  8258. QualType ResType = Operand->getType();
  8259. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8260. ResType = ResAtomicType->getValueType();
  8261. if (!ResType->isAnyPointerType()) return true;
  8262. QualType PointeeTy = ResType->getPointeeType();
  8263. if (PointeeTy->isVoidType()) {
  8264. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8265. return !S.getLangOpts().CPlusPlus;
  8266. }
  8267. if (PointeeTy->isFunctionType()) {
  8268. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8269. return !S.getLangOpts().CPlusPlus;
  8270. }
  8271. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8272. return true;
  8273. }
  8274. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8275. /// operands.
  8276. ///
  8277. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8278. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8279. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8280. /// are (potentially problematic) pointers.
  8281. ///
  8282. /// \returns True when the operand is valid to use (even if as an extension).
  8283. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8284. Expr *LHSExpr, Expr *RHSExpr) {
  8285. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8286. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8287. if (!isLHSPointer && !isRHSPointer) return true;
  8288. QualType LHSPointeeTy, RHSPointeeTy;
  8289. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8290. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8291. // if both are pointers check if operation is valid wrt address spaces
  8292. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8293. const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
  8294. const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
  8295. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8296. S.Diag(Loc,
  8297. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8298. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8299. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8300. return false;
  8301. }
  8302. }
  8303. // Check for arithmetic on pointers to incomplete types.
  8304. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8305. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8306. if (isLHSVoidPtr || isRHSVoidPtr) {
  8307. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8308. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8309. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8310. return !S.getLangOpts().CPlusPlus;
  8311. }
  8312. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8313. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8314. if (isLHSFuncPtr || isRHSFuncPtr) {
  8315. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8316. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8317. RHSExpr);
  8318. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8319. return !S.getLangOpts().CPlusPlus;
  8320. }
  8321. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8322. return false;
  8323. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8324. return false;
  8325. return true;
  8326. }
  8327. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8328. /// literal.
  8329. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8330. Expr *LHSExpr, Expr *RHSExpr) {
  8331. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8332. Expr* IndexExpr = RHSExpr;
  8333. if (!StrExpr) {
  8334. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8335. IndexExpr = LHSExpr;
  8336. }
  8337. bool IsStringPlusInt = StrExpr &&
  8338. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8339. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8340. return;
  8341. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8342. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8343. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8344. // Only print a fixit for "str" + int, not for int + "str".
  8345. if (IndexExpr == RHSExpr) {
  8346. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8347. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8348. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8349. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8350. << FixItHint::CreateInsertion(EndLoc, "]");
  8351. } else
  8352. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8353. }
  8354. /// Emit a warning when adding a char literal to a string.
  8355. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8356. Expr *LHSExpr, Expr *RHSExpr) {
  8357. const Expr *StringRefExpr = LHSExpr;
  8358. const CharacterLiteral *CharExpr =
  8359. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8360. if (!CharExpr) {
  8361. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8362. StringRefExpr = RHSExpr;
  8363. }
  8364. if (!CharExpr || !StringRefExpr)
  8365. return;
  8366. const QualType StringType = StringRefExpr->getType();
  8367. // Return if not a PointerType.
  8368. if (!StringType->isAnyPointerType())
  8369. return;
  8370. // Return if not a CharacterType.
  8371. if (!StringType->getPointeeType()->isAnyCharacterType())
  8372. return;
  8373. ASTContext &Ctx = Self.getASTContext();
  8374. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8375. const QualType CharType = CharExpr->getType();
  8376. if (!CharType->isAnyCharacterType() &&
  8377. CharType->isIntegerType() &&
  8378. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8379. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8380. << DiagRange << Ctx.CharTy;
  8381. } else {
  8382. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8383. << DiagRange << CharExpr->getType();
  8384. }
  8385. // Only print a fixit for str + char, not for char + str.
  8386. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8387. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8388. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8389. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8390. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8391. << FixItHint::CreateInsertion(EndLoc, "]");
  8392. } else {
  8393. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8394. }
  8395. }
  8396. /// Emit error when two pointers are incompatible.
  8397. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8398. Expr *LHSExpr, Expr *RHSExpr) {
  8399. assert(LHSExpr->getType()->isAnyPointerType());
  8400. assert(RHSExpr->getType()->isAnyPointerType());
  8401. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8402. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8403. << RHSExpr->getSourceRange();
  8404. }
  8405. // C99 6.5.6
  8406. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8407. SourceLocation Loc, BinaryOperatorKind Opc,
  8408. QualType* CompLHSTy) {
  8409. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8410. if (LHS.get()->getType()->isVectorType() ||
  8411. RHS.get()->getType()->isVectorType()) {
  8412. QualType compType = CheckVectorOperands(
  8413. LHS, RHS, Loc, CompLHSTy,
  8414. /*AllowBothBool*/getLangOpts().AltiVec,
  8415. /*AllowBoolConversions*/getLangOpts().ZVector);
  8416. if (CompLHSTy) *CompLHSTy = compType;
  8417. return compType;
  8418. }
  8419. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8420. if (LHS.isInvalid() || RHS.isInvalid())
  8421. return QualType();
  8422. // Diagnose "string literal" '+' int and string '+' "char literal".
  8423. if (Opc == BO_Add) {
  8424. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8425. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8426. }
  8427. // handle the common case first (both operands are arithmetic).
  8428. if (!compType.isNull() && compType->isArithmeticType()) {
  8429. if (CompLHSTy) *CompLHSTy = compType;
  8430. return compType;
  8431. }
  8432. // Type-checking. Ultimately the pointer's going to be in PExp;
  8433. // note that we bias towards the LHS being the pointer.
  8434. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8435. bool isObjCPointer;
  8436. if (PExp->getType()->isPointerType()) {
  8437. isObjCPointer = false;
  8438. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8439. isObjCPointer = true;
  8440. } else {
  8441. std::swap(PExp, IExp);
  8442. if (PExp->getType()->isPointerType()) {
  8443. isObjCPointer = false;
  8444. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8445. isObjCPointer = true;
  8446. } else {
  8447. return InvalidOperands(Loc, LHS, RHS);
  8448. }
  8449. }
  8450. assert(PExp->getType()->isAnyPointerType());
  8451. if (!IExp->getType()->isIntegerType())
  8452. return InvalidOperands(Loc, LHS, RHS);
  8453. // Adding to a null pointer results in undefined behavior.
  8454. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8455. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8456. // In C++ adding zero to a null pointer is defined.
  8457. Expr::EvalResult KnownVal;
  8458. if (!getLangOpts().CPlusPlus ||
  8459. (!IExp->isValueDependent() &&
  8460. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8461. KnownVal.Val.getInt() != 0))) {
  8462. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8463. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8464. Context, BO_Add, PExp, IExp);
  8465. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8466. }
  8467. }
  8468. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8469. return QualType();
  8470. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8471. return QualType();
  8472. // Check array bounds for pointer arithemtic
  8473. CheckArrayAccess(PExp, IExp);
  8474. if (CompLHSTy) {
  8475. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8476. if (LHSTy.isNull()) {
  8477. LHSTy = LHS.get()->getType();
  8478. if (LHSTy->isPromotableIntegerType())
  8479. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8480. }
  8481. *CompLHSTy = LHSTy;
  8482. }
  8483. return PExp->getType();
  8484. }
  8485. // C99 6.5.6
  8486. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8487. SourceLocation Loc,
  8488. QualType* CompLHSTy) {
  8489. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8490. if (LHS.get()->getType()->isVectorType() ||
  8491. RHS.get()->getType()->isVectorType()) {
  8492. QualType compType = CheckVectorOperands(
  8493. LHS, RHS, Loc, CompLHSTy,
  8494. /*AllowBothBool*/getLangOpts().AltiVec,
  8495. /*AllowBoolConversions*/getLangOpts().ZVector);
  8496. if (CompLHSTy) *CompLHSTy = compType;
  8497. return compType;
  8498. }
  8499. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8500. if (LHS.isInvalid() || RHS.isInvalid())
  8501. return QualType();
  8502. // Enforce type constraints: C99 6.5.6p3.
  8503. // Handle the common case first (both operands are arithmetic).
  8504. if (!compType.isNull() && compType->isArithmeticType()) {
  8505. if (CompLHSTy) *CompLHSTy = compType;
  8506. return compType;
  8507. }
  8508. // Either ptr - int or ptr - ptr.
  8509. if (LHS.get()->getType()->isAnyPointerType()) {
  8510. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8511. // Diagnose bad cases where we step over interface counts.
  8512. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8513. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8514. return QualType();
  8515. // The result type of a pointer-int computation is the pointer type.
  8516. if (RHS.get()->getType()->isIntegerType()) {
  8517. // Subtracting from a null pointer should produce a warning.
  8518. // The last argument to the diagnose call says this doesn't match the
  8519. // GNU int-to-pointer idiom.
  8520. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8521. Expr::NPC_ValueDependentIsNotNull)) {
  8522. // In C++ adding zero to a null pointer is defined.
  8523. Expr::EvalResult KnownVal;
  8524. if (!getLangOpts().CPlusPlus ||
  8525. (!RHS.get()->isValueDependent() &&
  8526. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8527. KnownVal.Val.getInt() != 0))) {
  8528. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8529. }
  8530. }
  8531. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8532. return QualType();
  8533. // Check array bounds for pointer arithemtic
  8534. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8535. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8536. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8537. return LHS.get()->getType();
  8538. }
  8539. // Handle pointer-pointer subtractions.
  8540. if (const PointerType *RHSPTy
  8541. = RHS.get()->getType()->getAs<PointerType>()) {
  8542. QualType rpointee = RHSPTy->getPointeeType();
  8543. if (getLangOpts().CPlusPlus) {
  8544. // Pointee types must be the same: C++ [expr.add]
  8545. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8546. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8547. }
  8548. } else {
  8549. // Pointee types must be compatible C99 6.5.6p3
  8550. if (!Context.typesAreCompatible(
  8551. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8552. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8553. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8554. return QualType();
  8555. }
  8556. }
  8557. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8558. LHS.get(), RHS.get()))
  8559. return QualType();
  8560. // FIXME: Add warnings for nullptr - ptr.
  8561. // The pointee type may have zero size. As an extension, a structure or
  8562. // union may have zero size or an array may have zero length. In this
  8563. // case subtraction does not make sense.
  8564. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8565. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8566. if (ElementSize.isZero()) {
  8567. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8568. << rpointee.getUnqualifiedType()
  8569. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8570. }
  8571. }
  8572. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8573. return Context.getPointerDiffType();
  8574. }
  8575. }
  8576. return InvalidOperands(Loc, LHS, RHS);
  8577. }
  8578. static bool isScopedEnumerationType(QualType T) {
  8579. if (const EnumType *ET = T->getAs<EnumType>())
  8580. return ET->getDecl()->isScoped();
  8581. return false;
  8582. }
  8583. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8584. SourceLocation Loc, BinaryOperatorKind Opc,
  8585. QualType LHSType) {
  8586. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8587. // so skip remaining warnings as we don't want to modify values within Sema.
  8588. if (S.getLangOpts().OpenCL)
  8589. return;
  8590. // Check right/shifter operand
  8591. Expr::EvalResult RHSResult;
  8592. if (RHS.get()->isValueDependent() ||
  8593. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8594. return;
  8595. llvm::APSInt Right = RHSResult.Val.getInt();
  8596. if (Right.isNegative()) {
  8597. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8598. S.PDiag(diag::warn_shift_negative)
  8599. << RHS.get()->getSourceRange());
  8600. return;
  8601. }
  8602. llvm::APInt LeftBits(Right.getBitWidth(),
  8603. S.Context.getTypeSize(LHS.get()->getType()));
  8604. if (Right.uge(LeftBits)) {
  8605. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8606. S.PDiag(diag::warn_shift_gt_typewidth)
  8607. << RHS.get()->getSourceRange());
  8608. return;
  8609. }
  8610. if (Opc != BO_Shl)
  8611. return;
  8612. // When left shifting an ICE which is signed, we can check for overflow which
  8613. // according to C++ standards prior to C++2a has undefined behavior
  8614. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  8615. // more than the maximum value representable in the result type, so never
  8616. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  8617. // expression is still probably a bug.)
  8618. Expr::EvalResult LHSResult;
  8619. if (LHS.get()->isValueDependent() ||
  8620. LHSType->hasUnsignedIntegerRepresentation() ||
  8621. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8622. return;
  8623. llvm::APSInt Left = LHSResult.Val.getInt();
  8624. // If LHS does not have a signed type and non-negative value
  8625. // then, the behavior is undefined before C++2a. Warn about it.
  8626. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  8627. !S.getLangOpts().CPlusPlus2a) {
  8628. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8629. S.PDiag(diag::warn_shift_lhs_negative)
  8630. << LHS.get()->getSourceRange());
  8631. return;
  8632. }
  8633. llvm::APInt ResultBits =
  8634. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8635. if (LeftBits.uge(ResultBits))
  8636. return;
  8637. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8638. Result = Result.shl(Right);
  8639. // Print the bit representation of the signed integer as an unsigned
  8640. // hexadecimal number.
  8641. SmallString<40> HexResult;
  8642. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8643. // If we are only missing a sign bit, this is less likely to result in actual
  8644. // bugs -- if the result is cast back to an unsigned type, it will have the
  8645. // expected value. Thus we place this behind a different warning that can be
  8646. // turned off separately if needed.
  8647. if (LeftBits == ResultBits - 1) {
  8648. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8649. << HexResult << LHSType
  8650. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8651. return;
  8652. }
  8653. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8654. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8655. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8656. << RHS.get()->getSourceRange();
  8657. }
  8658. /// Return the resulting type when a vector is shifted
  8659. /// by a scalar or vector shift amount.
  8660. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8661. SourceLocation Loc, bool IsCompAssign) {
  8662. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8663. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8664. !LHS.get()->getType()->isVectorType()) {
  8665. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8666. << RHS.get()->getType() << LHS.get()->getType()
  8667. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8668. return QualType();
  8669. }
  8670. if (!IsCompAssign) {
  8671. LHS = S.UsualUnaryConversions(LHS.get());
  8672. if (LHS.isInvalid()) return QualType();
  8673. }
  8674. RHS = S.UsualUnaryConversions(RHS.get());
  8675. if (RHS.isInvalid()) return QualType();
  8676. QualType LHSType = LHS.get()->getType();
  8677. // Note that LHS might be a scalar because the routine calls not only in
  8678. // OpenCL case.
  8679. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8680. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8681. // Note that RHS might not be a vector.
  8682. QualType RHSType = RHS.get()->getType();
  8683. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8684. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8685. // The operands need to be integers.
  8686. if (!LHSEleType->isIntegerType()) {
  8687. S.Diag(Loc, diag::err_typecheck_expect_int)
  8688. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8689. return QualType();
  8690. }
  8691. if (!RHSEleType->isIntegerType()) {
  8692. S.Diag(Loc, diag::err_typecheck_expect_int)
  8693. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8694. return QualType();
  8695. }
  8696. if (!LHSVecTy) {
  8697. assert(RHSVecTy);
  8698. if (IsCompAssign)
  8699. return RHSType;
  8700. if (LHSEleType != RHSEleType) {
  8701. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8702. LHSEleType = RHSEleType;
  8703. }
  8704. QualType VecTy =
  8705. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8706. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8707. LHSType = VecTy;
  8708. } else if (RHSVecTy) {
  8709. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8710. // are applied component-wise. So if RHS is a vector, then ensure
  8711. // that the number of elements is the same as LHS...
  8712. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8713. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8714. << LHS.get()->getType() << RHS.get()->getType()
  8715. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8716. return QualType();
  8717. }
  8718. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8719. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8720. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8721. if (LHSBT != RHSBT &&
  8722. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8723. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8724. << LHS.get()->getType() << RHS.get()->getType()
  8725. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8726. }
  8727. }
  8728. } else {
  8729. // ...else expand RHS to match the number of elements in LHS.
  8730. QualType VecTy =
  8731. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8732. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8733. }
  8734. return LHSType;
  8735. }
  8736. // C99 6.5.7
  8737. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8738. SourceLocation Loc, BinaryOperatorKind Opc,
  8739. bool IsCompAssign) {
  8740. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8741. // Vector shifts promote their scalar inputs to vector type.
  8742. if (LHS.get()->getType()->isVectorType() ||
  8743. RHS.get()->getType()->isVectorType()) {
  8744. if (LangOpts.ZVector) {
  8745. // The shift operators for the z vector extensions work basically
  8746. // like general shifts, except that neither the LHS nor the RHS is
  8747. // allowed to be a "vector bool".
  8748. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8749. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8750. return InvalidOperands(Loc, LHS, RHS);
  8751. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8752. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8753. return InvalidOperands(Loc, LHS, RHS);
  8754. }
  8755. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8756. }
  8757. // Shifts don't perform usual arithmetic conversions, they just do integer
  8758. // promotions on each operand. C99 6.5.7p3
  8759. // For the LHS, do usual unary conversions, but then reset them away
  8760. // if this is a compound assignment.
  8761. ExprResult OldLHS = LHS;
  8762. LHS = UsualUnaryConversions(LHS.get());
  8763. if (LHS.isInvalid())
  8764. return QualType();
  8765. QualType LHSType = LHS.get()->getType();
  8766. if (IsCompAssign) LHS = OldLHS;
  8767. // The RHS is simpler.
  8768. RHS = UsualUnaryConversions(RHS.get());
  8769. if (RHS.isInvalid())
  8770. return QualType();
  8771. QualType RHSType = RHS.get()->getType();
  8772. // C99 6.5.7p2: Each of the operands shall have integer type.
  8773. if (!LHSType->hasIntegerRepresentation() ||
  8774. !RHSType->hasIntegerRepresentation())
  8775. return InvalidOperands(Loc, LHS, RHS);
  8776. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8777. // hasIntegerRepresentation() above instead of this.
  8778. if (isScopedEnumerationType(LHSType) ||
  8779. isScopedEnumerationType(RHSType)) {
  8780. return InvalidOperands(Loc, LHS, RHS);
  8781. }
  8782. // Sanity-check shift operands
  8783. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8784. // "The type of the result is that of the promoted left operand."
  8785. return LHSType;
  8786. }
  8787. /// If two different enums are compared, raise a warning.
  8788. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8789. Expr *RHS) {
  8790. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8791. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8792. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8793. if (!LHSEnumType)
  8794. return;
  8795. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8796. if (!RHSEnumType)
  8797. return;
  8798. // Ignore anonymous enums.
  8799. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8800. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8801. return;
  8802. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8803. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8804. return;
  8805. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8806. return;
  8807. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8808. << LHSStrippedType << RHSStrippedType
  8809. << LHS->getSourceRange() << RHS->getSourceRange();
  8810. }
  8811. /// Diagnose bad pointer comparisons.
  8812. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8813. ExprResult &LHS, ExprResult &RHS,
  8814. bool IsError) {
  8815. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8816. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8817. << LHS.get()->getType() << RHS.get()->getType()
  8818. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8819. }
  8820. /// Returns false if the pointers are converted to a composite type,
  8821. /// true otherwise.
  8822. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8823. ExprResult &LHS, ExprResult &RHS) {
  8824. // C++ [expr.rel]p2:
  8825. // [...] Pointer conversions (4.10) and qualification
  8826. // conversions (4.4) are performed on pointer operands (or on
  8827. // a pointer operand and a null pointer constant) to bring
  8828. // them to their composite pointer type. [...]
  8829. //
  8830. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8831. // comparisons of pointers.
  8832. QualType LHSType = LHS.get()->getType();
  8833. QualType RHSType = RHS.get()->getType();
  8834. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8835. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8836. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8837. if (T.isNull()) {
  8838. if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
  8839. (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
  8840. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8841. else
  8842. S.InvalidOperands(Loc, LHS, RHS);
  8843. return true;
  8844. }
  8845. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8846. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8847. return false;
  8848. }
  8849. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8850. ExprResult &LHS,
  8851. ExprResult &RHS,
  8852. bool IsError) {
  8853. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8854. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8855. << LHS.get()->getType() << RHS.get()->getType()
  8856. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8857. }
  8858. static bool isObjCObjectLiteral(ExprResult &E) {
  8859. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8860. case Stmt::ObjCArrayLiteralClass:
  8861. case Stmt::ObjCDictionaryLiteralClass:
  8862. case Stmt::ObjCStringLiteralClass:
  8863. case Stmt::ObjCBoxedExprClass:
  8864. return true;
  8865. default:
  8866. // Note that ObjCBoolLiteral is NOT an object literal!
  8867. return false;
  8868. }
  8869. }
  8870. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8871. const ObjCObjectPointerType *Type =
  8872. LHS->getType()->getAs<ObjCObjectPointerType>();
  8873. // If this is not actually an Objective-C object, bail out.
  8874. if (!Type)
  8875. return false;
  8876. // Get the LHS object's interface type.
  8877. QualType InterfaceType = Type->getPointeeType();
  8878. // If the RHS isn't an Objective-C object, bail out.
  8879. if (!RHS->getType()->isObjCObjectPointerType())
  8880. return false;
  8881. // Try to find the -isEqual: method.
  8882. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8883. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8884. InterfaceType,
  8885. /*IsInstance=*/true);
  8886. if (!Method) {
  8887. if (Type->isObjCIdType()) {
  8888. // For 'id', just check the global pool.
  8889. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8890. /*receiverId=*/true);
  8891. } else {
  8892. // Check protocols.
  8893. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8894. /*IsInstance=*/true);
  8895. }
  8896. }
  8897. if (!Method)
  8898. return false;
  8899. QualType T = Method->parameters()[0]->getType();
  8900. if (!T->isObjCObjectPointerType())
  8901. return false;
  8902. QualType R = Method->getReturnType();
  8903. if (!R->isScalarType())
  8904. return false;
  8905. return true;
  8906. }
  8907. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8908. FromE = FromE->IgnoreParenImpCasts();
  8909. switch (FromE->getStmtClass()) {
  8910. default:
  8911. break;
  8912. case Stmt::ObjCStringLiteralClass:
  8913. // "string literal"
  8914. return LK_String;
  8915. case Stmt::ObjCArrayLiteralClass:
  8916. // "array literal"
  8917. return LK_Array;
  8918. case Stmt::ObjCDictionaryLiteralClass:
  8919. // "dictionary literal"
  8920. return LK_Dictionary;
  8921. case Stmt::BlockExprClass:
  8922. return LK_Block;
  8923. case Stmt::ObjCBoxedExprClass: {
  8924. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8925. switch (Inner->getStmtClass()) {
  8926. case Stmt::IntegerLiteralClass:
  8927. case Stmt::FloatingLiteralClass:
  8928. case Stmt::CharacterLiteralClass:
  8929. case Stmt::ObjCBoolLiteralExprClass:
  8930. case Stmt::CXXBoolLiteralExprClass:
  8931. // "numeric literal"
  8932. return LK_Numeric;
  8933. case Stmt::ImplicitCastExprClass: {
  8934. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8935. // Boolean literals can be represented by implicit casts.
  8936. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8937. return LK_Numeric;
  8938. break;
  8939. }
  8940. default:
  8941. break;
  8942. }
  8943. return LK_Boxed;
  8944. }
  8945. }
  8946. return LK_None;
  8947. }
  8948. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8949. ExprResult &LHS, ExprResult &RHS,
  8950. BinaryOperator::Opcode Opc){
  8951. Expr *Literal;
  8952. Expr *Other;
  8953. if (isObjCObjectLiteral(LHS)) {
  8954. Literal = LHS.get();
  8955. Other = RHS.get();
  8956. } else {
  8957. Literal = RHS.get();
  8958. Other = LHS.get();
  8959. }
  8960. // Don't warn on comparisons against nil.
  8961. Other = Other->IgnoreParenCasts();
  8962. if (Other->isNullPointerConstant(S.getASTContext(),
  8963. Expr::NPC_ValueDependentIsNotNull))
  8964. return;
  8965. // This should be kept in sync with warn_objc_literal_comparison.
  8966. // LK_String should always be after the other literals, since it has its own
  8967. // warning flag.
  8968. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8969. assert(LiteralKind != Sema::LK_Block);
  8970. if (LiteralKind == Sema::LK_None) {
  8971. llvm_unreachable("Unknown Objective-C object literal kind");
  8972. }
  8973. if (LiteralKind == Sema::LK_String)
  8974. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8975. << Literal->getSourceRange();
  8976. else
  8977. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8978. << LiteralKind << Literal->getSourceRange();
  8979. if (BinaryOperator::isEqualityOp(Opc) &&
  8980. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8981. SourceLocation Start = LHS.get()->getBeginLoc();
  8982. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8983. CharSourceRange OpRange =
  8984. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8985. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8986. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8987. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8988. << FixItHint::CreateInsertion(End, "]");
  8989. }
  8990. }
  8991. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8992. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8993. ExprResult &RHS, SourceLocation Loc,
  8994. BinaryOperatorKind Opc) {
  8995. // Check that left hand side is !something.
  8996. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8997. if (!UO || UO->getOpcode() != UO_LNot) return;
  8998. // Only check if the right hand side is non-bool arithmetic type.
  8999. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  9000. // Make sure that the something in !something is not bool.
  9001. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  9002. if (SubExpr->isKnownToHaveBooleanValue()) return;
  9003. // Emit warning.
  9004. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  9005. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  9006. << Loc << IsBitwiseOp;
  9007. // First note suggest !(x < y)
  9008. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  9009. SourceLocation FirstClose = RHS.get()->getEndLoc();
  9010. FirstClose = S.getLocForEndOfToken(FirstClose);
  9011. if (FirstClose.isInvalid())
  9012. FirstOpen = SourceLocation();
  9013. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  9014. << IsBitwiseOp
  9015. << FixItHint::CreateInsertion(FirstOpen, "(")
  9016. << FixItHint::CreateInsertion(FirstClose, ")");
  9017. // Second note suggests (!x) < y
  9018. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  9019. SourceLocation SecondClose = LHS.get()->getEndLoc();
  9020. SecondClose = S.getLocForEndOfToken(SecondClose);
  9021. if (SecondClose.isInvalid())
  9022. SecondOpen = SourceLocation();
  9023. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  9024. << FixItHint::CreateInsertion(SecondOpen, "(")
  9025. << FixItHint::CreateInsertion(SecondClose, ")");
  9026. }
  9027. // Returns true if E refers to a non-weak array.
  9028. static bool checkForArray(const Expr *E) {
  9029. const ValueDecl *D = nullptr;
  9030. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  9031. D = DR->getDecl();
  9032. } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  9033. if (Mem->isImplicitAccess())
  9034. D = Mem->getMemberDecl();
  9035. }
  9036. if (!D)
  9037. return false;
  9038. return D->getType()->isArrayType() && !D->isWeak();
  9039. }
  9040. /// Diagnose some forms of syntactically-obvious tautological comparison.
  9041. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  9042. Expr *LHS, Expr *RHS,
  9043. BinaryOperatorKind Opc) {
  9044. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  9045. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  9046. QualType LHSType = LHS->getType();
  9047. QualType RHSType = RHS->getType();
  9048. if (LHSType->hasFloatingRepresentation() ||
  9049. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  9050. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  9051. S.inTemplateInstantiation())
  9052. return;
  9053. // Comparisons between two array types are ill-formed for operator<=>, so
  9054. // we shouldn't emit any additional warnings about it.
  9055. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  9056. return;
  9057. // For non-floating point types, check for self-comparisons of the form
  9058. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9059. // often indicate logic errors in the program.
  9060. //
  9061. // NOTE: Don't warn about comparison expressions resulting from macro
  9062. // expansion. Also don't warn about comparisons which are only self
  9063. // comparisons within a template instantiation. The warnings should catch
  9064. // obvious cases in the definition of the template anyways. The idea is to
  9065. // warn when the typed comparison operator will always evaluate to the same
  9066. // result.
  9067. // Used for indexing into %select in warn_comparison_always
  9068. enum {
  9069. AlwaysConstant,
  9070. AlwaysTrue,
  9071. AlwaysFalse,
  9072. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  9073. };
  9074. if (Expr::isSameComparisonOperand(LHS, RHS)) {
  9075. unsigned Result;
  9076. switch (Opc) {
  9077. case BO_EQ: case BO_LE: case BO_GE:
  9078. Result = AlwaysTrue;
  9079. break;
  9080. case BO_NE: case BO_LT: case BO_GT:
  9081. Result = AlwaysFalse;
  9082. break;
  9083. case BO_Cmp:
  9084. Result = AlwaysEqual;
  9085. break;
  9086. default:
  9087. Result = AlwaysConstant;
  9088. break;
  9089. }
  9090. S.DiagRuntimeBehavior(Loc, nullptr,
  9091. S.PDiag(diag::warn_comparison_always)
  9092. << 0 /*self-comparison*/
  9093. << Result);
  9094. } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
  9095. // What is it always going to evaluate to?
  9096. unsigned Result;
  9097. switch(Opc) {
  9098. case BO_EQ: // e.g. array1 == array2
  9099. Result = AlwaysFalse;
  9100. break;
  9101. case BO_NE: // e.g. array1 != array2
  9102. Result = AlwaysTrue;
  9103. break;
  9104. default: // e.g. array1 <= array2
  9105. // The best we can say is 'a constant'
  9106. Result = AlwaysConstant;
  9107. break;
  9108. }
  9109. S.DiagRuntimeBehavior(Loc, nullptr,
  9110. S.PDiag(diag::warn_comparison_always)
  9111. << 1 /*array comparison*/
  9112. << Result);
  9113. }
  9114. if (isa<CastExpr>(LHSStripped))
  9115. LHSStripped = LHSStripped->IgnoreParenCasts();
  9116. if (isa<CastExpr>(RHSStripped))
  9117. RHSStripped = RHSStripped->IgnoreParenCasts();
  9118. // Warn about comparisons against a string constant (unless the other
  9119. // operand is null); the user probably wants strcmp.
  9120. Expr *LiteralString = nullptr;
  9121. Expr *LiteralStringStripped = nullptr;
  9122. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  9123. !RHSStripped->isNullPointerConstant(S.Context,
  9124. Expr::NPC_ValueDependentIsNull)) {
  9125. LiteralString = LHS;
  9126. LiteralStringStripped = LHSStripped;
  9127. } else if ((isa<StringLiteral>(RHSStripped) ||
  9128. isa<ObjCEncodeExpr>(RHSStripped)) &&
  9129. !LHSStripped->isNullPointerConstant(S.Context,
  9130. Expr::NPC_ValueDependentIsNull)) {
  9131. LiteralString = RHS;
  9132. LiteralStringStripped = RHSStripped;
  9133. }
  9134. if (LiteralString) {
  9135. S.DiagRuntimeBehavior(Loc, nullptr,
  9136. S.PDiag(diag::warn_stringcompare)
  9137. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  9138. << LiteralString->getSourceRange());
  9139. }
  9140. }
  9141. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  9142. switch (CK) {
  9143. default: {
  9144. #ifndef NDEBUG
  9145. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  9146. << "\n";
  9147. #endif
  9148. llvm_unreachable("unhandled cast kind");
  9149. }
  9150. case CK_UserDefinedConversion:
  9151. return ICK_Identity;
  9152. case CK_LValueToRValue:
  9153. return ICK_Lvalue_To_Rvalue;
  9154. case CK_ArrayToPointerDecay:
  9155. return ICK_Array_To_Pointer;
  9156. case CK_FunctionToPointerDecay:
  9157. return ICK_Function_To_Pointer;
  9158. case CK_IntegralCast:
  9159. return ICK_Integral_Conversion;
  9160. case CK_FloatingCast:
  9161. return ICK_Floating_Conversion;
  9162. case CK_IntegralToFloating:
  9163. case CK_FloatingToIntegral:
  9164. return ICK_Floating_Integral;
  9165. case CK_IntegralComplexCast:
  9166. case CK_FloatingComplexCast:
  9167. case CK_FloatingComplexToIntegralComplex:
  9168. case CK_IntegralComplexToFloatingComplex:
  9169. return ICK_Complex_Conversion;
  9170. case CK_FloatingComplexToReal:
  9171. case CK_FloatingRealToComplex:
  9172. case CK_IntegralComplexToReal:
  9173. case CK_IntegralRealToComplex:
  9174. return ICK_Complex_Real;
  9175. }
  9176. }
  9177. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  9178. QualType FromType,
  9179. SourceLocation Loc) {
  9180. // Check for a narrowing implicit conversion.
  9181. StandardConversionSequence SCS;
  9182. SCS.setAsIdentityConversion();
  9183. SCS.setToType(0, FromType);
  9184. SCS.setToType(1, ToType);
  9185. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9186. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  9187. APValue PreNarrowingValue;
  9188. QualType PreNarrowingType;
  9189. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  9190. PreNarrowingType,
  9191. /*IgnoreFloatToIntegralConversion*/ true)) {
  9192. case NK_Dependent_Narrowing:
  9193. // Implicit conversion to a narrower type, but the expression is
  9194. // value-dependent so we can't tell whether it's actually narrowing.
  9195. case NK_Not_Narrowing:
  9196. return false;
  9197. case NK_Constant_Narrowing:
  9198. // Implicit conversion to a narrower type, and the value is not a constant
  9199. // expression.
  9200. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9201. << /*Constant*/ 1
  9202. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  9203. return true;
  9204. case NK_Variable_Narrowing:
  9205. // Implicit conversion to a narrower type, and the value is not a constant
  9206. // expression.
  9207. case NK_Type_Narrowing:
  9208. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9209. << /*Constant*/ 0 << FromType << ToType;
  9210. // TODO: It's not a constant expression, but what if the user intended it
  9211. // to be? Can we produce notes to help them figure out why it isn't?
  9212. return true;
  9213. }
  9214. llvm_unreachable("unhandled case in switch");
  9215. }
  9216. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9217. ExprResult &LHS,
  9218. ExprResult &RHS,
  9219. SourceLocation Loc) {
  9220. using CCT = ComparisonCategoryType;
  9221. QualType LHSType = LHS.get()->getType();
  9222. QualType RHSType = RHS.get()->getType();
  9223. // Dig out the original argument type and expression before implicit casts
  9224. // were applied. These are the types/expressions we need to check the
  9225. // [expr.spaceship] requirements against.
  9226. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9227. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9228. QualType LHSStrippedType = LHSStripped.get()->getType();
  9229. QualType RHSStrippedType = RHSStripped.get()->getType();
  9230. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9231. // other is not, the program is ill-formed.
  9232. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9233. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9234. return QualType();
  9235. }
  9236. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9237. RHSStrippedType->isEnumeralType();
  9238. if (NumEnumArgs == 1) {
  9239. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9240. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9241. if (OtherTy->hasFloatingRepresentation()) {
  9242. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9243. return QualType();
  9244. }
  9245. }
  9246. if (NumEnumArgs == 2) {
  9247. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9248. // type E, the operator yields the result of converting the operands
  9249. // to the underlying type of E and applying <=> to the converted operands.
  9250. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9251. S.InvalidOperands(Loc, LHS, RHS);
  9252. return QualType();
  9253. }
  9254. QualType IntType =
  9255. LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
  9256. assert(IntType->isArithmeticType());
  9257. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9258. // promote the boolean type, and all other promotable integer types, to
  9259. // avoid this.
  9260. if (IntType->isPromotableIntegerType())
  9261. IntType = S.Context.getPromotedIntegerType(IntType);
  9262. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9263. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9264. LHSType = RHSType = IntType;
  9265. }
  9266. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9267. // usual arithmetic conversions are applied to the operands.
  9268. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9269. if (LHS.isInvalid() || RHS.isInvalid())
  9270. return QualType();
  9271. if (Type.isNull())
  9272. return S.InvalidOperands(Loc, LHS, RHS);
  9273. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9274. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9275. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9276. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9277. RHS.get()->getBeginLoc());
  9278. if (HasNarrowing)
  9279. return QualType();
  9280. assert(!Type.isNull() && "composite type for <=> has not been set");
  9281. auto TypeKind = [&]() {
  9282. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9283. if (CT->getElementType()->hasFloatingRepresentation())
  9284. return CCT::WeakEquality;
  9285. return CCT::StrongEquality;
  9286. }
  9287. if (Type->isIntegralOrEnumerationType())
  9288. return CCT::StrongOrdering;
  9289. if (Type->hasFloatingRepresentation())
  9290. return CCT::PartialOrdering;
  9291. llvm_unreachable("other types are unimplemented");
  9292. }();
  9293. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9294. }
  9295. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9296. ExprResult &RHS,
  9297. SourceLocation Loc,
  9298. BinaryOperatorKind Opc) {
  9299. if (Opc == BO_Cmp)
  9300. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9301. // C99 6.5.8p3 / C99 6.5.9p4
  9302. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9303. if (LHS.isInvalid() || RHS.isInvalid())
  9304. return QualType();
  9305. if (Type.isNull())
  9306. return S.InvalidOperands(Loc, LHS, RHS);
  9307. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9308. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9309. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9310. return S.InvalidOperands(Loc, LHS, RHS);
  9311. // Check for comparisons of floating point operands using != and ==.
  9312. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9313. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9314. // The result of comparisons is 'bool' in C++, 'int' in C.
  9315. return S.Context.getLogicalOperationType();
  9316. }
  9317. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  9318. if (!NullE.get()->getType()->isAnyPointerType())
  9319. return;
  9320. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  9321. if (!E.get()->getType()->isAnyPointerType() &&
  9322. E.get()->isNullPointerConstant(Context,
  9323. Expr::NPC_ValueDependentIsNotNull) ==
  9324. Expr::NPCK_ZeroExpression) {
  9325. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  9326. if (CL->getValue() == 0)
  9327. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9328. << NullValue
  9329. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9330. NullValue ? "NULL" : "(void *)0");
  9331. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  9332. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  9333. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  9334. if (T == Context.CharTy)
  9335. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9336. << NullValue
  9337. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9338. NullValue ? "NULL" : "(void *)0");
  9339. }
  9340. }
  9341. }
  9342. // C99 6.5.8, C++ [expr.rel]
  9343. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9344. SourceLocation Loc,
  9345. BinaryOperatorKind Opc) {
  9346. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9347. bool IsThreeWay = Opc == BO_Cmp;
  9348. auto IsAnyPointerType = [](ExprResult E) {
  9349. QualType Ty = E.get()->getType();
  9350. return Ty->isPointerType() || Ty->isMemberPointerType();
  9351. };
  9352. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9353. // type, array-to-pointer, ..., conversions are performed on both operands to
  9354. // bring them to their composite type.
  9355. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9356. // any type-related checks.
  9357. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9358. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9359. if (LHS.isInvalid())
  9360. return QualType();
  9361. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9362. if (RHS.isInvalid())
  9363. return QualType();
  9364. } else {
  9365. LHS = DefaultLvalueConversion(LHS.get());
  9366. if (LHS.isInvalid())
  9367. return QualType();
  9368. RHS = DefaultLvalueConversion(RHS.get());
  9369. if (RHS.isInvalid())
  9370. return QualType();
  9371. }
  9372. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  9373. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  9374. CheckPtrComparisonWithNullChar(LHS, RHS);
  9375. CheckPtrComparisonWithNullChar(RHS, LHS);
  9376. }
  9377. // Handle vector comparisons separately.
  9378. if (LHS.get()->getType()->isVectorType() ||
  9379. RHS.get()->getType()->isVectorType())
  9380. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9381. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9382. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9383. QualType LHSType = LHS.get()->getType();
  9384. QualType RHSType = RHS.get()->getType();
  9385. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9386. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9387. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9388. const Expr::NullPointerConstantKind LHSNullKind =
  9389. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9390. const Expr::NullPointerConstantKind RHSNullKind =
  9391. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9392. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9393. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9394. auto computeResultTy = [&]() {
  9395. if (Opc != BO_Cmp)
  9396. return Context.getLogicalOperationType();
  9397. assert(getLangOpts().CPlusPlus);
  9398. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9399. QualType CompositeTy = LHS.get()->getType();
  9400. assert(!CompositeTy->isReferenceType());
  9401. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9402. return CheckComparisonCategoryType(Kind, Loc);
  9403. };
  9404. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9405. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9406. // result is of type std::strong_equality
  9407. if (CompositeTy->isFunctionPointerType() ||
  9408. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9409. // FIXME: consider making the function pointer case produce
  9410. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9411. // and direction polls
  9412. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9413. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9414. // pointer type, p <=> q is of type std::strong_ordering.
  9415. if (CompositeTy->isPointerType()) {
  9416. // P0946R0: Comparisons between a null pointer constant and an object
  9417. // pointer result in std::strong_equality
  9418. if (LHSIsNull != RHSIsNull)
  9419. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9420. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9421. }
  9422. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9423. // TODO: Extend support for operator<=> to ObjC types.
  9424. return InvalidOperands(Loc, LHS, RHS);
  9425. };
  9426. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9427. bool IsEquality = Opc == BO_EQ;
  9428. if (RHSIsNull)
  9429. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9430. RHS.get()->getSourceRange());
  9431. else
  9432. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9433. LHS.get()->getSourceRange());
  9434. }
  9435. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9436. (RHSType->isIntegerType() && !RHSIsNull)) {
  9437. // Skip normal pointer conversion checks in this case; we have better
  9438. // diagnostics for this below.
  9439. } else if (getLangOpts().CPlusPlus) {
  9440. // Equality comparison of a function pointer to a void pointer is invalid,
  9441. // but we allow it as an extension.
  9442. // FIXME: If we really want to allow this, should it be part of composite
  9443. // pointer type computation so it works in conditionals too?
  9444. if (!IsRelational &&
  9445. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9446. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9447. // This is a gcc extension compatibility comparison.
  9448. // In a SFINAE context, we treat this as a hard error to maintain
  9449. // conformance with the C++ standard.
  9450. diagnoseFunctionPointerToVoidComparison(
  9451. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9452. if (isSFINAEContext())
  9453. return QualType();
  9454. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9455. return computeResultTy();
  9456. }
  9457. // C++ [expr.eq]p2:
  9458. // If at least one operand is a pointer [...] bring them to their
  9459. // composite pointer type.
  9460. // C++ [expr.spaceship]p6
  9461. // If at least one of the operands is of pointer type, [...] bring them
  9462. // to their composite pointer type.
  9463. // C++ [expr.rel]p2:
  9464. // If both operands are pointers, [...] bring them to their composite
  9465. // pointer type.
  9466. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9467. (IsRelational ? 2 : 1) &&
  9468. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9469. RHSType->isObjCObjectPointerType()))) {
  9470. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9471. return QualType();
  9472. return computeResultTy();
  9473. }
  9474. } else if (LHSType->isPointerType() &&
  9475. RHSType->isPointerType()) { // C99 6.5.8p2
  9476. // All of the following pointer-related warnings are GCC extensions, except
  9477. // when handling null pointer constants.
  9478. QualType LCanPointeeTy =
  9479. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9480. QualType RCanPointeeTy =
  9481. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9482. // C99 6.5.9p2 and C99 6.5.8p2
  9483. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9484. RCanPointeeTy.getUnqualifiedType())) {
  9485. // Valid unless a relational comparison of function pointers
  9486. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9487. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9488. << LHSType << RHSType << LHS.get()->getSourceRange()
  9489. << RHS.get()->getSourceRange();
  9490. }
  9491. } else if (!IsRelational &&
  9492. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9493. // Valid unless comparison between non-null pointer and function pointer
  9494. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9495. && !LHSIsNull && !RHSIsNull)
  9496. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9497. /*isError*/false);
  9498. } else {
  9499. // Invalid
  9500. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9501. }
  9502. if (LCanPointeeTy != RCanPointeeTy) {
  9503. // Treat NULL constant as a special case in OpenCL.
  9504. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9505. const PointerType *LHSPtr = LHSType->castAs<PointerType>();
  9506. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
  9507. Diag(Loc,
  9508. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9509. << LHSType << RHSType << 0 /* comparison */
  9510. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9511. }
  9512. }
  9513. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9514. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9515. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9516. : CK_BitCast;
  9517. if (LHSIsNull && !RHSIsNull)
  9518. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9519. else
  9520. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9521. }
  9522. return computeResultTy();
  9523. }
  9524. if (getLangOpts().CPlusPlus) {
  9525. // C++ [expr.eq]p4:
  9526. // Two operands of type std::nullptr_t or one operand of type
  9527. // std::nullptr_t and the other a null pointer constant compare equal.
  9528. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9529. if (LHSType->isNullPtrType()) {
  9530. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9531. return computeResultTy();
  9532. }
  9533. if (RHSType->isNullPtrType()) {
  9534. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9535. return computeResultTy();
  9536. }
  9537. }
  9538. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9539. // These aren't covered by the composite pointer type rules.
  9540. if (!IsRelational && RHSType->isNullPtrType() &&
  9541. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9542. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9543. return computeResultTy();
  9544. }
  9545. if (!IsRelational && LHSType->isNullPtrType() &&
  9546. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9547. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9548. return computeResultTy();
  9549. }
  9550. if (IsRelational &&
  9551. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9552. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9553. // HACK: Relational comparison of nullptr_t against a pointer type is
  9554. // invalid per DR583, but we allow it within std::less<> and friends,
  9555. // since otherwise common uses of it break.
  9556. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9557. // friends to have std::nullptr_t overload candidates.
  9558. DeclContext *DC = CurContext;
  9559. if (isa<FunctionDecl>(DC))
  9560. DC = DC->getParent();
  9561. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9562. if (CTSD->isInStdNamespace() &&
  9563. llvm::StringSwitch<bool>(CTSD->getName())
  9564. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9565. .Default(false)) {
  9566. if (RHSType->isNullPtrType())
  9567. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9568. else
  9569. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9570. return computeResultTy();
  9571. }
  9572. }
  9573. }
  9574. // C++ [expr.eq]p2:
  9575. // If at least one operand is a pointer to member, [...] bring them to
  9576. // their composite pointer type.
  9577. if (!IsRelational &&
  9578. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9579. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9580. return QualType();
  9581. else
  9582. return computeResultTy();
  9583. }
  9584. }
  9585. // Handle block pointer types.
  9586. if (!IsRelational && LHSType->isBlockPointerType() &&
  9587. RHSType->isBlockPointerType()) {
  9588. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9589. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9590. if (!LHSIsNull && !RHSIsNull &&
  9591. !Context.typesAreCompatible(lpointee, rpointee)) {
  9592. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9593. << LHSType << RHSType << LHS.get()->getSourceRange()
  9594. << RHS.get()->getSourceRange();
  9595. }
  9596. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9597. return computeResultTy();
  9598. }
  9599. // Allow block pointers to be compared with null pointer constants.
  9600. if (!IsRelational
  9601. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9602. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9603. if (!LHSIsNull && !RHSIsNull) {
  9604. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9605. ->getPointeeType()->isVoidType())
  9606. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9607. ->getPointeeType()->isVoidType())))
  9608. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9609. << LHSType << RHSType << LHS.get()->getSourceRange()
  9610. << RHS.get()->getSourceRange();
  9611. }
  9612. if (LHSIsNull && !RHSIsNull)
  9613. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9614. RHSType->isPointerType() ? CK_BitCast
  9615. : CK_AnyPointerToBlockPointerCast);
  9616. else
  9617. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9618. LHSType->isPointerType() ? CK_BitCast
  9619. : CK_AnyPointerToBlockPointerCast);
  9620. return computeResultTy();
  9621. }
  9622. if (LHSType->isObjCObjectPointerType() ||
  9623. RHSType->isObjCObjectPointerType()) {
  9624. const PointerType *LPT = LHSType->getAs<PointerType>();
  9625. const PointerType *RPT = RHSType->getAs<PointerType>();
  9626. if (LPT || RPT) {
  9627. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9628. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9629. if (!LPtrToVoid && !RPtrToVoid &&
  9630. !Context.typesAreCompatible(LHSType, RHSType)) {
  9631. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9632. /*isError*/false);
  9633. }
  9634. if (LHSIsNull && !RHSIsNull) {
  9635. Expr *E = LHS.get();
  9636. if (getLangOpts().ObjCAutoRefCount)
  9637. CheckObjCConversion(SourceRange(), RHSType, E,
  9638. CCK_ImplicitConversion);
  9639. LHS = ImpCastExprToType(E, RHSType,
  9640. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9641. }
  9642. else {
  9643. Expr *E = RHS.get();
  9644. if (getLangOpts().ObjCAutoRefCount)
  9645. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9646. /*Diagnose=*/true,
  9647. /*DiagnoseCFAudited=*/false, Opc);
  9648. RHS = ImpCastExprToType(E, LHSType,
  9649. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9650. }
  9651. return computeResultTy();
  9652. }
  9653. if (LHSType->isObjCObjectPointerType() &&
  9654. RHSType->isObjCObjectPointerType()) {
  9655. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9656. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9657. /*isError*/false);
  9658. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9659. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9660. if (LHSIsNull && !RHSIsNull)
  9661. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9662. else
  9663. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9664. return computeResultTy();
  9665. }
  9666. if (!IsRelational && LHSType->isBlockPointerType() &&
  9667. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9668. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9669. CK_BlockPointerToObjCPointerCast);
  9670. return computeResultTy();
  9671. } else if (!IsRelational &&
  9672. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9673. RHSType->isBlockPointerType()) {
  9674. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9675. CK_BlockPointerToObjCPointerCast);
  9676. return computeResultTy();
  9677. }
  9678. }
  9679. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9680. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9681. unsigned DiagID = 0;
  9682. bool isError = false;
  9683. if (LangOpts.DebuggerSupport) {
  9684. // Under a debugger, allow the comparison of pointers to integers,
  9685. // since users tend to want to compare addresses.
  9686. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9687. (RHSIsNull && RHSType->isIntegerType())) {
  9688. if (IsRelational) {
  9689. isError = getLangOpts().CPlusPlus;
  9690. DiagID =
  9691. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9692. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9693. }
  9694. } else if (getLangOpts().CPlusPlus) {
  9695. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9696. isError = true;
  9697. } else if (IsRelational)
  9698. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9699. else
  9700. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9701. if (DiagID) {
  9702. Diag(Loc, DiagID)
  9703. << LHSType << RHSType << LHS.get()->getSourceRange()
  9704. << RHS.get()->getSourceRange();
  9705. if (isError)
  9706. return QualType();
  9707. }
  9708. if (LHSType->isIntegerType())
  9709. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9710. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9711. else
  9712. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9713. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9714. return computeResultTy();
  9715. }
  9716. // Handle block pointers.
  9717. if (!IsRelational && RHSIsNull
  9718. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9719. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9720. return computeResultTy();
  9721. }
  9722. if (!IsRelational && LHSIsNull
  9723. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9724. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9725. return computeResultTy();
  9726. }
  9727. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9728. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9729. return computeResultTy();
  9730. }
  9731. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9732. return computeResultTy();
  9733. }
  9734. if (LHSIsNull && RHSType->isQueueT()) {
  9735. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9736. return computeResultTy();
  9737. }
  9738. if (LHSType->isQueueT() && RHSIsNull) {
  9739. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9740. return computeResultTy();
  9741. }
  9742. }
  9743. return InvalidOperands(Loc, LHS, RHS);
  9744. }
  9745. // Return a signed ext_vector_type that is of identical size and number of
  9746. // elements. For floating point vectors, return an integer type of identical
  9747. // size and number of elements. In the non ext_vector_type case, search from
  9748. // the largest type to the smallest type to avoid cases where long long == long,
  9749. // where long gets picked over long long.
  9750. QualType Sema::GetSignedVectorType(QualType V) {
  9751. const VectorType *VTy = V->castAs<VectorType>();
  9752. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9753. if (isa<ExtVectorType>(VTy)) {
  9754. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9755. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9756. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9757. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9758. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9759. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9760. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9761. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9762. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9763. "Unhandled vector element size in vector compare");
  9764. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9765. }
  9766. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9767. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9768. VectorType::GenericVector);
  9769. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9770. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9771. VectorType::GenericVector);
  9772. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9773. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9774. VectorType::GenericVector);
  9775. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9776. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9777. VectorType::GenericVector);
  9778. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9779. "Unhandled vector element size in vector compare");
  9780. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9781. VectorType::GenericVector);
  9782. }
  9783. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9784. /// operates on extended vector types. Instead of producing an IntTy result,
  9785. /// like a scalar comparison, a vector comparison produces a vector of integer
  9786. /// types.
  9787. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9788. SourceLocation Loc,
  9789. BinaryOperatorKind Opc) {
  9790. // Check to make sure we're operating on vectors of the same type and width,
  9791. // Allowing one side to be a scalar of element type.
  9792. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9793. /*AllowBothBool*/true,
  9794. /*AllowBoolConversions*/getLangOpts().ZVector);
  9795. if (vType.isNull())
  9796. return vType;
  9797. QualType LHSType = LHS.get()->getType();
  9798. // If AltiVec, the comparison results in a numeric type, i.e.
  9799. // bool for C++, int for C
  9800. if (getLangOpts().AltiVec &&
  9801. vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9802. return Context.getLogicalOperationType();
  9803. // For non-floating point types, check for self-comparisons of the form
  9804. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9805. // often indicate logic errors in the program.
  9806. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9807. // Check for comparisons of floating point operands using != and ==.
  9808. if (BinaryOperator::isEqualityOp(Opc) &&
  9809. LHSType->hasFloatingRepresentation()) {
  9810. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9811. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9812. }
  9813. // Return a signed type for the vector.
  9814. return GetSignedVectorType(vType);
  9815. }
  9816. static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
  9817. const ExprResult &XorRHS,
  9818. const SourceLocation Loc) {
  9819. // Do not diagnose macros.
  9820. if (Loc.isMacroID())
  9821. return;
  9822. bool Negative = false;
  9823. bool ExplicitPlus = false;
  9824. const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
  9825. const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
  9826. if (!LHSInt)
  9827. return;
  9828. if (!RHSInt) {
  9829. // Check negative literals.
  9830. if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
  9831. UnaryOperatorKind Opc = UO->getOpcode();
  9832. if (Opc != UO_Minus && Opc != UO_Plus)
  9833. return;
  9834. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  9835. if (!RHSInt)
  9836. return;
  9837. Negative = (Opc == UO_Minus);
  9838. ExplicitPlus = !Negative;
  9839. } else {
  9840. return;
  9841. }
  9842. }
  9843. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  9844. llvm::APInt RightSideValue = RHSInt->getValue();
  9845. if (LeftSideValue != 2 && LeftSideValue != 10)
  9846. return;
  9847. if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
  9848. return;
  9849. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  9850. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  9851. llvm::StringRef ExprStr =
  9852. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  9853. CharSourceRange XorRange =
  9854. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  9855. llvm::StringRef XorStr =
  9856. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  9857. // Do not diagnose if xor keyword/macro is used.
  9858. if (XorStr == "xor")
  9859. return;
  9860. std::string LHSStr = Lexer::getSourceText(
  9861. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  9862. S.getSourceManager(), S.getLangOpts());
  9863. std::string RHSStr = Lexer::getSourceText(
  9864. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  9865. S.getSourceManager(), S.getLangOpts());
  9866. if (Negative) {
  9867. RightSideValue = -RightSideValue;
  9868. RHSStr = "-" + RHSStr;
  9869. } else if (ExplicitPlus) {
  9870. RHSStr = "+" + RHSStr;
  9871. }
  9872. StringRef LHSStrRef = LHSStr;
  9873. StringRef RHSStrRef = RHSStr;
  9874. // Do not diagnose literals with digit separators, binary, hexadecimal, octal
  9875. // literals.
  9876. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  9877. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  9878. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  9879. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  9880. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  9881. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
  9882. LHSStrRef.find('\'') != StringRef::npos ||
  9883. RHSStrRef.find('\'') != StringRef::npos)
  9884. return;
  9885. bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
  9886. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  9887. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  9888. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  9889. std::string SuggestedExpr = "1 << " + RHSStr;
  9890. bool Overflow = false;
  9891. llvm::APInt One = (LeftSideValue - 1);
  9892. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  9893. if (Overflow) {
  9894. if (RightSideIntValue < 64)
  9895. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9896. << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
  9897. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  9898. else if (RightSideIntValue == 64)
  9899. S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
  9900. else
  9901. return;
  9902. } else {
  9903. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  9904. << ExprStr << XorValue.toString(10, true) << SuggestedExpr
  9905. << PowValue.toString(10, true)
  9906. << FixItHint::CreateReplacement(
  9907. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  9908. }
  9909. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
  9910. } else if (LeftSideValue == 10) {
  9911. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  9912. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9913. << ExprStr << XorValue.toString(10, true) << SuggestedValue
  9914. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  9915. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
  9916. }
  9917. }
  9918. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9919. SourceLocation Loc) {
  9920. // Ensure that either both operands are of the same vector type, or
  9921. // one operand is of a vector type and the other is of its element type.
  9922. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9923. /*AllowBothBool*/true,
  9924. /*AllowBoolConversions*/false);
  9925. if (vType.isNull())
  9926. return InvalidOperands(Loc, LHS, RHS);
  9927. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9928. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9929. return InvalidOperands(Loc, LHS, RHS);
  9930. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9931. // usage of the logical operators && and || with vectors in C. This
  9932. // check could be notionally dropped.
  9933. if (!getLangOpts().CPlusPlus &&
  9934. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9935. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9936. return GetSignedVectorType(LHS.get()->getType());
  9937. }
  9938. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9939. SourceLocation Loc,
  9940. BinaryOperatorKind Opc) {
  9941. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9942. bool IsCompAssign =
  9943. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9944. if (LHS.get()->getType()->isVectorType() ||
  9945. RHS.get()->getType()->isVectorType()) {
  9946. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9947. RHS.get()->getType()->hasIntegerRepresentation())
  9948. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9949. /*AllowBothBool*/true,
  9950. /*AllowBoolConversions*/getLangOpts().ZVector);
  9951. return InvalidOperands(Loc, LHS, RHS);
  9952. }
  9953. if (Opc == BO_And)
  9954. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9955. ExprResult LHSResult = LHS, RHSResult = RHS;
  9956. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9957. IsCompAssign);
  9958. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9959. return QualType();
  9960. LHS = LHSResult.get();
  9961. RHS = RHSResult.get();
  9962. if (Opc == BO_Xor)
  9963. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  9964. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9965. return compType;
  9966. return InvalidOperands(Loc, LHS, RHS);
  9967. }
  9968. // C99 6.5.[13,14]
  9969. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9970. SourceLocation Loc,
  9971. BinaryOperatorKind Opc) {
  9972. // Check vector operands differently.
  9973. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9974. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9975. bool EnumConstantInBoolContext = false;
  9976. for (const ExprResult &HS : {LHS, RHS}) {
  9977. if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
  9978. const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
  9979. if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
  9980. EnumConstantInBoolContext = true;
  9981. }
  9982. }
  9983. if (EnumConstantInBoolContext)
  9984. Diag(Loc, diag::warn_enum_constant_in_bool_context);
  9985. // Diagnose cases where the user write a logical and/or but probably meant a
  9986. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9987. // is a constant.
  9988. if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
  9989. !LHS.get()->getType()->isBooleanType() &&
  9990. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9991. // Don't warn in macros or template instantiations.
  9992. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9993. // If the RHS can be constant folded, and if it constant folds to something
  9994. // that isn't 0 or 1 (which indicate a potential logical operation that
  9995. // happened to fold to true/false) then warn.
  9996. // Parens on the RHS are ignored.
  9997. Expr::EvalResult EVResult;
  9998. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9999. llvm::APSInt Result = EVResult.Val.getInt();
  10000. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  10001. !RHS.get()->getExprLoc().isMacroID()) ||
  10002. (Result != 0 && Result != 1)) {
  10003. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  10004. << RHS.get()->getSourceRange()
  10005. << (Opc == BO_LAnd ? "&&" : "||");
  10006. // Suggest replacing the logical operator with the bitwise version
  10007. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  10008. << (Opc == BO_LAnd ? "&" : "|")
  10009. << FixItHint::CreateReplacement(SourceRange(
  10010. Loc, getLocForEndOfToken(Loc)),
  10011. Opc == BO_LAnd ? "&" : "|");
  10012. if (Opc == BO_LAnd)
  10013. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  10014. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  10015. << FixItHint::CreateRemoval(
  10016. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  10017. RHS.get()->getEndLoc()));
  10018. }
  10019. }
  10020. }
  10021. if (!Context.getLangOpts().CPlusPlus) {
  10022. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  10023. // not operate on the built-in scalar and vector float types.
  10024. if (Context.getLangOpts().OpenCL &&
  10025. Context.getLangOpts().OpenCLVersion < 120) {
  10026. if (LHS.get()->getType()->isFloatingType() ||
  10027. RHS.get()->getType()->isFloatingType())
  10028. return InvalidOperands(Loc, LHS, RHS);
  10029. }
  10030. LHS = UsualUnaryConversions(LHS.get());
  10031. if (LHS.isInvalid())
  10032. return QualType();
  10033. RHS = UsualUnaryConversions(RHS.get());
  10034. if (RHS.isInvalid())
  10035. return QualType();
  10036. if (!LHS.get()->getType()->isScalarType() ||
  10037. !RHS.get()->getType()->isScalarType())
  10038. return InvalidOperands(Loc, LHS, RHS);
  10039. return Context.IntTy;
  10040. }
  10041. // The following is safe because we only use this method for
  10042. // non-overloadable operands.
  10043. // C++ [expr.log.and]p1
  10044. // C++ [expr.log.or]p1
  10045. // The operands are both contextually converted to type bool.
  10046. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  10047. if (LHSRes.isInvalid())
  10048. return InvalidOperands(Loc, LHS, RHS);
  10049. LHS = LHSRes;
  10050. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  10051. if (RHSRes.isInvalid())
  10052. return InvalidOperands(Loc, LHS, RHS);
  10053. RHS = RHSRes;
  10054. // C++ [expr.log.and]p2
  10055. // C++ [expr.log.or]p2
  10056. // The result is a bool.
  10057. return Context.BoolTy;
  10058. }
  10059. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  10060. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  10061. if (!ME) return false;
  10062. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  10063. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  10064. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  10065. if (!Base) return false;
  10066. return Base->getMethodDecl() != nullptr;
  10067. }
  10068. /// Is the given expression (which must be 'const') a reference to a
  10069. /// variable which was originally non-const, but which has become
  10070. /// 'const' due to being captured within a block?
  10071. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  10072. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  10073. assert(E->isLValue() && E->getType().isConstQualified());
  10074. E = E->IgnoreParens();
  10075. // Must be a reference to a declaration from an enclosing scope.
  10076. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  10077. if (!DRE) return NCCK_None;
  10078. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  10079. // The declaration must be a variable which is not declared 'const'.
  10080. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  10081. if (!var) return NCCK_None;
  10082. if (var->getType().isConstQualified()) return NCCK_None;
  10083. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  10084. // Decide whether the first capture was for a block or a lambda.
  10085. DeclContext *DC = S.CurContext, *Prev = nullptr;
  10086. // Decide whether the first capture was for a block or a lambda.
  10087. while (DC) {
  10088. // For init-capture, it is possible that the variable belongs to the
  10089. // template pattern of the current context.
  10090. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  10091. if (var->isInitCapture() &&
  10092. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  10093. break;
  10094. if (DC == var->getDeclContext())
  10095. break;
  10096. Prev = DC;
  10097. DC = DC->getParent();
  10098. }
  10099. // Unless we have an init-capture, we've gone one step too far.
  10100. if (!var->isInitCapture())
  10101. DC = Prev;
  10102. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  10103. }
  10104. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  10105. Ty = Ty.getNonReferenceType();
  10106. if (IsDereference && Ty->isPointerType())
  10107. Ty = Ty->getPointeeType();
  10108. return !Ty.isConstQualified();
  10109. }
  10110. // Update err_typecheck_assign_const and note_typecheck_assign_const
  10111. // when this enum is changed.
  10112. enum {
  10113. ConstFunction,
  10114. ConstVariable,
  10115. ConstMember,
  10116. ConstMethod,
  10117. NestedConstMember,
  10118. ConstUnknown, // Keep as last element
  10119. };
  10120. /// Emit the "read-only variable not assignable" error and print notes to give
  10121. /// more information about why the variable is not assignable, such as pointing
  10122. /// to the declaration of a const variable, showing that a method is const, or
  10123. /// that the function is returning a const reference.
  10124. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  10125. SourceLocation Loc) {
  10126. SourceRange ExprRange = E->getSourceRange();
  10127. // Only emit one error on the first const found. All other consts will emit
  10128. // a note to the error.
  10129. bool DiagnosticEmitted = false;
  10130. // Track if the current expression is the result of a dereference, and if the
  10131. // next checked expression is the result of a dereference.
  10132. bool IsDereference = false;
  10133. bool NextIsDereference = false;
  10134. // Loop to process MemberExpr chains.
  10135. while (true) {
  10136. IsDereference = NextIsDereference;
  10137. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  10138. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10139. NextIsDereference = ME->isArrow();
  10140. const ValueDecl *VD = ME->getMemberDecl();
  10141. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  10142. // Mutable fields can be modified even if the class is const.
  10143. if (Field->isMutable()) {
  10144. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  10145. break;
  10146. }
  10147. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  10148. if (!DiagnosticEmitted) {
  10149. S.Diag(Loc, diag::err_typecheck_assign_const)
  10150. << ExprRange << ConstMember << false /*static*/ << Field
  10151. << Field->getType();
  10152. DiagnosticEmitted = true;
  10153. }
  10154. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10155. << ConstMember << false /*static*/ << Field << Field->getType()
  10156. << Field->getSourceRange();
  10157. }
  10158. E = ME->getBase();
  10159. continue;
  10160. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  10161. if (VDecl->getType().isConstQualified()) {
  10162. if (!DiagnosticEmitted) {
  10163. S.Diag(Loc, diag::err_typecheck_assign_const)
  10164. << ExprRange << ConstMember << true /*static*/ << VDecl
  10165. << VDecl->getType();
  10166. DiagnosticEmitted = true;
  10167. }
  10168. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10169. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  10170. << VDecl->getSourceRange();
  10171. }
  10172. // Static fields do not inherit constness from parents.
  10173. break;
  10174. }
  10175. break; // End MemberExpr
  10176. } else if (const ArraySubscriptExpr *ASE =
  10177. dyn_cast<ArraySubscriptExpr>(E)) {
  10178. E = ASE->getBase()->IgnoreParenImpCasts();
  10179. continue;
  10180. } else if (const ExtVectorElementExpr *EVE =
  10181. dyn_cast<ExtVectorElementExpr>(E)) {
  10182. E = EVE->getBase()->IgnoreParenImpCasts();
  10183. continue;
  10184. }
  10185. break;
  10186. }
  10187. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  10188. // Function calls
  10189. const FunctionDecl *FD = CE->getDirectCallee();
  10190. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  10191. if (!DiagnosticEmitted) {
  10192. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10193. << ConstFunction << FD;
  10194. DiagnosticEmitted = true;
  10195. }
  10196. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  10197. diag::note_typecheck_assign_const)
  10198. << ConstFunction << FD << FD->getReturnType()
  10199. << FD->getReturnTypeSourceRange();
  10200. }
  10201. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10202. // Point to variable declaration.
  10203. if (const ValueDecl *VD = DRE->getDecl()) {
  10204. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  10205. if (!DiagnosticEmitted) {
  10206. S.Diag(Loc, diag::err_typecheck_assign_const)
  10207. << ExprRange << ConstVariable << VD << VD->getType();
  10208. DiagnosticEmitted = true;
  10209. }
  10210. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10211. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  10212. }
  10213. }
  10214. } else if (isa<CXXThisExpr>(E)) {
  10215. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  10216. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  10217. if (MD->isConst()) {
  10218. if (!DiagnosticEmitted) {
  10219. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10220. << ConstMethod << MD;
  10221. DiagnosticEmitted = true;
  10222. }
  10223. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  10224. << ConstMethod << MD << MD->getSourceRange();
  10225. }
  10226. }
  10227. }
  10228. }
  10229. if (DiagnosticEmitted)
  10230. return;
  10231. // Can't determine a more specific message, so display the generic error.
  10232. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  10233. }
  10234. enum OriginalExprKind {
  10235. OEK_Variable,
  10236. OEK_Member,
  10237. OEK_LValue
  10238. };
  10239. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  10240. const RecordType *Ty,
  10241. SourceLocation Loc, SourceRange Range,
  10242. OriginalExprKind OEK,
  10243. bool &DiagnosticEmitted) {
  10244. std::vector<const RecordType *> RecordTypeList;
  10245. RecordTypeList.push_back(Ty);
  10246. unsigned NextToCheckIndex = 0;
  10247. // We walk the record hierarchy breadth-first to ensure that we print
  10248. // diagnostics in field nesting order.
  10249. while (RecordTypeList.size() > NextToCheckIndex) {
  10250. bool IsNested = NextToCheckIndex > 0;
  10251. for (const FieldDecl *Field :
  10252. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  10253. // First, check every field for constness.
  10254. QualType FieldTy = Field->getType();
  10255. if (FieldTy.isConstQualified()) {
  10256. if (!DiagnosticEmitted) {
  10257. S.Diag(Loc, diag::err_typecheck_assign_const)
  10258. << Range << NestedConstMember << OEK << VD
  10259. << IsNested << Field;
  10260. DiagnosticEmitted = true;
  10261. }
  10262. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  10263. << NestedConstMember << IsNested << Field
  10264. << FieldTy << Field->getSourceRange();
  10265. }
  10266. // Then we append it to the list to check next in order.
  10267. FieldTy = FieldTy.getCanonicalType();
  10268. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  10269. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  10270. RecordTypeList.push_back(FieldRecTy);
  10271. }
  10272. }
  10273. ++NextToCheckIndex;
  10274. }
  10275. }
  10276. /// Emit an error for the case where a record we are trying to assign to has a
  10277. /// const-qualified field somewhere in its hierarchy.
  10278. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  10279. SourceLocation Loc) {
  10280. QualType Ty = E->getType();
  10281. assert(Ty->isRecordType() && "lvalue was not record?");
  10282. SourceRange Range = E->getSourceRange();
  10283. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  10284. bool DiagEmitted = false;
  10285. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  10286. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  10287. Range, OEK_Member, DiagEmitted);
  10288. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10289. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  10290. Range, OEK_Variable, DiagEmitted);
  10291. else
  10292. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  10293. Range, OEK_LValue, DiagEmitted);
  10294. if (!DiagEmitted)
  10295. DiagnoseConstAssignment(S, E, Loc);
  10296. }
  10297. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  10298. /// emit an error and return true. If so, return false.
  10299. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  10300. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  10301. S.CheckShadowingDeclModification(E, Loc);
  10302. SourceLocation OrigLoc = Loc;
  10303. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  10304. &Loc);
  10305. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  10306. IsLV = Expr::MLV_InvalidMessageExpression;
  10307. if (IsLV == Expr::MLV_Valid)
  10308. return false;
  10309. unsigned DiagID = 0;
  10310. bool NeedType = false;
  10311. switch (IsLV) { // C99 6.5.16p2
  10312. case Expr::MLV_ConstQualified:
  10313. // Use a specialized diagnostic when we're assigning to an object
  10314. // from an enclosing function or block.
  10315. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  10316. if (NCCK == NCCK_Block)
  10317. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  10318. else
  10319. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  10320. break;
  10321. }
  10322. // In ARC, use some specialized diagnostics for occasions where we
  10323. // infer 'const'. These are always pseudo-strong variables.
  10324. if (S.getLangOpts().ObjCAutoRefCount) {
  10325. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  10326. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  10327. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  10328. // Use the normal diagnostic if it's pseudo-__strong but the
  10329. // user actually wrote 'const'.
  10330. if (var->isARCPseudoStrong() &&
  10331. (!var->getTypeSourceInfo() ||
  10332. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  10333. // There are three pseudo-strong cases:
  10334. // - self
  10335. ObjCMethodDecl *method = S.getCurMethodDecl();
  10336. if (method && var == method->getSelfDecl()) {
  10337. DiagID = method->isClassMethod()
  10338. ? diag::err_typecheck_arc_assign_self_class_method
  10339. : diag::err_typecheck_arc_assign_self;
  10340. // - Objective-C externally_retained attribute.
  10341. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  10342. isa<ParmVarDecl>(var)) {
  10343. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  10344. // - fast enumeration variables
  10345. } else {
  10346. DiagID = diag::err_typecheck_arr_assign_enumeration;
  10347. }
  10348. SourceRange Assign;
  10349. if (Loc != OrigLoc)
  10350. Assign = SourceRange(OrigLoc, OrigLoc);
  10351. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10352. // We need to preserve the AST regardless, so migration tool
  10353. // can do its job.
  10354. return false;
  10355. }
  10356. }
  10357. }
  10358. // If none of the special cases above are triggered, then this is a
  10359. // simple const assignment.
  10360. if (DiagID == 0) {
  10361. DiagnoseConstAssignment(S, E, Loc);
  10362. return true;
  10363. }
  10364. break;
  10365. case Expr::MLV_ConstAddrSpace:
  10366. DiagnoseConstAssignment(S, E, Loc);
  10367. return true;
  10368. case Expr::MLV_ConstQualifiedField:
  10369. DiagnoseRecursiveConstFields(S, E, Loc);
  10370. return true;
  10371. case Expr::MLV_ArrayType:
  10372. case Expr::MLV_ArrayTemporary:
  10373. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10374. NeedType = true;
  10375. break;
  10376. case Expr::MLV_NotObjectType:
  10377. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10378. NeedType = true;
  10379. break;
  10380. case Expr::MLV_LValueCast:
  10381. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10382. break;
  10383. case Expr::MLV_Valid:
  10384. llvm_unreachable("did not take early return for MLV_Valid");
  10385. case Expr::MLV_InvalidExpression:
  10386. case Expr::MLV_MemberFunction:
  10387. case Expr::MLV_ClassTemporary:
  10388. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10389. break;
  10390. case Expr::MLV_IncompleteType:
  10391. case Expr::MLV_IncompleteVoidType:
  10392. return S.RequireCompleteType(Loc, E->getType(),
  10393. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10394. case Expr::MLV_DuplicateVectorComponents:
  10395. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10396. break;
  10397. case Expr::MLV_NoSetterProperty:
  10398. llvm_unreachable("readonly properties should be processed differently");
  10399. case Expr::MLV_InvalidMessageExpression:
  10400. DiagID = diag::err_readonly_message_assignment;
  10401. break;
  10402. case Expr::MLV_SubObjCPropertySetting:
  10403. DiagID = diag::err_no_subobject_property_setting;
  10404. break;
  10405. }
  10406. SourceRange Assign;
  10407. if (Loc != OrigLoc)
  10408. Assign = SourceRange(OrigLoc, OrigLoc);
  10409. if (NeedType)
  10410. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10411. else
  10412. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10413. return true;
  10414. }
  10415. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10416. SourceLocation Loc,
  10417. Sema &Sema) {
  10418. if (Sema.inTemplateInstantiation())
  10419. return;
  10420. if (Sema.isUnevaluatedContext())
  10421. return;
  10422. if (Loc.isInvalid() || Loc.isMacroID())
  10423. return;
  10424. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10425. return;
  10426. // C / C++ fields
  10427. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10428. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10429. if (ML && MR) {
  10430. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10431. return;
  10432. const ValueDecl *LHSDecl =
  10433. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10434. const ValueDecl *RHSDecl =
  10435. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10436. if (LHSDecl != RHSDecl)
  10437. return;
  10438. if (LHSDecl->getType().isVolatileQualified())
  10439. return;
  10440. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10441. if (RefTy->getPointeeType().isVolatileQualified())
  10442. return;
  10443. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10444. }
  10445. // Objective-C instance variables
  10446. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10447. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10448. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10449. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10450. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10451. if (RL && RR && RL->getDecl() == RR->getDecl())
  10452. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10453. }
  10454. }
  10455. // C99 6.5.16.1
  10456. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10457. SourceLocation Loc,
  10458. QualType CompoundType) {
  10459. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10460. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10461. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10462. return QualType();
  10463. QualType LHSType = LHSExpr->getType();
  10464. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10465. CompoundType;
  10466. // OpenCL v1.2 s6.1.1.1 p2:
  10467. // The half data type can only be used to declare a pointer to a buffer that
  10468. // contains half values
  10469. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10470. LHSType->isHalfType()) {
  10471. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10472. << LHSType.getUnqualifiedType();
  10473. return QualType();
  10474. }
  10475. AssignConvertType ConvTy;
  10476. if (CompoundType.isNull()) {
  10477. Expr *RHSCheck = RHS.get();
  10478. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10479. QualType LHSTy(LHSType);
  10480. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10481. if (RHS.isInvalid())
  10482. return QualType();
  10483. // Special case of NSObject attributes on c-style pointer types.
  10484. if (ConvTy == IncompatiblePointer &&
  10485. ((Context.isObjCNSObjectType(LHSType) &&
  10486. RHSType->isObjCObjectPointerType()) ||
  10487. (Context.isObjCNSObjectType(RHSType) &&
  10488. LHSType->isObjCObjectPointerType())))
  10489. ConvTy = Compatible;
  10490. if (ConvTy == Compatible &&
  10491. LHSType->isObjCObjectType())
  10492. Diag(Loc, diag::err_objc_object_assignment)
  10493. << LHSType;
  10494. // If the RHS is a unary plus or minus, check to see if they = and + are
  10495. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10496. // instead of "x += 4".
  10497. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10498. RHSCheck = ICE->getSubExpr();
  10499. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10500. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10501. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10502. // Only if the two operators are exactly adjacent.
  10503. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10504. // And there is a space or other character before the subexpr of the
  10505. // unary +/-. We don't want to warn on "x=-1".
  10506. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10507. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10508. Diag(Loc, diag::warn_not_compound_assign)
  10509. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10510. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10511. }
  10512. }
  10513. if (ConvTy == Compatible) {
  10514. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10515. // Warn about retain cycles where a block captures the LHS, but
  10516. // not if the LHS is a simple variable into which the block is
  10517. // being stored...unless that variable can be captured by reference!
  10518. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10519. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10520. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10521. checkRetainCycles(LHSExpr, RHS.get());
  10522. }
  10523. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10524. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10525. // It is safe to assign a weak reference into a strong variable.
  10526. // Although this code can still have problems:
  10527. // id x = self.weakProp;
  10528. // id y = self.weakProp;
  10529. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10530. // paths through the function. This should be revisited if
  10531. // -Wrepeated-use-of-weak is made flow-sensitive.
  10532. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10533. // variable, which will be valid for the current autorelease scope.
  10534. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10535. RHS.get()->getBeginLoc()))
  10536. getCurFunction()->markSafeWeakUse(RHS.get());
  10537. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10538. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10539. }
  10540. }
  10541. } else {
  10542. // Compound assignment "x += y"
  10543. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10544. }
  10545. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10546. RHS.get(), AA_Assigning))
  10547. return QualType();
  10548. CheckForNullPointerDereference(*this, LHSExpr);
  10549. if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
  10550. if (CompoundType.isNull()) {
  10551. // C++2a [expr.ass]p5:
  10552. // A simple-assignment whose left operand is of a volatile-qualified
  10553. // type is deprecated unless the assignment is either a discarded-value
  10554. // expression or an unevaluated operand
  10555. ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
  10556. } else {
  10557. // C++2a [expr.ass]p6:
  10558. // [Compound-assignment] expressions are deprecated if E1 has
  10559. // volatile-qualified type
  10560. Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
  10561. }
  10562. }
  10563. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10564. // left operand unless the left operand has qualified type, in which case
  10565. // it is the unqualified version of the type of the left operand.
  10566. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10567. // is converted to the type of the assignment expression (above).
  10568. // C++ 5.17p1: the type of the assignment expression is that of its left
  10569. // operand.
  10570. return (getLangOpts().CPlusPlus
  10571. ? LHSType : LHSType.getUnqualifiedType());
  10572. }
  10573. // Only ignore explicit casts to void.
  10574. static bool IgnoreCommaOperand(const Expr *E) {
  10575. E = E->IgnoreParens();
  10576. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10577. if (CE->getCastKind() == CK_ToVoid) {
  10578. return true;
  10579. }
  10580. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10581. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10582. CE->getSubExpr()->getType()->isDependentType()) {
  10583. return true;
  10584. }
  10585. }
  10586. return false;
  10587. }
  10588. // Look for instances where it is likely the comma operator is confused with
  10589. // another operator. There is a whitelist of acceptable expressions for the
  10590. // left hand side of the comma operator, otherwise emit a warning.
  10591. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10592. // No warnings in macros
  10593. if (Loc.isMacroID())
  10594. return;
  10595. // Don't warn in template instantiations.
  10596. if (inTemplateInstantiation())
  10597. return;
  10598. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10599. // instead, skip more than needed, then call back into here with the
  10600. // CommaVisitor in SemaStmt.cpp.
  10601. // The whitelisted locations are the initialization and increment portions
  10602. // of a for loop. The additional checks are on the condition of
  10603. // if statements, do/while loops, and for loops.
  10604. // Differences in scope flags for C89 mode requires the extra logic.
  10605. const unsigned ForIncrementFlags =
  10606. getLangOpts().C99 || getLangOpts().CPlusPlus
  10607. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10608. : Scope::ContinueScope | Scope::BreakScope;
  10609. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10610. const unsigned ScopeFlags = getCurScope()->getFlags();
  10611. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10612. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10613. return;
  10614. // If there are multiple comma operators used together, get the RHS of the
  10615. // of the comma operator as the LHS.
  10616. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10617. if (BO->getOpcode() != BO_Comma)
  10618. break;
  10619. LHS = BO->getRHS();
  10620. }
  10621. // Only allow some expressions on LHS to not warn.
  10622. if (IgnoreCommaOperand(LHS))
  10623. return;
  10624. Diag(Loc, diag::warn_comma_operator);
  10625. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10626. << LHS->getSourceRange()
  10627. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10628. LangOpts.CPlusPlus ? "static_cast<void>("
  10629. : "(void)(")
  10630. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10631. ")");
  10632. }
  10633. // C99 6.5.17
  10634. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10635. SourceLocation Loc) {
  10636. LHS = S.CheckPlaceholderExpr(LHS.get());
  10637. RHS = S.CheckPlaceholderExpr(RHS.get());
  10638. if (LHS.isInvalid() || RHS.isInvalid())
  10639. return QualType();
  10640. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10641. // operands, but not unary promotions.
  10642. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10643. // So we treat the LHS as a ignored value, and in C++ we allow the
  10644. // containing site to determine what should be done with the RHS.
  10645. LHS = S.IgnoredValueConversions(LHS.get());
  10646. if (LHS.isInvalid())
  10647. return QualType();
  10648. S.DiagnoseUnusedExprResult(LHS.get());
  10649. if (!S.getLangOpts().CPlusPlus) {
  10650. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10651. if (RHS.isInvalid())
  10652. return QualType();
  10653. if (!RHS.get()->getType()->isVoidType())
  10654. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10655. diag::err_incomplete_type);
  10656. }
  10657. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10658. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10659. return RHS.get()->getType();
  10660. }
  10661. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10662. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10663. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10664. ExprValueKind &VK,
  10665. ExprObjectKind &OK,
  10666. SourceLocation OpLoc,
  10667. bool IsInc, bool IsPrefix) {
  10668. if (Op->isTypeDependent())
  10669. return S.Context.DependentTy;
  10670. QualType ResType = Op->getType();
  10671. // Atomic types can be used for increment / decrement where the non-atomic
  10672. // versions can, so ignore the _Atomic() specifier for the purpose of
  10673. // checking.
  10674. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10675. ResType = ResAtomicType->getValueType();
  10676. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10677. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10678. // Decrement of bool is not allowed.
  10679. if (!IsInc) {
  10680. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10681. return QualType();
  10682. }
  10683. // Increment of bool sets it to true, but is deprecated.
  10684. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10685. : diag::warn_increment_bool)
  10686. << Op->getSourceRange();
  10687. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10688. // Error on enum increments and decrements in C++ mode
  10689. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10690. return QualType();
  10691. } else if (ResType->isRealType()) {
  10692. // OK!
  10693. } else if (ResType->isPointerType()) {
  10694. // C99 6.5.2.4p2, 6.5.6p2
  10695. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10696. return QualType();
  10697. } else if (ResType->isObjCObjectPointerType()) {
  10698. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10699. // Otherwise, we just need a complete type.
  10700. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10701. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10702. return QualType();
  10703. } else if (ResType->isAnyComplexType()) {
  10704. // C99 does not support ++/-- on complex types, we allow as an extension.
  10705. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10706. << ResType << Op->getSourceRange();
  10707. } else if (ResType->isPlaceholderType()) {
  10708. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10709. if (PR.isInvalid()) return QualType();
  10710. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10711. IsInc, IsPrefix);
  10712. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10713. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10714. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10715. (ResType->castAs<VectorType>()->getVectorKind() !=
  10716. VectorType::AltiVecBool)) {
  10717. // The z vector extensions allow ++ and -- for non-bool vectors.
  10718. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10719. ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
  10720. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10721. } else {
  10722. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10723. << ResType << int(IsInc) << Op->getSourceRange();
  10724. return QualType();
  10725. }
  10726. // At this point, we know we have a real, complex or pointer type.
  10727. // Now make sure the operand is a modifiable lvalue.
  10728. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10729. return QualType();
  10730. if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
  10731. // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
  10732. // An operand with volatile-qualified type is deprecated
  10733. S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
  10734. << IsInc << ResType;
  10735. }
  10736. // In C++, a prefix increment is the same type as the operand. Otherwise
  10737. // (in C or with postfix), the increment is the unqualified type of the
  10738. // operand.
  10739. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10740. VK = VK_LValue;
  10741. OK = Op->getObjectKind();
  10742. return ResType;
  10743. } else {
  10744. VK = VK_RValue;
  10745. return ResType.getUnqualifiedType();
  10746. }
  10747. }
  10748. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10749. /// This routine allows us to typecheck complex/recursive expressions
  10750. /// where the declaration is needed for type checking. We only need to
  10751. /// handle cases when the expression references a function designator
  10752. /// or is an lvalue. Here are some examples:
  10753. /// - &(x) => x
  10754. /// - &*****f => f for f a function designator.
  10755. /// - &s.xx => s
  10756. /// - &s.zz[1].yy -> s, if zz is an array
  10757. /// - *(x + 1) -> x, if x is an array
  10758. /// - &"123"[2] -> 0
  10759. /// - & __real__ x -> x
  10760. static ValueDecl *getPrimaryDecl(Expr *E) {
  10761. switch (E->getStmtClass()) {
  10762. case Stmt::DeclRefExprClass:
  10763. return cast<DeclRefExpr>(E)->getDecl();
  10764. case Stmt::MemberExprClass:
  10765. // If this is an arrow operator, the address is an offset from
  10766. // the base's value, so the object the base refers to is
  10767. // irrelevant.
  10768. if (cast<MemberExpr>(E)->isArrow())
  10769. return nullptr;
  10770. // Otherwise, the expression refers to a part of the base
  10771. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10772. case Stmt::ArraySubscriptExprClass: {
  10773. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10774. // promotion of register arrays earlier.
  10775. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10776. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10777. if (ICE->getSubExpr()->getType()->isArrayType())
  10778. return getPrimaryDecl(ICE->getSubExpr());
  10779. }
  10780. return nullptr;
  10781. }
  10782. case Stmt::UnaryOperatorClass: {
  10783. UnaryOperator *UO = cast<UnaryOperator>(E);
  10784. switch(UO->getOpcode()) {
  10785. case UO_Real:
  10786. case UO_Imag:
  10787. case UO_Extension:
  10788. return getPrimaryDecl(UO->getSubExpr());
  10789. default:
  10790. return nullptr;
  10791. }
  10792. }
  10793. case Stmt::ParenExprClass:
  10794. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10795. case Stmt::ImplicitCastExprClass:
  10796. // If the result of an implicit cast is an l-value, we care about
  10797. // the sub-expression; otherwise, the result here doesn't matter.
  10798. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10799. default:
  10800. return nullptr;
  10801. }
  10802. }
  10803. namespace {
  10804. enum {
  10805. AO_Bit_Field = 0,
  10806. AO_Vector_Element = 1,
  10807. AO_Property_Expansion = 2,
  10808. AO_Register_Variable = 3,
  10809. AO_No_Error = 4
  10810. };
  10811. }
  10812. /// Diagnose invalid operand for address of operations.
  10813. ///
  10814. /// \param Type The type of operand which cannot have its address taken.
  10815. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10816. Expr *E, unsigned Type) {
  10817. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10818. }
  10819. /// CheckAddressOfOperand - The operand of & must be either a function
  10820. /// designator or an lvalue designating an object. If it is an lvalue, the
  10821. /// object cannot be declared with storage class register or be a bit field.
  10822. /// Note: The usual conversions are *not* applied to the operand of the &
  10823. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10824. /// In C++, the operand might be an overloaded function name, in which case
  10825. /// we allow the '&' but retain the overloaded-function type.
  10826. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10827. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10828. if (PTy->getKind() == BuiltinType::Overload) {
  10829. Expr *E = OrigOp.get()->IgnoreParens();
  10830. if (!isa<OverloadExpr>(E)) {
  10831. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10832. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10833. << OrigOp.get()->getSourceRange();
  10834. return QualType();
  10835. }
  10836. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10837. if (isa<UnresolvedMemberExpr>(Ovl))
  10838. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10839. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10840. << OrigOp.get()->getSourceRange();
  10841. return QualType();
  10842. }
  10843. return Context.OverloadTy;
  10844. }
  10845. if (PTy->getKind() == BuiltinType::UnknownAny)
  10846. return Context.UnknownAnyTy;
  10847. if (PTy->getKind() == BuiltinType::BoundMember) {
  10848. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10849. << OrigOp.get()->getSourceRange();
  10850. return QualType();
  10851. }
  10852. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10853. if (OrigOp.isInvalid()) return QualType();
  10854. }
  10855. if (OrigOp.get()->isTypeDependent())
  10856. return Context.DependentTy;
  10857. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10858. // Make sure to ignore parentheses in subsequent checks
  10859. Expr *op = OrigOp.get()->IgnoreParens();
  10860. // In OpenCL captures for blocks called as lambda functions
  10861. // are located in the private address space. Blocks used in
  10862. // enqueue_kernel can be located in a different address space
  10863. // depending on a vendor implementation. Thus preventing
  10864. // taking an address of the capture to avoid invalid AS casts.
  10865. if (LangOpts.OpenCL) {
  10866. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10867. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10868. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10869. return QualType();
  10870. }
  10871. }
  10872. if (getLangOpts().C99) {
  10873. // Implement C99-only parts of addressof rules.
  10874. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10875. if (uOp->getOpcode() == UO_Deref)
  10876. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10877. // (assuming the deref expression is valid).
  10878. return uOp->getSubExpr()->getType();
  10879. }
  10880. // Technically, there should be a check for array subscript
  10881. // expressions here, but the result of one is always an lvalue anyway.
  10882. }
  10883. ValueDecl *dcl = getPrimaryDecl(op);
  10884. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10885. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10886. op->getBeginLoc()))
  10887. return QualType();
  10888. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10889. unsigned AddressOfError = AO_No_Error;
  10890. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10891. bool sfinae = (bool)isSFINAEContext();
  10892. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10893. : diag::ext_typecheck_addrof_temporary)
  10894. << op->getType() << op->getSourceRange();
  10895. if (sfinae)
  10896. return QualType();
  10897. // Materialize the temporary as an lvalue so that we can take its address.
  10898. OrigOp = op =
  10899. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10900. } else if (isa<ObjCSelectorExpr>(op)) {
  10901. return Context.getPointerType(op->getType());
  10902. } else if (lval == Expr::LV_MemberFunction) {
  10903. // If it's an instance method, make a member pointer.
  10904. // The expression must have exactly the form &A::foo.
  10905. // If the underlying expression isn't a decl ref, give up.
  10906. if (!isa<DeclRefExpr>(op)) {
  10907. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10908. << OrigOp.get()->getSourceRange();
  10909. return QualType();
  10910. }
  10911. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10912. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10913. // The id-expression was parenthesized.
  10914. if (OrigOp.get() != DRE) {
  10915. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10916. << OrigOp.get()->getSourceRange();
  10917. // The method was named without a qualifier.
  10918. } else if (!DRE->getQualifier()) {
  10919. if (MD->getParent()->getName().empty())
  10920. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10921. << op->getSourceRange();
  10922. else {
  10923. SmallString<32> Str;
  10924. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10925. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10926. << op->getSourceRange()
  10927. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10928. }
  10929. }
  10930. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10931. if (isa<CXXDestructorDecl>(MD))
  10932. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10933. QualType MPTy = Context.getMemberPointerType(
  10934. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10935. // Under the MS ABI, lock down the inheritance model now.
  10936. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10937. (void)isCompleteType(OpLoc, MPTy);
  10938. return MPTy;
  10939. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10940. // C99 6.5.3.2p1
  10941. // The operand must be either an l-value or a function designator
  10942. if (!op->getType()->isFunctionType()) {
  10943. // Use a special diagnostic for loads from property references.
  10944. if (isa<PseudoObjectExpr>(op)) {
  10945. AddressOfError = AO_Property_Expansion;
  10946. } else {
  10947. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10948. << op->getType() << op->getSourceRange();
  10949. return QualType();
  10950. }
  10951. }
  10952. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10953. // The operand cannot be a bit-field
  10954. AddressOfError = AO_Bit_Field;
  10955. } else if (op->getObjectKind() == OK_VectorComponent) {
  10956. // The operand cannot be an element of a vector
  10957. AddressOfError = AO_Vector_Element;
  10958. } else if (dcl) { // C99 6.5.3.2p1
  10959. // We have an lvalue with a decl. Make sure the decl is not declared
  10960. // with the register storage-class specifier.
  10961. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10962. // in C++ it is not error to take address of a register
  10963. // variable (c++03 7.1.1P3)
  10964. if (vd->getStorageClass() == SC_Register &&
  10965. !getLangOpts().CPlusPlus) {
  10966. AddressOfError = AO_Register_Variable;
  10967. }
  10968. } else if (isa<MSPropertyDecl>(dcl)) {
  10969. AddressOfError = AO_Property_Expansion;
  10970. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10971. return Context.OverloadTy;
  10972. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10973. // Okay: we can take the address of a field.
  10974. // Could be a pointer to member, though, if there is an explicit
  10975. // scope qualifier for the class.
  10976. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10977. DeclContext *Ctx = dcl->getDeclContext();
  10978. if (Ctx && Ctx->isRecord()) {
  10979. if (dcl->getType()->isReferenceType()) {
  10980. Diag(OpLoc,
  10981. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10982. << dcl->getDeclName() << dcl->getType();
  10983. return QualType();
  10984. }
  10985. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10986. Ctx = Ctx->getParent();
  10987. QualType MPTy = Context.getMemberPointerType(
  10988. op->getType(),
  10989. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10990. // Under the MS ABI, lock down the inheritance model now.
  10991. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10992. (void)isCompleteType(OpLoc, MPTy);
  10993. return MPTy;
  10994. }
  10995. }
  10996. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10997. !isa<BindingDecl>(dcl))
  10998. llvm_unreachable("Unknown/unexpected decl type");
  10999. }
  11000. if (AddressOfError != AO_No_Error) {
  11001. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  11002. return QualType();
  11003. }
  11004. if (lval == Expr::LV_IncompleteVoidType) {
  11005. // Taking the address of a void variable is technically illegal, but we
  11006. // allow it in cases which are otherwise valid.
  11007. // Example: "extern void x; void* y = &x;".
  11008. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  11009. }
  11010. // If the operand has type "type", the result has type "pointer to type".
  11011. if (op->getType()->isObjCObjectType())
  11012. return Context.getObjCObjectPointerType(op->getType());
  11013. CheckAddressOfPackedMember(op);
  11014. return Context.getPointerType(op->getType());
  11015. }
  11016. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  11017. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  11018. if (!DRE)
  11019. return;
  11020. const Decl *D = DRE->getDecl();
  11021. if (!D)
  11022. return;
  11023. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  11024. if (!Param)
  11025. return;
  11026. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  11027. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  11028. return;
  11029. if (FunctionScopeInfo *FD = S.getCurFunction())
  11030. if (!FD->ModifiedNonNullParams.count(Param))
  11031. FD->ModifiedNonNullParams.insert(Param);
  11032. }
  11033. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  11034. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  11035. SourceLocation OpLoc) {
  11036. if (Op->isTypeDependent())
  11037. return S.Context.DependentTy;
  11038. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  11039. if (ConvResult.isInvalid())
  11040. return QualType();
  11041. Op = ConvResult.get();
  11042. QualType OpTy = Op->getType();
  11043. QualType Result;
  11044. if (isa<CXXReinterpretCastExpr>(Op)) {
  11045. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  11046. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  11047. Op->getSourceRange());
  11048. }
  11049. if (const PointerType *PT = OpTy->getAs<PointerType>())
  11050. {
  11051. Result = PT->getPointeeType();
  11052. }
  11053. else if (const ObjCObjectPointerType *OPT =
  11054. OpTy->getAs<ObjCObjectPointerType>())
  11055. Result = OPT->getPointeeType();
  11056. else {
  11057. ExprResult PR = S.CheckPlaceholderExpr(Op);
  11058. if (PR.isInvalid()) return QualType();
  11059. if (PR.get() != Op)
  11060. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  11061. }
  11062. if (Result.isNull()) {
  11063. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  11064. << OpTy << Op->getSourceRange();
  11065. return QualType();
  11066. }
  11067. // Note that per both C89 and C99, indirection is always legal, even if Result
  11068. // is an incomplete type or void. It would be possible to warn about
  11069. // dereferencing a void pointer, but it's completely well-defined, and such a
  11070. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  11071. // for pointers to 'void' but is fine for any other pointer type:
  11072. //
  11073. // C++ [expr.unary.op]p1:
  11074. // [...] the expression to which [the unary * operator] is applied shall
  11075. // be a pointer to an object type, or a pointer to a function type
  11076. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  11077. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  11078. << OpTy << Op->getSourceRange();
  11079. // Dereferences are usually l-values...
  11080. VK = VK_LValue;
  11081. // ...except that certain expressions are never l-values in C.
  11082. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  11083. VK = VK_RValue;
  11084. return Result;
  11085. }
  11086. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  11087. BinaryOperatorKind Opc;
  11088. switch (Kind) {
  11089. default: llvm_unreachable("Unknown binop!");
  11090. case tok::periodstar: Opc = BO_PtrMemD; break;
  11091. case tok::arrowstar: Opc = BO_PtrMemI; break;
  11092. case tok::star: Opc = BO_Mul; break;
  11093. case tok::slash: Opc = BO_Div; break;
  11094. case tok::percent: Opc = BO_Rem; break;
  11095. case tok::plus: Opc = BO_Add; break;
  11096. case tok::minus: Opc = BO_Sub; break;
  11097. case tok::lessless: Opc = BO_Shl; break;
  11098. case tok::greatergreater: Opc = BO_Shr; break;
  11099. case tok::lessequal: Opc = BO_LE; break;
  11100. case tok::less: Opc = BO_LT; break;
  11101. case tok::greaterequal: Opc = BO_GE; break;
  11102. case tok::greater: Opc = BO_GT; break;
  11103. case tok::exclaimequal: Opc = BO_NE; break;
  11104. case tok::equalequal: Opc = BO_EQ; break;
  11105. case tok::spaceship: Opc = BO_Cmp; break;
  11106. case tok::amp: Opc = BO_And; break;
  11107. case tok::caret: Opc = BO_Xor; break;
  11108. case tok::pipe: Opc = BO_Or; break;
  11109. case tok::ampamp: Opc = BO_LAnd; break;
  11110. case tok::pipepipe: Opc = BO_LOr; break;
  11111. case tok::equal: Opc = BO_Assign; break;
  11112. case tok::starequal: Opc = BO_MulAssign; break;
  11113. case tok::slashequal: Opc = BO_DivAssign; break;
  11114. case tok::percentequal: Opc = BO_RemAssign; break;
  11115. case tok::plusequal: Opc = BO_AddAssign; break;
  11116. case tok::minusequal: Opc = BO_SubAssign; break;
  11117. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  11118. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  11119. case tok::ampequal: Opc = BO_AndAssign; break;
  11120. case tok::caretequal: Opc = BO_XorAssign; break;
  11121. case tok::pipeequal: Opc = BO_OrAssign; break;
  11122. case tok::comma: Opc = BO_Comma; break;
  11123. }
  11124. return Opc;
  11125. }
  11126. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  11127. tok::TokenKind Kind) {
  11128. UnaryOperatorKind Opc;
  11129. switch (Kind) {
  11130. default: llvm_unreachable("Unknown unary op!");
  11131. case tok::plusplus: Opc = UO_PreInc; break;
  11132. case tok::minusminus: Opc = UO_PreDec; break;
  11133. case tok::amp: Opc = UO_AddrOf; break;
  11134. case tok::star: Opc = UO_Deref; break;
  11135. case tok::plus: Opc = UO_Plus; break;
  11136. case tok::minus: Opc = UO_Minus; break;
  11137. case tok::tilde: Opc = UO_Not; break;
  11138. case tok::exclaim: Opc = UO_LNot; break;
  11139. case tok::kw___real: Opc = UO_Real; break;
  11140. case tok::kw___imag: Opc = UO_Imag; break;
  11141. case tok::kw___extension__: Opc = UO_Extension; break;
  11142. }
  11143. return Opc;
  11144. }
  11145. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  11146. /// This warning suppressed in the event of macro expansions.
  11147. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  11148. SourceLocation OpLoc, bool IsBuiltin) {
  11149. if (S.inTemplateInstantiation())
  11150. return;
  11151. if (S.isUnevaluatedContext())
  11152. return;
  11153. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  11154. return;
  11155. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11156. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11157. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11158. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11159. if (!LHSDeclRef || !RHSDeclRef ||
  11160. LHSDeclRef->getLocation().isMacroID() ||
  11161. RHSDeclRef->getLocation().isMacroID())
  11162. return;
  11163. const ValueDecl *LHSDecl =
  11164. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  11165. const ValueDecl *RHSDecl =
  11166. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  11167. if (LHSDecl != RHSDecl)
  11168. return;
  11169. if (LHSDecl->getType().isVolatileQualified())
  11170. return;
  11171. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  11172. if (RefTy->getPointeeType().isVolatileQualified())
  11173. return;
  11174. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  11175. : diag::warn_self_assignment_overloaded)
  11176. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  11177. << RHSExpr->getSourceRange();
  11178. }
  11179. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  11180. /// is usually indicative of introspection within the Objective-C pointer.
  11181. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  11182. SourceLocation OpLoc) {
  11183. if (!S.getLangOpts().ObjC)
  11184. return;
  11185. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  11186. const Expr *LHS = L.get();
  11187. const Expr *RHS = R.get();
  11188. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11189. ObjCPointerExpr = LHS;
  11190. OtherExpr = RHS;
  11191. }
  11192. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11193. ObjCPointerExpr = RHS;
  11194. OtherExpr = LHS;
  11195. }
  11196. // This warning is deliberately made very specific to reduce false
  11197. // positives with logic that uses '&' for hashing. This logic mainly
  11198. // looks for code trying to introspect into tagged pointers, which
  11199. // code should generally never do.
  11200. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  11201. unsigned Diag = diag::warn_objc_pointer_masking;
  11202. // Determine if we are introspecting the result of performSelectorXXX.
  11203. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  11204. // Special case messages to -performSelector and friends, which
  11205. // can return non-pointer values boxed in a pointer value.
  11206. // Some clients may wish to silence warnings in this subcase.
  11207. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  11208. Selector S = ME->getSelector();
  11209. StringRef SelArg0 = S.getNameForSlot(0);
  11210. if (SelArg0.startswith("performSelector"))
  11211. Diag = diag::warn_objc_pointer_masking_performSelector;
  11212. }
  11213. S.Diag(OpLoc, Diag)
  11214. << ObjCPointerExpr->getSourceRange();
  11215. }
  11216. }
  11217. static NamedDecl *getDeclFromExpr(Expr *E) {
  11218. if (!E)
  11219. return nullptr;
  11220. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  11221. return DRE->getDecl();
  11222. if (auto *ME = dyn_cast<MemberExpr>(E))
  11223. return ME->getMemberDecl();
  11224. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  11225. return IRE->getDecl();
  11226. return nullptr;
  11227. }
  11228. // This helper function promotes a binary operator's operands (which are of a
  11229. // half vector type) to a vector of floats and then truncates the result to
  11230. // a vector of either half or short.
  11231. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  11232. BinaryOperatorKind Opc, QualType ResultTy,
  11233. ExprValueKind VK, ExprObjectKind OK,
  11234. bool IsCompAssign, SourceLocation OpLoc,
  11235. FPOptions FPFeatures) {
  11236. auto &Context = S.getASTContext();
  11237. assert((isVector(ResultTy, Context.HalfTy) ||
  11238. isVector(ResultTy, Context.ShortTy)) &&
  11239. "Result must be a vector of half or short");
  11240. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  11241. isVector(RHS.get()->getType(), Context.HalfTy) &&
  11242. "both operands expected to be a half vector");
  11243. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  11244. QualType BinOpResTy = RHS.get()->getType();
  11245. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  11246. // change BinOpResTy to a vector of ints.
  11247. if (isVector(ResultTy, Context.ShortTy))
  11248. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  11249. if (IsCompAssign)
  11250. return new (Context) CompoundAssignOperator(
  11251. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  11252. OpLoc, FPFeatures);
  11253. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  11254. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  11255. VK, OK, OpLoc, FPFeatures);
  11256. return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
  11257. }
  11258. static std::pair<ExprResult, ExprResult>
  11259. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  11260. Expr *RHSExpr) {
  11261. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11262. if (!S.getLangOpts().CPlusPlus) {
  11263. // C cannot handle TypoExpr nodes on either side of a binop because it
  11264. // doesn't handle dependent types properly, so make sure any TypoExprs have
  11265. // been dealt with before checking the operands.
  11266. LHS = S.CorrectDelayedTyposInExpr(LHS);
  11267. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  11268. if (Opc != BO_Assign)
  11269. return ExprResult(E);
  11270. // Avoid correcting the RHS to the same Expr as the LHS.
  11271. Decl *D = getDeclFromExpr(E);
  11272. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  11273. });
  11274. }
  11275. return std::make_pair(LHS, RHS);
  11276. }
  11277. /// Returns true if conversion between vectors of halfs and vectors of floats
  11278. /// is needed.
  11279. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  11280. QualType SrcType) {
  11281. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  11282. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  11283. isVector(SrcType, Ctx.HalfTy);
  11284. }
  11285. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  11286. /// operator @p Opc at location @c TokLoc. This routine only supports
  11287. /// built-in operations; ActOnBinOp handles overloaded operators.
  11288. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  11289. BinaryOperatorKind Opc,
  11290. Expr *LHSExpr, Expr *RHSExpr) {
  11291. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  11292. // The syntax only allows initializer lists on the RHS of assignment,
  11293. // so we don't need to worry about accepting invalid code for
  11294. // non-assignment operators.
  11295. // C++11 5.17p9:
  11296. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  11297. // of x = {} is x = T().
  11298. InitializationKind Kind = InitializationKind::CreateDirectList(
  11299. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11300. InitializedEntity Entity =
  11301. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  11302. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  11303. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  11304. if (Init.isInvalid())
  11305. return Init;
  11306. RHSExpr = Init.get();
  11307. }
  11308. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11309. QualType ResultTy; // Result type of the binary operator.
  11310. // The following two variables are used for compound assignment operators
  11311. QualType CompLHSTy; // Type of LHS after promotions for computation
  11312. QualType CompResultTy; // Type of computation result
  11313. ExprValueKind VK = VK_RValue;
  11314. ExprObjectKind OK = OK_Ordinary;
  11315. bool ConvertHalfVec = false;
  11316. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11317. if (!LHS.isUsable() || !RHS.isUsable())
  11318. return ExprError();
  11319. if (getLangOpts().OpenCL) {
  11320. QualType LHSTy = LHSExpr->getType();
  11321. QualType RHSTy = RHSExpr->getType();
  11322. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  11323. // the ATOMIC_VAR_INIT macro.
  11324. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  11325. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11326. if (BO_Assign == Opc)
  11327. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  11328. else
  11329. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11330. return ExprError();
  11331. }
  11332. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11333. // only with a builtin functions and therefore should be disallowed here.
  11334. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  11335. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  11336. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  11337. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  11338. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11339. return ExprError();
  11340. }
  11341. }
  11342. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11343. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11344. if (Opc != BO_Assign && Opc != BO_Comma) {
  11345. checkOpenMPDeviceExpr(LHSExpr);
  11346. checkOpenMPDeviceExpr(RHSExpr);
  11347. }
  11348. }
  11349. switch (Opc) {
  11350. case BO_Assign:
  11351. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  11352. if (getLangOpts().CPlusPlus &&
  11353. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  11354. VK = LHS.get()->getValueKind();
  11355. OK = LHS.get()->getObjectKind();
  11356. }
  11357. if (!ResultTy.isNull()) {
  11358. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11359. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  11360. // Avoid copying a block to the heap if the block is assigned to a local
  11361. // auto variable that is declared in the same scope as the block. This
  11362. // optimization is unsafe if the local variable is declared in an outer
  11363. // scope. For example:
  11364. //
  11365. // BlockTy b;
  11366. // {
  11367. // b = ^{...};
  11368. // }
  11369. // // It is unsafe to invoke the block here if it wasn't copied to the
  11370. // // heap.
  11371. // b();
  11372. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  11373. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  11374. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11375. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11376. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11377. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11378. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  11379. NTCUC_Assignment, NTCUK_Copy);
  11380. }
  11381. RecordModifiableNonNullParam(*this, LHS.get());
  11382. break;
  11383. case BO_PtrMemD:
  11384. case BO_PtrMemI:
  11385. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11386. Opc == BO_PtrMemI);
  11387. break;
  11388. case BO_Mul:
  11389. case BO_Div:
  11390. ConvertHalfVec = true;
  11391. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11392. Opc == BO_Div);
  11393. break;
  11394. case BO_Rem:
  11395. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11396. break;
  11397. case BO_Add:
  11398. ConvertHalfVec = true;
  11399. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11400. break;
  11401. case BO_Sub:
  11402. ConvertHalfVec = true;
  11403. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11404. break;
  11405. case BO_Shl:
  11406. case BO_Shr:
  11407. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11408. break;
  11409. case BO_LE:
  11410. case BO_LT:
  11411. case BO_GE:
  11412. case BO_GT:
  11413. ConvertHalfVec = true;
  11414. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11415. break;
  11416. case BO_EQ:
  11417. case BO_NE:
  11418. ConvertHalfVec = true;
  11419. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11420. break;
  11421. case BO_Cmp:
  11422. ConvertHalfVec = true;
  11423. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11424. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11425. break;
  11426. case BO_And:
  11427. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11428. LLVM_FALLTHROUGH;
  11429. case BO_Xor:
  11430. case BO_Or:
  11431. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11432. break;
  11433. case BO_LAnd:
  11434. case BO_LOr:
  11435. ConvertHalfVec = true;
  11436. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11437. break;
  11438. case BO_MulAssign:
  11439. case BO_DivAssign:
  11440. ConvertHalfVec = true;
  11441. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11442. Opc == BO_DivAssign);
  11443. CompLHSTy = CompResultTy;
  11444. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11445. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11446. break;
  11447. case BO_RemAssign:
  11448. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11449. CompLHSTy = CompResultTy;
  11450. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11451. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11452. break;
  11453. case BO_AddAssign:
  11454. ConvertHalfVec = true;
  11455. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11456. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11457. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11458. break;
  11459. case BO_SubAssign:
  11460. ConvertHalfVec = true;
  11461. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11462. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11463. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11464. break;
  11465. case BO_ShlAssign:
  11466. case BO_ShrAssign:
  11467. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11468. CompLHSTy = CompResultTy;
  11469. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11470. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11471. break;
  11472. case BO_AndAssign:
  11473. case BO_OrAssign: // fallthrough
  11474. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11475. LLVM_FALLTHROUGH;
  11476. case BO_XorAssign:
  11477. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11478. CompLHSTy = CompResultTy;
  11479. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11480. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11481. break;
  11482. case BO_Comma:
  11483. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11484. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11485. VK = RHS.get()->getValueKind();
  11486. OK = RHS.get()->getObjectKind();
  11487. }
  11488. break;
  11489. }
  11490. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11491. return ExprError();
  11492. // Some of the binary operations require promoting operands of half vector to
  11493. // float vectors and truncating the result back to half vector. For now, we do
  11494. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11495. // arm64).
  11496. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11497. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11498. "both sides are half vectors or neither sides are");
  11499. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11500. LHS.get()->getType());
  11501. // Check for array bounds violations for both sides of the BinaryOperator
  11502. CheckArrayAccess(LHS.get());
  11503. CheckArrayAccess(RHS.get());
  11504. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11505. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11506. &Context.Idents.get("object_setClass"),
  11507. SourceLocation(), LookupOrdinaryName);
  11508. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11509. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11510. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11511. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11512. "object_setClass(")
  11513. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11514. ",")
  11515. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11516. }
  11517. else
  11518. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11519. }
  11520. else if (const ObjCIvarRefExpr *OIRE =
  11521. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11522. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11523. // Opc is not a compound assignment if CompResultTy is null.
  11524. if (CompResultTy.isNull()) {
  11525. if (ConvertHalfVec)
  11526. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11527. OpLoc, FPFeatures);
  11528. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11529. OK, OpLoc, FPFeatures);
  11530. }
  11531. // Handle compound assignments.
  11532. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11533. OK_ObjCProperty) {
  11534. VK = VK_LValue;
  11535. OK = LHS.get()->getObjectKind();
  11536. }
  11537. if (ConvertHalfVec)
  11538. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11539. OpLoc, FPFeatures);
  11540. return new (Context) CompoundAssignOperator(
  11541. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11542. OpLoc, FPFeatures);
  11543. }
  11544. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11545. /// operators are mixed in a way that suggests that the programmer forgot that
  11546. /// comparison operators have higher precedence. The most typical example of
  11547. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11548. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11549. SourceLocation OpLoc, Expr *LHSExpr,
  11550. Expr *RHSExpr) {
  11551. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11552. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11553. // Check that one of the sides is a comparison operator and the other isn't.
  11554. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11555. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11556. if (isLeftComp == isRightComp)
  11557. return;
  11558. // Bitwise operations are sometimes used as eager logical ops.
  11559. // Don't diagnose this.
  11560. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11561. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11562. if (isLeftBitwise || isRightBitwise)
  11563. return;
  11564. SourceRange DiagRange = isLeftComp
  11565. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11566. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11567. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11568. SourceRange ParensRange =
  11569. isLeftComp
  11570. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11571. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11572. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11573. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11574. SuggestParentheses(Self, OpLoc,
  11575. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11576. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11577. SuggestParentheses(Self, OpLoc,
  11578. Self.PDiag(diag::note_precedence_bitwise_first)
  11579. << BinaryOperator::getOpcodeStr(Opc),
  11580. ParensRange);
  11581. }
  11582. /// It accepts a '&&' expr that is inside a '||' one.
  11583. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11584. /// in parentheses.
  11585. static void
  11586. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11587. BinaryOperator *Bop) {
  11588. assert(Bop->getOpcode() == BO_LAnd);
  11589. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11590. << Bop->getSourceRange() << OpLoc;
  11591. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11592. Self.PDiag(diag::note_precedence_silence)
  11593. << Bop->getOpcodeStr(),
  11594. Bop->getSourceRange());
  11595. }
  11596. /// Returns true if the given expression can be evaluated as a constant
  11597. /// 'true'.
  11598. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11599. bool Res;
  11600. return !E->isValueDependent() &&
  11601. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11602. }
  11603. /// Returns true if the given expression can be evaluated as a constant
  11604. /// 'false'.
  11605. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11606. bool Res;
  11607. return !E->isValueDependent() &&
  11608. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11609. }
  11610. /// Look for '&&' in the left hand of a '||' expr.
  11611. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11612. Expr *LHSExpr, Expr *RHSExpr) {
  11613. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11614. if (Bop->getOpcode() == BO_LAnd) {
  11615. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11616. if (EvaluatesAsFalse(S, RHSExpr))
  11617. return;
  11618. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11619. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11620. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11621. } else if (Bop->getOpcode() == BO_LOr) {
  11622. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11623. // If it's "a || b && 1 || c" we didn't warn earlier for
  11624. // "a || b && 1", but warn now.
  11625. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11626. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11627. }
  11628. }
  11629. }
  11630. }
  11631. /// Look for '&&' in the right hand of a '||' expr.
  11632. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11633. Expr *LHSExpr, Expr *RHSExpr) {
  11634. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11635. if (Bop->getOpcode() == BO_LAnd) {
  11636. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11637. if (EvaluatesAsFalse(S, LHSExpr))
  11638. return;
  11639. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11640. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11641. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11642. }
  11643. }
  11644. }
  11645. /// Look for bitwise op in the left or right hand of a bitwise op with
  11646. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11647. /// the '&' expression in parentheses.
  11648. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11649. SourceLocation OpLoc, Expr *SubExpr) {
  11650. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11651. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11652. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11653. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11654. << Bop->getSourceRange() << OpLoc;
  11655. SuggestParentheses(S, Bop->getOperatorLoc(),
  11656. S.PDiag(diag::note_precedence_silence)
  11657. << Bop->getOpcodeStr(),
  11658. Bop->getSourceRange());
  11659. }
  11660. }
  11661. }
  11662. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11663. Expr *SubExpr, StringRef Shift) {
  11664. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11665. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11666. StringRef Op = Bop->getOpcodeStr();
  11667. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11668. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11669. SuggestParentheses(S, Bop->getOperatorLoc(),
  11670. S.PDiag(diag::note_precedence_silence) << Op,
  11671. Bop->getSourceRange());
  11672. }
  11673. }
  11674. }
  11675. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11676. Expr *LHSExpr, Expr *RHSExpr) {
  11677. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11678. if (!OCE)
  11679. return;
  11680. FunctionDecl *FD = OCE->getDirectCallee();
  11681. if (!FD || !FD->isOverloadedOperator())
  11682. return;
  11683. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11684. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11685. return;
  11686. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11687. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11688. << (Kind == OO_LessLess);
  11689. SuggestParentheses(S, OCE->getOperatorLoc(),
  11690. S.PDiag(diag::note_precedence_silence)
  11691. << (Kind == OO_LessLess ? "<<" : ">>"),
  11692. OCE->getSourceRange());
  11693. SuggestParentheses(
  11694. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11695. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11696. }
  11697. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11698. /// precedence.
  11699. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11700. SourceLocation OpLoc, Expr *LHSExpr,
  11701. Expr *RHSExpr){
  11702. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11703. if (BinaryOperator::isBitwiseOp(Opc))
  11704. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11705. // Diagnose "arg1 & arg2 | arg3"
  11706. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11707. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11708. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11709. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11710. }
  11711. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11712. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11713. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11714. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11715. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11716. }
  11717. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11718. || Opc == BO_Shr) {
  11719. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11720. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11721. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11722. }
  11723. // Warn on overloaded shift operators and comparisons, such as:
  11724. // cout << 5 == 4;
  11725. if (BinaryOperator::isComparisonOp(Opc))
  11726. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11727. }
  11728. // Binary Operators. 'Tok' is the token for the operator.
  11729. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11730. tok::TokenKind Kind,
  11731. Expr *LHSExpr, Expr *RHSExpr) {
  11732. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11733. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11734. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11735. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11736. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11737. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11738. }
  11739. /// Build an overloaded binary operator expression in the given scope.
  11740. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11741. BinaryOperatorKind Opc,
  11742. Expr *LHS, Expr *RHS) {
  11743. switch (Opc) {
  11744. case BO_Assign:
  11745. case BO_DivAssign:
  11746. case BO_RemAssign:
  11747. case BO_SubAssign:
  11748. case BO_AndAssign:
  11749. case BO_OrAssign:
  11750. case BO_XorAssign:
  11751. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11752. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11753. break;
  11754. default:
  11755. break;
  11756. }
  11757. // Find all of the overloaded operators visible from this
  11758. // point. We perform both an operator-name lookup from the local
  11759. // scope and an argument-dependent lookup based on the types of
  11760. // the arguments.
  11761. UnresolvedSet<16> Functions;
  11762. OverloadedOperatorKind OverOp
  11763. = BinaryOperator::getOverloadedOperator(Opc);
  11764. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11765. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11766. RHS->getType(), Functions);
  11767. // In C++20 onwards, we may have a second operator to look up.
  11768. if (S.getLangOpts().CPlusPlus2a) {
  11769. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
  11770. S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
  11771. RHS->getType(), Functions);
  11772. }
  11773. // Build the (potentially-overloaded, potentially-dependent)
  11774. // binary operation.
  11775. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11776. }
  11777. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11778. BinaryOperatorKind Opc,
  11779. Expr *LHSExpr, Expr *RHSExpr) {
  11780. ExprResult LHS, RHS;
  11781. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11782. if (!LHS.isUsable() || !RHS.isUsable())
  11783. return ExprError();
  11784. LHSExpr = LHS.get();
  11785. RHSExpr = RHS.get();
  11786. // We want to end up calling one of checkPseudoObjectAssignment
  11787. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11788. // both expressions are overloadable or either is type-dependent),
  11789. // or CreateBuiltinBinOp (in any other case). We also want to get
  11790. // any placeholder types out of the way.
  11791. // Handle pseudo-objects in the LHS.
  11792. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11793. // Assignments with a pseudo-object l-value need special analysis.
  11794. if (pty->getKind() == BuiltinType::PseudoObject &&
  11795. BinaryOperator::isAssignmentOp(Opc))
  11796. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11797. // Don't resolve overloads if the other type is overloadable.
  11798. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11799. // We can't actually test that if we still have a placeholder,
  11800. // though. Fortunately, none of the exceptions we see in that
  11801. // code below are valid when the LHS is an overload set. Note
  11802. // that an overload set can be dependently-typed, but it never
  11803. // instantiates to having an overloadable type.
  11804. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11805. if (resolvedRHS.isInvalid()) return ExprError();
  11806. RHSExpr = resolvedRHS.get();
  11807. if (RHSExpr->isTypeDependent() ||
  11808. RHSExpr->getType()->isOverloadableType())
  11809. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11810. }
  11811. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11812. // template, diagnose the missing 'template' keyword instead of diagnosing
  11813. // an invalid use of a bound member function.
  11814. //
  11815. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11816. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11817. if (Opc == BO_LT && inTemplateInstantiation() &&
  11818. (pty->getKind() == BuiltinType::BoundMember ||
  11819. pty->getKind() == BuiltinType::Overload)) {
  11820. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11821. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11822. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11823. return isa<FunctionTemplateDecl>(ND);
  11824. })) {
  11825. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11826. : OE->getNameLoc(),
  11827. diag::err_template_kw_missing)
  11828. << OE->getName().getAsString() << "";
  11829. return ExprError();
  11830. }
  11831. }
  11832. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11833. if (LHS.isInvalid()) return ExprError();
  11834. LHSExpr = LHS.get();
  11835. }
  11836. // Handle pseudo-objects in the RHS.
  11837. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11838. // An overload in the RHS can potentially be resolved by the type
  11839. // being assigned to.
  11840. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11841. if (getLangOpts().CPlusPlus &&
  11842. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11843. LHSExpr->getType()->isOverloadableType()))
  11844. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11845. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11846. }
  11847. // Don't resolve overloads if the other type is overloadable.
  11848. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11849. LHSExpr->getType()->isOverloadableType())
  11850. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11851. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11852. if (!resolvedRHS.isUsable()) return ExprError();
  11853. RHSExpr = resolvedRHS.get();
  11854. }
  11855. if (getLangOpts().CPlusPlus) {
  11856. // If either expression is type-dependent, always build an
  11857. // overloaded op.
  11858. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11859. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11860. // Otherwise, build an overloaded op if either expression has an
  11861. // overloadable type.
  11862. if (LHSExpr->getType()->isOverloadableType() ||
  11863. RHSExpr->getType()->isOverloadableType())
  11864. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11865. }
  11866. // Build a built-in binary operation.
  11867. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11868. }
  11869. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11870. if (T.isNull() || T->isDependentType())
  11871. return false;
  11872. if (!T->isPromotableIntegerType())
  11873. return true;
  11874. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11875. }
  11876. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11877. UnaryOperatorKind Opc,
  11878. Expr *InputExpr) {
  11879. ExprResult Input = InputExpr;
  11880. ExprValueKind VK = VK_RValue;
  11881. ExprObjectKind OK = OK_Ordinary;
  11882. QualType resultType;
  11883. bool CanOverflow = false;
  11884. bool ConvertHalfVec = false;
  11885. if (getLangOpts().OpenCL) {
  11886. QualType Ty = InputExpr->getType();
  11887. // The only legal unary operation for atomics is '&'.
  11888. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11889. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11890. // only with a builtin functions and therefore should be disallowed here.
  11891. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11892. || Ty->isBlockPointerType())) {
  11893. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11894. << InputExpr->getType()
  11895. << Input.get()->getSourceRange());
  11896. }
  11897. }
  11898. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11899. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11900. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11901. UnaryOperator::isArithmeticOp(Opc))
  11902. checkOpenMPDeviceExpr(InputExpr);
  11903. }
  11904. switch (Opc) {
  11905. case UO_PreInc:
  11906. case UO_PreDec:
  11907. case UO_PostInc:
  11908. case UO_PostDec:
  11909. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11910. OpLoc,
  11911. Opc == UO_PreInc ||
  11912. Opc == UO_PostInc,
  11913. Opc == UO_PreInc ||
  11914. Opc == UO_PreDec);
  11915. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11916. break;
  11917. case UO_AddrOf:
  11918. resultType = CheckAddressOfOperand(Input, OpLoc);
  11919. CheckAddressOfNoDeref(InputExpr);
  11920. RecordModifiableNonNullParam(*this, InputExpr);
  11921. break;
  11922. case UO_Deref: {
  11923. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11924. if (Input.isInvalid()) return ExprError();
  11925. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11926. break;
  11927. }
  11928. case UO_Plus:
  11929. case UO_Minus:
  11930. CanOverflow = Opc == UO_Minus &&
  11931. isOverflowingIntegerType(Context, Input.get()->getType());
  11932. Input = UsualUnaryConversions(Input.get());
  11933. if (Input.isInvalid()) return ExprError();
  11934. // Unary plus and minus require promoting an operand of half vector to a
  11935. // float vector and truncating the result back to a half vector. For now, we
  11936. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11937. // arm or arm64).
  11938. ConvertHalfVec =
  11939. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11940. // If the operand is a half vector, promote it to a float vector.
  11941. if (ConvertHalfVec)
  11942. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11943. resultType = Input.get()->getType();
  11944. if (resultType->isDependentType())
  11945. break;
  11946. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11947. break;
  11948. else if (resultType->isVectorType() &&
  11949. // The z vector extensions don't allow + or - with bool vectors.
  11950. (!Context.getLangOpts().ZVector ||
  11951. resultType->castAs<VectorType>()->getVectorKind() !=
  11952. VectorType::AltiVecBool))
  11953. break;
  11954. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11955. Opc == UO_Plus &&
  11956. resultType->isPointerType())
  11957. break;
  11958. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11959. << resultType << Input.get()->getSourceRange());
  11960. case UO_Not: // bitwise complement
  11961. Input = UsualUnaryConversions(Input.get());
  11962. if (Input.isInvalid())
  11963. return ExprError();
  11964. resultType = Input.get()->getType();
  11965. if (resultType->isDependentType())
  11966. break;
  11967. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11968. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11969. // C99 does not support '~' for complex conjugation.
  11970. Diag(OpLoc, diag::ext_integer_complement_complex)
  11971. << resultType << Input.get()->getSourceRange();
  11972. else if (resultType->hasIntegerRepresentation())
  11973. break;
  11974. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11975. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11976. // on vector float types.
  11977. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  11978. if (!T->isIntegerType())
  11979. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11980. << resultType << Input.get()->getSourceRange());
  11981. } else {
  11982. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11983. << resultType << Input.get()->getSourceRange());
  11984. }
  11985. break;
  11986. case UO_LNot: // logical negation
  11987. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11988. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11989. if (Input.isInvalid()) return ExprError();
  11990. resultType = Input.get()->getType();
  11991. // Though we still have to promote half FP to float...
  11992. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11993. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11994. resultType = Context.FloatTy;
  11995. }
  11996. if (resultType->isDependentType())
  11997. break;
  11998. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11999. // C99 6.5.3.3p1: ok, fallthrough;
  12000. if (Context.getLangOpts().CPlusPlus) {
  12001. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  12002. // operand contextually converted to bool.
  12003. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  12004. ScalarTypeToBooleanCastKind(resultType));
  12005. } else if (Context.getLangOpts().OpenCL &&
  12006. Context.getLangOpts().OpenCLVersion < 120) {
  12007. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  12008. // operate on scalar float types.
  12009. if (!resultType->isIntegerType() && !resultType->isPointerType())
  12010. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12011. << resultType << Input.get()->getSourceRange());
  12012. }
  12013. } else if (resultType->isExtVectorType()) {
  12014. if (Context.getLangOpts().OpenCL &&
  12015. Context.getLangOpts().OpenCLVersion < 120 &&
  12016. !Context.getLangOpts().OpenCLCPlusPlus) {
  12017. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  12018. // operate on vector float types.
  12019. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  12020. if (!T->isIntegerType())
  12021. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12022. << resultType << Input.get()->getSourceRange());
  12023. }
  12024. // Vector logical not returns the signed variant of the operand type.
  12025. resultType = GetSignedVectorType(resultType);
  12026. break;
  12027. } else {
  12028. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  12029. // type in C++. We should allow that here too.
  12030. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  12031. << resultType << Input.get()->getSourceRange());
  12032. }
  12033. // LNot always has type int. C99 6.5.3.3p5.
  12034. // In C++, it's bool. C++ 5.3.1p8
  12035. resultType = Context.getLogicalOperationType();
  12036. break;
  12037. case UO_Real:
  12038. case UO_Imag:
  12039. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  12040. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  12041. // complex l-values to ordinary l-values and all other values to r-values.
  12042. if (Input.isInvalid()) return ExprError();
  12043. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  12044. if (Input.get()->getValueKind() != VK_RValue &&
  12045. Input.get()->getObjectKind() == OK_Ordinary)
  12046. VK = Input.get()->getValueKind();
  12047. } else if (!getLangOpts().CPlusPlus) {
  12048. // In C, a volatile scalar is read by __imag. In C++, it is not.
  12049. Input = DefaultLvalueConversion(Input.get());
  12050. }
  12051. break;
  12052. case UO_Extension:
  12053. resultType = Input.get()->getType();
  12054. VK = Input.get()->getValueKind();
  12055. OK = Input.get()->getObjectKind();
  12056. break;
  12057. case UO_Coawait:
  12058. // It's unnecessary to represent the pass-through operator co_await in the
  12059. // AST; just return the input expression instead.
  12060. assert(!Input.get()->getType()->isDependentType() &&
  12061. "the co_await expression must be non-dependant before "
  12062. "building operator co_await");
  12063. return Input;
  12064. }
  12065. if (resultType.isNull() || Input.isInvalid())
  12066. return ExprError();
  12067. // Check for array bounds violations in the operand of the UnaryOperator,
  12068. // except for the '*' and '&' operators that have to be handled specially
  12069. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  12070. // that are explicitly defined as valid by the standard).
  12071. if (Opc != UO_AddrOf && Opc != UO_Deref)
  12072. CheckArrayAccess(Input.get());
  12073. auto *UO = new (Context)
  12074. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  12075. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  12076. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  12077. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  12078. // Convert the result back to a half vector.
  12079. if (ConvertHalfVec)
  12080. return convertVector(UO, Context.HalfTy, *this);
  12081. return UO;
  12082. }
  12083. /// Determine whether the given expression is a qualified member
  12084. /// access expression, of a form that could be turned into a pointer to member
  12085. /// with the address-of operator.
  12086. bool Sema::isQualifiedMemberAccess(Expr *E) {
  12087. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12088. if (!DRE->getQualifier())
  12089. return false;
  12090. ValueDecl *VD = DRE->getDecl();
  12091. if (!VD->isCXXClassMember())
  12092. return false;
  12093. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  12094. return true;
  12095. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  12096. return Method->isInstance();
  12097. return false;
  12098. }
  12099. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12100. if (!ULE->getQualifier())
  12101. return false;
  12102. for (NamedDecl *D : ULE->decls()) {
  12103. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  12104. if (Method->isInstance())
  12105. return true;
  12106. } else {
  12107. // Overload set does not contain methods.
  12108. break;
  12109. }
  12110. }
  12111. return false;
  12112. }
  12113. return false;
  12114. }
  12115. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  12116. UnaryOperatorKind Opc, Expr *Input) {
  12117. // First things first: handle placeholders so that the
  12118. // overloaded-operator check considers the right type.
  12119. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  12120. // Increment and decrement of pseudo-object references.
  12121. if (pty->getKind() == BuiltinType::PseudoObject &&
  12122. UnaryOperator::isIncrementDecrementOp(Opc))
  12123. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  12124. // extension is always a builtin operator.
  12125. if (Opc == UO_Extension)
  12126. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12127. // & gets special logic for several kinds of placeholder.
  12128. // The builtin code knows what to do.
  12129. if (Opc == UO_AddrOf &&
  12130. (pty->getKind() == BuiltinType::Overload ||
  12131. pty->getKind() == BuiltinType::UnknownAny ||
  12132. pty->getKind() == BuiltinType::BoundMember))
  12133. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12134. // Anything else needs to be handled now.
  12135. ExprResult Result = CheckPlaceholderExpr(Input);
  12136. if (Result.isInvalid()) return ExprError();
  12137. Input = Result.get();
  12138. }
  12139. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  12140. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  12141. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  12142. // Find all of the overloaded operators visible from this
  12143. // point. We perform both an operator-name lookup from the local
  12144. // scope and an argument-dependent lookup based on the types of
  12145. // the arguments.
  12146. UnresolvedSet<16> Functions;
  12147. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  12148. if (S && OverOp != OO_None)
  12149. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  12150. Functions);
  12151. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  12152. }
  12153. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12154. }
  12155. // Unary Operators. 'Tok' is the token for the operator.
  12156. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  12157. tok::TokenKind Op, Expr *Input) {
  12158. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  12159. }
  12160. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  12161. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  12162. LabelDecl *TheDecl) {
  12163. TheDecl->markUsed(Context);
  12164. // Create the AST node. The address of a label always has type 'void*'.
  12165. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  12166. Context.getPointerType(Context.VoidTy));
  12167. }
  12168. void Sema::ActOnStartStmtExpr() {
  12169. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  12170. }
  12171. void Sema::ActOnStmtExprError() {
  12172. // Note that function is also called by TreeTransform when leaving a
  12173. // StmtExpr scope without rebuilding anything.
  12174. DiscardCleanupsInEvaluationContext();
  12175. PopExpressionEvaluationContext();
  12176. }
  12177. ExprResult
  12178. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  12179. SourceLocation RPLoc) { // "({..})"
  12180. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  12181. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  12182. if (hasAnyUnrecoverableErrorsInThisFunction())
  12183. DiscardCleanupsInEvaluationContext();
  12184. assert(!Cleanup.exprNeedsCleanups() &&
  12185. "cleanups within StmtExpr not correctly bound!");
  12186. PopExpressionEvaluationContext();
  12187. // FIXME: there are a variety of strange constraints to enforce here, for
  12188. // example, it is not possible to goto into a stmt expression apparently.
  12189. // More semantic analysis is needed.
  12190. // If there are sub-stmts in the compound stmt, take the type of the last one
  12191. // as the type of the stmtexpr.
  12192. QualType Ty = Context.VoidTy;
  12193. bool StmtExprMayBindToTemp = false;
  12194. if (!Compound->body_empty()) {
  12195. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  12196. if (const auto *LastStmt =
  12197. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  12198. if (const Expr *Value = LastStmt->getExprStmt()) {
  12199. StmtExprMayBindToTemp = true;
  12200. Ty = Value->getType();
  12201. }
  12202. }
  12203. }
  12204. // FIXME: Check that expression type is complete/non-abstract; statement
  12205. // expressions are not lvalues.
  12206. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  12207. if (StmtExprMayBindToTemp)
  12208. return MaybeBindToTemporary(ResStmtExpr);
  12209. return ResStmtExpr;
  12210. }
  12211. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  12212. if (ER.isInvalid())
  12213. return ExprError();
  12214. // Do function/array conversion on the last expression, but not
  12215. // lvalue-to-rvalue. However, initialize an unqualified type.
  12216. ER = DefaultFunctionArrayConversion(ER.get());
  12217. if (ER.isInvalid())
  12218. return ExprError();
  12219. Expr *E = ER.get();
  12220. if (E->isTypeDependent())
  12221. return E;
  12222. // In ARC, if the final expression ends in a consume, splice
  12223. // the consume out and bind it later. In the alternate case
  12224. // (when dealing with a retainable type), the result
  12225. // initialization will create a produce. In both cases the
  12226. // result will be +1, and we'll need to balance that out with
  12227. // a bind.
  12228. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  12229. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  12230. return Cast->getSubExpr();
  12231. // FIXME: Provide a better location for the initialization.
  12232. return PerformCopyInitialization(
  12233. InitializedEntity::InitializeStmtExprResult(
  12234. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  12235. SourceLocation(), E);
  12236. }
  12237. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  12238. TypeSourceInfo *TInfo,
  12239. ArrayRef<OffsetOfComponent> Components,
  12240. SourceLocation RParenLoc) {
  12241. QualType ArgTy = TInfo->getType();
  12242. bool Dependent = ArgTy->isDependentType();
  12243. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  12244. // We must have at least one component that refers to the type, and the first
  12245. // one is known to be a field designator. Verify that the ArgTy represents
  12246. // a struct/union/class.
  12247. if (!Dependent && !ArgTy->isRecordType())
  12248. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  12249. << ArgTy << TypeRange);
  12250. // Type must be complete per C99 7.17p3 because a declaring a variable
  12251. // with an incomplete type would be ill-formed.
  12252. if (!Dependent
  12253. && RequireCompleteType(BuiltinLoc, ArgTy,
  12254. diag::err_offsetof_incomplete_type, TypeRange))
  12255. return ExprError();
  12256. bool DidWarnAboutNonPOD = false;
  12257. QualType CurrentType = ArgTy;
  12258. SmallVector<OffsetOfNode, 4> Comps;
  12259. SmallVector<Expr*, 4> Exprs;
  12260. for (const OffsetOfComponent &OC : Components) {
  12261. if (OC.isBrackets) {
  12262. // Offset of an array sub-field. TODO: Should we allow vector elements?
  12263. if (!CurrentType->isDependentType()) {
  12264. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  12265. if(!AT)
  12266. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  12267. << CurrentType);
  12268. CurrentType = AT->getElementType();
  12269. } else
  12270. CurrentType = Context.DependentTy;
  12271. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  12272. if (IdxRval.isInvalid())
  12273. return ExprError();
  12274. Expr *Idx = IdxRval.get();
  12275. // The expression must be an integral expression.
  12276. // FIXME: An integral constant expression?
  12277. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  12278. !Idx->getType()->isIntegerType())
  12279. return ExprError(
  12280. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  12281. << Idx->getSourceRange());
  12282. // Record this array index.
  12283. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  12284. Exprs.push_back(Idx);
  12285. continue;
  12286. }
  12287. // Offset of a field.
  12288. if (CurrentType->isDependentType()) {
  12289. // We have the offset of a field, but we can't look into the dependent
  12290. // type. Just record the identifier of the field.
  12291. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  12292. CurrentType = Context.DependentTy;
  12293. continue;
  12294. }
  12295. // We need to have a complete type to look into.
  12296. if (RequireCompleteType(OC.LocStart, CurrentType,
  12297. diag::err_offsetof_incomplete_type))
  12298. return ExprError();
  12299. // Look for the designated field.
  12300. const RecordType *RC = CurrentType->getAs<RecordType>();
  12301. if (!RC)
  12302. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  12303. << CurrentType);
  12304. RecordDecl *RD = RC->getDecl();
  12305. // C++ [lib.support.types]p5:
  12306. // The macro offsetof accepts a restricted set of type arguments in this
  12307. // International Standard. type shall be a POD structure or a POD union
  12308. // (clause 9).
  12309. // C++11 [support.types]p4:
  12310. // If type is not a standard-layout class (Clause 9), the results are
  12311. // undefined.
  12312. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  12313. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  12314. unsigned DiagID =
  12315. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  12316. : diag::ext_offsetof_non_pod_type;
  12317. if (!IsSafe && !DidWarnAboutNonPOD &&
  12318. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  12319. PDiag(DiagID)
  12320. << SourceRange(Components[0].LocStart, OC.LocEnd)
  12321. << CurrentType))
  12322. DidWarnAboutNonPOD = true;
  12323. }
  12324. // Look for the field.
  12325. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  12326. LookupQualifiedName(R, RD);
  12327. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  12328. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  12329. if (!MemberDecl) {
  12330. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  12331. MemberDecl = IndirectMemberDecl->getAnonField();
  12332. }
  12333. if (!MemberDecl)
  12334. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  12335. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  12336. OC.LocEnd));
  12337. // C99 7.17p3:
  12338. // (If the specified member is a bit-field, the behavior is undefined.)
  12339. //
  12340. // We diagnose this as an error.
  12341. if (MemberDecl->isBitField()) {
  12342. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  12343. << MemberDecl->getDeclName()
  12344. << SourceRange(BuiltinLoc, RParenLoc);
  12345. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  12346. return ExprError();
  12347. }
  12348. RecordDecl *Parent = MemberDecl->getParent();
  12349. if (IndirectMemberDecl)
  12350. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  12351. // If the member was found in a base class, introduce OffsetOfNodes for
  12352. // the base class indirections.
  12353. CXXBasePaths Paths;
  12354. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  12355. Paths)) {
  12356. if (Paths.getDetectedVirtual()) {
  12357. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  12358. << MemberDecl->getDeclName()
  12359. << SourceRange(BuiltinLoc, RParenLoc);
  12360. return ExprError();
  12361. }
  12362. CXXBasePath &Path = Paths.front();
  12363. for (const CXXBasePathElement &B : Path)
  12364. Comps.push_back(OffsetOfNode(B.Base));
  12365. }
  12366. if (IndirectMemberDecl) {
  12367. for (auto *FI : IndirectMemberDecl->chain()) {
  12368. assert(isa<FieldDecl>(FI));
  12369. Comps.push_back(OffsetOfNode(OC.LocStart,
  12370. cast<FieldDecl>(FI), OC.LocEnd));
  12371. }
  12372. } else
  12373. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  12374. CurrentType = MemberDecl->getType().getNonReferenceType();
  12375. }
  12376. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  12377. Comps, Exprs, RParenLoc);
  12378. }
  12379. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  12380. SourceLocation BuiltinLoc,
  12381. SourceLocation TypeLoc,
  12382. ParsedType ParsedArgTy,
  12383. ArrayRef<OffsetOfComponent> Components,
  12384. SourceLocation RParenLoc) {
  12385. TypeSourceInfo *ArgTInfo;
  12386. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12387. if (ArgTy.isNull())
  12388. return ExprError();
  12389. if (!ArgTInfo)
  12390. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12391. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12392. }
  12393. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12394. Expr *CondExpr,
  12395. Expr *LHSExpr, Expr *RHSExpr,
  12396. SourceLocation RPLoc) {
  12397. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12398. ExprValueKind VK = VK_RValue;
  12399. ExprObjectKind OK = OK_Ordinary;
  12400. QualType resType;
  12401. bool ValueDependent = false;
  12402. bool CondIsTrue = false;
  12403. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12404. resType = Context.DependentTy;
  12405. ValueDependent = true;
  12406. } else {
  12407. // The conditional expression is required to be a constant expression.
  12408. llvm::APSInt condEval(32);
  12409. ExprResult CondICE
  12410. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12411. diag::err_typecheck_choose_expr_requires_constant, false);
  12412. if (CondICE.isInvalid())
  12413. return ExprError();
  12414. CondExpr = CondICE.get();
  12415. CondIsTrue = condEval.getZExtValue();
  12416. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12417. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12418. resType = ActiveExpr->getType();
  12419. ValueDependent = ActiveExpr->isValueDependent();
  12420. VK = ActiveExpr->getValueKind();
  12421. OK = ActiveExpr->getObjectKind();
  12422. }
  12423. return new (Context)
  12424. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12425. CondIsTrue, resType->isDependentType(), ValueDependent);
  12426. }
  12427. //===----------------------------------------------------------------------===//
  12428. // Clang Extensions.
  12429. //===----------------------------------------------------------------------===//
  12430. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12431. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12432. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12433. if (LangOpts.CPlusPlus) {
  12434. MangleNumberingContext *MCtx;
  12435. Decl *ManglingContextDecl;
  12436. std::tie(MCtx, ManglingContextDecl) =
  12437. getCurrentMangleNumberContext(Block->getDeclContext());
  12438. if (MCtx) {
  12439. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12440. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12441. }
  12442. }
  12443. PushBlockScope(CurScope, Block);
  12444. CurContext->addDecl(Block);
  12445. if (CurScope)
  12446. PushDeclContext(CurScope, Block);
  12447. else
  12448. CurContext = Block;
  12449. getCurBlock()->HasImplicitReturnType = true;
  12450. // Enter a new evaluation context to insulate the block from any
  12451. // cleanups from the enclosing full-expression.
  12452. PushExpressionEvaluationContext(
  12453. ExpressionEvaluationContext::PotentiallyEvaluated);
  12454. }
  12455. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12456. Scope *CurScope) {
  12457. assert(ParamInfo.getIdentifier() == nullptr &&
  12458. "block-id should have no identifier!");
  12459. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12460. BlockScopeInfo *CurBlock = getCurBlock();
  12461. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12462. QualType T = Sig->getType();
  12463. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12464. // in turn, make the block expression contain unexpanded parameter packs.
  12465. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12466. // Drop the parameters.
  12467. FunctionProtoType::ExtProtoInfo EPI;
  12468. EPI.HasTrailingReturn = false;
  12469. EPI.TypeQuals.addConst();
  12470. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12471. Sig = Context.getTrivialTypeSourceInfo(T);
  12472. }
  12473. // GetTypeForDeclarator always produces a function type for a block
  12474. // literal signature. Furthermore, it is always a FunctionProtoType
  12475. // unless the function was written with a typedef.
  12476. assert(T->isFunctionType() &&
  12477. "GetTypeForDeclarator made a non-function block signature");
  12478. // Look for an explicit signature in that function type.
  12479. FunctionProtoTypeLoc ExplicitSignature;
  12480. if ((ExplicitSignature = Sig->getTypeLoc()
  12481. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12482. // Check whether that explicit signature was synthesized by
  12483. // GetTypeForDeclarator. If so, don't save that as part of the
  12484. // written signature.
  12485. if (ExplicitSignature.getLocalRangeBegin() ==
  12486. ExplicitSignature.getLocalRangeEnd()) {
  12487. // This would be much cheaper if we stored TypeLocs instead of
  12488. // TypeSourceInfos.
  12489. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12490. unsigned Size = Result.getFullDataSize();
  12491. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12492. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12493. ExplicitSignature = FunctionProtoTypeLoc();
  12494. }
  12495. }
  12496. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12497. CurBlock->FunctionType = T;
  12498. const FunctionType *Fn = T->getAs<FunctionType>();
  12499. QualType RetTy = Fn->getReturnType();
  12500. bool isVariadic =
  12501. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12502. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12503. // Context.DependentTy is used as a placeholder for a missing block
  12504. // return type. TODO: what should we do with declarators like:
  12505. // ^ * { ... }
  12506. // If the answer is "apply template argument deduction"....
  12507. if (RetTy != Context.DependentTy) {
  12508. CurBlock->ReturnType = RetTy;
  12509. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12510. CurBlock->HasImplicitReturnType = false;
  12511. }
  12512. // Push block parameters from the declarator if we had them.
  12513. SmallVector<ParmVarDecl*, 8> Params;
  12514. if (ExplicitSignature) {
  12515. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12516. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12517. if (Param->getIdentifier() == nullptr &&
  12518. !Param->isImplicit() &&
  12519. !Param->isInvalidDecl() &&
  12520. !getLangOpts().CPlusPlus)
  12521. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12522. Params.push_back(Param);
  12523. }
  12524. // Fake up parameter variables if we have a typedef, like
  12525. // ^ fntype { ... }
  12526. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12527. for (const auto &I : Fn->param_types()) {
  12528. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12529. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12530. Params.push_back(Param);
  12531. }
  12532. }
  12533. // Set the parameters on the block decl.
  12534. if (!Params.empty()) {
  12535. CurBlock->TheDecl->setParams(Params);
  12536. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12537. /*CheckParameterNames=*/false);
  12538. }
  12539. // Finally we can process decl attributes.
  12540. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12541. // Put the parameter variables in scope.
  12542. for (auto AI : CurBlock->TheDecl->parameters()) {
  12543. AI->setOwningFunction(CurBlock->TheDecl);
  12544. // If this has an identifier, add it to the scope stack.
  12545. if (AI->getIdentifier()) {
  12546. CheckShadow(CurBlock->TheScope, AI);
  12547. PushOnScopeChains(AI, CurBlock->TheScope);
  12548. }
  12549. }
  12550. }
  12551. /// ActOnBlockError - If there is an error parsing a block, this callback
  12552. /// is invoked to pop the information about the block from the action impl.
  12553. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12554. // Leave the expression-evaluation context.
  12555. DiscardCleanupsInEvaluationContext();
  12556. PopExpressionEvaluationContext();
  12557. // Pop off CurBlock, handle nested blocks.
  12558. PopDeclContext();
  12559. PopFunctionScopeInfo();
  12560. }
  12561. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12562. /// literal was successfully completed. ^(int x){...}
  12563. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12564. Stmt *Body, Scope *CurScope) {
  12565. // If blocks are disabled, emit an error.
  12566. if (!LangOpts.Blocks)
  12567. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12568. // Leave the expression-evaluation context.
  12569. if (hasAnyUnrecoverableErrorsInThisFunction())
  12570. DiscardCleanupsInEvaluationContext();
  12571. assert(!Cleanup.exprNeedsCleanups() &&
  12572. "cleanups within block not correctly bound!");
  12573. PopExpressionEvaluationContext();
  12574. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12575. BlockDecl *BD = BSI->TheDecl;
  12576. if (BSI->HasImplicitReturnType)
  12577. deduceClosureReturnType(*BSI);
  12578. QualType RetTy = Context.VoidTy;
  12579. if (!BSI->ReturnType.isNull())
  12580. RetTy = BSI->ReturnType;
  12581. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12582. QualType BlockTy;
  12583. // If the user wrote a function type in some form, try to use that.
  12584. if (!BSI->FunctionType.isNull()) {
  12585. const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
  12586. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12587. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12588. // Turn protoless block types into nullary block types.
  12589. if (isa<FunctionNoProtoType>(FTy)) {
  12590. FunctionProtoType::ExtProtoInfo EPI;
  12591. EPI.ExtInfo = Ext;
  12592. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12593. // Otherwise, if we don't need to change anything about the function type,
  12594. // preserve its sugar structure.
  12595. } else if (FTy->getReturnType() == RetTy &&
  12596. (!NoReturn || FTy->getNoReturnAttr())) {
  12597. BlockTy = BSI->FunctionType;
  12598. // Otherwise, make the minimal modifications to the function type.
  12599. } else {
  12600. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12601. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12602. EPI.TypeQuals = Qualifiers();
  12603. EPI.ExtInfo = Ext;
  12604. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12605. }
  12606. // If we don't have a function type, just build one from nothing.
  12607. } else {
  12608. FunctionProtoType::ExtProtoInfo EPI;
  12609. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12610. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12611. }
  12612. DiagnoseUnusedParameters(BD->parameters());
  12613. BlockTy = Context.getBlockPointerType(BlockTy);
  12614. // If needed, diagnose invalid gotos and switches in the block.
  12615. if (getCurFunction()->NeedsScopeChecking() &&
  12616. !PP.isCodeCompletionEnabled())
  12617. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12618. BD->setBody(cast<CompoundStmt>(Body));
  12619. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12620. DiagnoseUnguardedAvailabilityViolations(BD);
  12621. // Try to apply the named return value optimization. We have to check again
  12622. // if we can do this, though, because blocks keep return statements around
  12623. // to deduce an implicit return type.
  12624. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12625. !BD->isDependentContext())
  12626. computeNRVO(Body, BSI);
  12627. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  12628. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  12629. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  12630. NTCUK_Destruct|NTCUK_Copy);
  12631. PopDeclContext();
  12632. // Pop the block scope now but keep it alive to the end of this function.
  12633. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12634. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12635. // Set the captured variables on the block.
  12636. SmallVector<BlockDecl::Capture, 4> Captures;
  12637. for (Capture &Cap : BSI->Captures) {
  12638. if (Cap.isInvalid() || Cap.isThisCapture())
  12639. continue;
  12640. VarDecl *Var = Cap.getVariable();
  12641. Expr *CopyExpr = nullptr;
  12642. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12643. if (const RecordType *Record =
  12644. Cap.getCaptureType()->getAs<RecordType>()) {
  12645. // The capture logic needs the destructor, so make sure we mark it.
  12646. // Usually this is unnecessary because most local variables have
  12647. // their destructors marked at declaration time, but parameters are
  12648. // an exception because it's technically only the call site that
  12649. // actually requires the destructor.
  12650. if (isa<ParmVarDecl>(Var))
  12651. FinalizeVarWithDestructor(Var, Record);
  12652. // Enter a separate potentially-evaluated context while building block
  12653. // initializers to isolate their cleanups from those of the block
  12654. // itself.
  12655. // FIXME: Is this appropriate even when the block itself occurs in an
  12656. // unevaluated operand?
  12657. EnterExpressionEvaluationContext EvalContext(
  12658. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12659. SourceLocation Loc = Cap.getLocation();
  12660. ExprResult Result = BuildDeclarationNameExpr(
  12661. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12662. // According to the blocks spec, the capture of a variable from
  12663. // the stack requires a const copy constructor. This is not true
  12664. // of the copy/move done to move a __block variable to the heap.
  12665. if (!Result.isInvalid() &&
  12666. !Result.get()->getType().isConstQualified()) {
  12667. Result = ImpCastExprToType(Result.get(),
  12668. Result.get()->getType().withConst(),
  12669. CK_NoOp, VK_LValue);
  12670. }
  12671. if (!Result.isInvalid()) {
  12672. Result = PerformCopyInitialization(
  12673. InitializedEntity::InitializeBlock(Var->getLocation(),
  12674. Cap.getCaptureType(), false),
  12675. Loc, Result.get());
  12676. }
  12677. // Build a full-expression copy expression if initialization
  12678. // succeeded and used a non-trivial constructor. Recover from
  12679. // errors by pretending that the copy isn't necessary.
  12680. if (!Result.isInvalid() &&
  12681. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12682. ->isTrivial()) {
  12683. Result = MaybeCreateExprWithCleanups(Result);
  12684. CopyExpr = Result.get();
  12685. }
  12686. }
  12687. }
  12688. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12689. CopyExpr);
  12690. Captures.push_back(NewCap);
  12691. }
  12692. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12693. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12694. // If the block isn't obviously global, i.e. it captures anything at
  12695. // all, then we need to do a few things in the surrounding context:
  12696. if (Result->getBlockDecl()->hasCaptures()) {
  12697. // First, this expression has a new cleanup object.
  12698. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12699. Cleanup.setExprNeedsCleanups(true);
  12700. // It also gets a branch-protected scope if any of the captured
  12701. // variables needs destruction.
  12702. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12703. const VarDecl *var = CI.getVariable();
  12704. if (var->getType().isDestructedType() != QualType::DK_none) {
  12705. setFunctionHasBranchProtectedScope();
  12706. break;
  12707. }
  12708. }
  12709. }
  12710. if (getCurFunction())
  12711. getCurFunction()->addBlock(BD);
  12712. return Result;
  12713. }
  12714. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12715. SourceLocation RPLoc) {
  12716. TypeSourceInfo *TInfo;
  12717. GetTypeFromParser(Ty, &TInfo);
  12718. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12719. }
  12720. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12721. Expr *E, TypeSourceInfo *TInfo,
  12722. SourceLocation RPLoc) {
  12723. Expr *OrigExpr = E;
  12724. bool IsMS = false;
  12725. // CUDA device code does not support varargs.
  12726. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12727. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12728. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12729. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12730. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12731. }
  12732. }
  12733. // NVPTX does not support va_arg expression.
  12734. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12735. Context.getTargetInfo().getTriple().isNVPTX())
  12736. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12737. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12738. // as Microsoft ABI on an actual Microsoft platform, where
  12739. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12740. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12741. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12742. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12743. if (Context.hasSameType(MSVaListType, E->getType())) {
  12744. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12745. return ExprError();
  12746. IsMS = true;
  12747. }
  12748. }
  12749. // Get the va_list type
  12750. QualType VaListType = Context.getBuiltinVaListType();
  12751. if (!IsMS) {
  12752. if (VaListType->isArrayType()) {
  12753. // Deal with implicit array decay; for example, on x86-64,
  12754. // va_list is an array, but it's supposed to decay to
  12755. // a pointer for va_arg.
  12756. VaListType = Context.getArrayDecayedType(VaListType);
  12757. // Make sure the input expression also decays appropriately.
  12758. ExprResult Result = UsualUnaryConversions(E);
  12759. if (Result.isInvalid())
  12760. return ExprError();
  12761. E = Result.get();
  12762. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12763. // If va_list is a record type and we are compiling in C++ mode,
  12764. // check the argument using reference binding.
  12765. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12766. Context, Context.getLValueReferenceType(VaListType), false);
  12767. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12768. if (Init.isInvalid())
  12769. return ExprError();
  12770. E = Init.getAs<Expr>();
  12771. } else {
  12772. // Otherwise, the va_list argument must be an l-value because
  12773. // it is modified by va_arg.
  12774. if (!E->isTypeDependent() &&
  12775. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12776. return ExprError();
  12777. }
  12778. }
  12779. if (!IsMS && !E->isTypeDependent() &&
  12780. !Context.hasSameType(VaListType, E->getType()))
  12781. return ExprError(
  12782. Diag(E->getBeginLoc(),
  12783. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12784. << OrigExpr->getType() << E->getSourceRange());
  12785. if (!TInfo->getType()->isDependentType()) {
  12786. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12787. diag::err_second_parameter_to_va_arg_incomplete,
  12788. TInfo->getTypeLoc()))
  12789. return ExprError();
  12790. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12791. TInfo->getType(),
  12792. diag::err_second_parameter_to_va_arg_abstract,
  12793. TInfo->getTypeLoc()))
  12794. return ExprError();
  12795. if (!TInfo->getType().isPODType(Context)) {
  12796. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12797. TInfo->getType()->isObjCLifetimeType()
  12798. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12799. : diag::warn_second_parameter_to_va_arg_not_pod)
  12800. << TInfo->getType()
  12801. << TInfo->getTypeLoc().getSourceRange();
  12802. }
  12803. // Check for va_arg where arguments of the given type will be promoted
  12804. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12805. QualType PromoteType;
  12806. if (TInfo->getType()->isPromotableIntegerType()) {
  12807. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12808. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12809. PromoteType = QualType();
  12810. }
  12811. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12812. PromoteType = Context.DoubleTy;
  12813. if (!PromoteType.isNull())
  12814. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12815. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12816. << TInfo->getType()
  12817. << PromoteType
  12818. << TInfo->getTypeLoc().getSourceRange());
  12819. }
  12820. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12821. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12822. }
  12823. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12824. // The type of __null will be int or long, depending on the size of
  12825. // pointers on the target.
  12826. QualType Ty;
  12827. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12828. if (pw == Context.getTargetInfo().getIntWidth())
  12829. Ty = Context.IntTy;
  12830. else if (pw == Context.getTargetInfo().getLongWidth())
  12831. Ty = Context.LongTy;
  12832. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12833. Ty = Context.LongLongTy;
  12834. else {
  12835. llvm_unreachable("I don't know size of pointer!");
  12836. }
  12837. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12838. }
  12839. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12840. SourceLocation BuiltinLoc,
  12841. SourceLocation RPLoc) {
  12842. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12843. }
  12844. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12845. SourceLocation BuiltinLoc,
  12846. SourceLocation RPLoc,
  12847. DeclContext *ParentContext) {
  12848. return new (Context)
  12849. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12850. }
  12851. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12852. bool Diagnose) {
  12853. if (!getLangOpts().ObjC)
  12854. return false;
  12855. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12856. if (!PT)
  12857. return false;
  12858. if (!PT->isObjCIdType()) {
  12859. // Check if the destination is the 'NSString' interface.
  12860. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12861. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12862. return false;
  12863. }
  12864. // Ignore any parens, implicit casts (should only be
  12865. // array-to-pointer decays), and not-so-opaque values. The last is
  12866. // important for making this trigger for property assignments.
  12867. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12868. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12869. if (OV->getSourceExpr())
  12870. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12871. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12872. if (!SL || !SL->isAscii())
  12873. return false;
  12874. if (Diagnose) {
  12875. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12876. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12877. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12878. }
  12879. return true;
  12880. }
  12881. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12882. const Expr *SrcExpr) {
  12883. if (!DstType->isFunctionPointerType() ||
  12884. !SrcExpr->getType()->isFunctionType())
  12885. return false;
  12886. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12887. if (!DRE)
  12888. return false;
  12889. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12890. if (!FD)
  12891. return false;
  12892. return !S.checkAddressOfFunctionIsAvailable(FD,
  12893. /*Complain=*/true,
  12894. SrcExpr->getBeginLoc());
  12895. }
  12896. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12897. SourceLocation Loc,
  12898. QualType DstType, QualType SrcType,
  12899. Expr *SrcExpr, AssignmentAction Action,
  12900. bool *Complained) {
  12901. if (Complained)
  12902. *Complained = false;
  12903. // Decode the result (notice that AST's are still created for extensions).
  12904. bool CheckInferredResultType = false;
  12905. bool isInvalid = false;
  12906. unsigned DiagKind = 0;
  12907. FixItHint Hint;
  12908. ConversionFixItGenerator ConvHints;
  12909. bool MayHaveConvFixit = false;
  12910. bool MayHaveFunctionDiff = false;
  12911. const ObjCInterfaceDecl *IFace = nullptr;
  12912. const ObjCProtocolDecl *PDecl = nullptr;
  12913. switch (ConvTy) {
  12914. case Compatible:
  12915. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12916. return false;
  12917. case PointerToInt:
  12918. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12919. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12920. MayHaveConvFixit = true;
  12921. break;
  12922. case IntToPointer:
  12923. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12924. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12925. MayHaveConvFixit = true;
  12926. break;
  12927. case IncompatiblePointer:
  12928. if (Action == AA_Passing_CFAudited)
  12929. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12930. else if (SrcType->isFunctionPointerType() &&
  12931. DstType->isFunctionPointerType())
  12932. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12933. else
  12934. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12935. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12936. SrcType->isObjCObjectPointerType();
  12937. if (Hint.isNull() && !CheckInferredResultType) {
  12938. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12939. }
  12940. else if (CheckInferredResultType) {
  12941. SrcType = SrcType.getUnqualifiedType();
  12942. DstType = DstType.getUnqualifiedType();
  12943. }
  12944. MayHaveConvFixit = true;
  12945. break;
  12946. case IncompatiblePointerSign:
  12947. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12948. break;
  12949. case FunctionVoidPointer:
  12950. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12951. break;
  12952. case IncompatiblePointerDiscardsQualifiers: {
  12953. // Perform array-to-pointer decay if necessary.
  12954. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12955. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12956. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12957. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12958. DiagKind = diag::err_typecheck_incompatible_address_space;
  12959. break;
  12960. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12961. DiagKind = diag::err_typecheck_incompatible_ownership;
  12962. break;
  12963. }
  12964. llvm_unreachable("unknown error case for discarding qualifiers!");
  12965. // fallthrough
  12966. }
  12967. case CompatiblePointerDiscardsQualifiers:
  12968. // If the qualifiers lost were because we were applying the
  12969. // (deprecated) C++ conversion from a string literal to a char*
  12970. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12971. // Ideally, this check would be performed in
  12972. // checkPointerTypesForAssignment. However, that would require a
  12973. // bit of refactoring (so that the second argument is an
  12974. // expression, rather than a type), which should be done as part
  12975. // of a larger effort to fix checkPointerTypesForAssignment for
  12976. // C++ semantics.
  12977. if (getLangOpts().CPlusPlus &&
  12978. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12979. return false;
  12980. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12981. break;
  12982. case IncompatibleNestedPointerQualifiers:
  12983. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12984. break;
  12985. case IncompatibleNestedPointerAddressSpaceMismatch:
  12986. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12987. break;
  12988. case IntToBlockPointer:
  12989. DiagKind = diag::err_int_to_block_pointer;
  12990. break;
  12991. case IncompatibleBlockPointer:
  12992. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12993. break;
  12994. case IncompatibleObjCQualifiedId: {
  12995. if (SrcType->isObjCQualifiedIdType()) {
  12996. const ObjCObjectPointerType *srcOPT =
  12997. SrcType->castAs<ObjCObjectPointerType>();
  12998. for (auto *srcProto : srcOPT->quals()) {
  12999. PDecl = srcProto;
  13000. break;
  13001. }
  13002. if (const ObjCInterfaceType *IFaceT =
  13003. DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  13004. IFace = IFaceT->getDecl();
  13005. }
  13006. else if (DstType->isObjCQualifiedIdType()) {
  13007. const ObjCObjectPointerType *dstOPT =
  13008. DstType->castAs<ObjCObjectPointerType>();
  13009. for (auto *dstProto : dstOPT->quals()) {
  13010. PDecl = dstProto;
  13011. break;
  13012. }
  13013. if (const ObjCInterfaceType *IFaceT =
  13014. SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  13015. IFace = IFaceT->getDecl();
  13016. }
  13017. DiagKind = diag::warn_incompatible_qualified_id;
  13018. break;
  13019. }
  13020. case IncompatibleVectors:
  13021. DiagKind = diag::warn_incompatible_vectors;
  13022. break;
  13023. case IncompatibleObjCWeakRef:
  13024. DiagKind = diag::err_arc_weak_unavailable_assign;
  13025. break;
  13026. case Incompatible:
  13027. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  13028. if (Complained)
  13029. *Complained = true;
  13030. return true;
  13031. }
  13032. DiagKind = diag::err_typecheck_convert_incompatible;
  13033. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  13034. MayHaveConvFixit = true;
  13035. isInvalid = true;
  13036. MayHaveFunctionDiff = true;
  13037. break;
  13038. }
  13039. QualType FirstType, SecondType;
  13040. switch (Action) {
  13041. case AA_Assigning:
  13042. case AA_Initializing:
  13043. // The destination type comes first.
  13044. FirstType = DstType;
  13045. SecondType = SrcType;
  13046. break;
  13047. case AA_Returning:
  13048. case AA_Passing:
  13049. case AA_Passing_CFAudited:
  13050. case AA_Converting:
  13051. case AA_Sending:
  13052. case AA_Casting:
  13053. // The source type comes first.
  13054. FirstType = SrcType;
  13055. SecondType = DstType;
  13056. break;
  13057. }
  13058. PartialDiagnostic FDiag = PDiag(DiagKind);
  13059. if (Action == AA_Passing_CFAudited)
  13060. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  13061. else
  13062. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  13063. // If we can fix the conversion, suggest the FixIts.
  13064. assert(ConvHints.isNull() || Hint.isNull());
  13065. if (!ConvHints.isNull()) {
  13066. for (FixItHint &H : ConvHints.Hints)
  13067. FDiag << H;
  13068. } else {
  13069. FDiag << Hint;
  13070. }
  13071. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  13072. if (MayHaveFunctionDiff)
  13073. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  13074. Diag(Loc, FDiag);
  13075. if (DiagKind == diag::warn_incompatible_qualified_id &&
  13076. PDecl && IFace && !IFace->hasDefinition())
  13077. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  13078. << IFace << PDecl;
  13079. if (SecondType == Context.OverloadTy)
  13080. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  13081. FirstType, /*TakingAddress=*/true);
  13082. if (CheckInferredResultType)
  13083. EmitRelatedResultTypeNote(SrcExpr);
  13084. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  13085. EmitRelatedResultTypeNoteForReturn(DstType);
  13086. if (Complained)
  13087. *Complained = true;
  13088. return isInvalid;
  13089. }
  13090. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13091. llvm::APSInt *Result) {
  13092. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  13093. public:
  13094. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13095. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  13096. }
  13097. } Diagnoser;
  13098. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  13099. }
  13100. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  13101. llvm::APSInt *Result,
  13102. unsigned DiagID,
  13103. bool AllowFold) {
  13104. class IDDiagnoser : public VerifyICEDiagnoser {
  13105. unsigned DiagID;
  13106. public:
  13107. IDDiagnoser(unsigned DiagID)
  13108. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  13109. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  13110. S.Diag(Loc, DiagID) << SR;
  13111. }
  13112. } Diagnoser(DiagID);
  13113. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  13114. }
  13115. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  13116. SourceRange SR) {
  13117. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  13118. }
  13119. ExprResult
  13120. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  13121. VerifyICEDiagnoser &Diagnoser,
  13122. bool AllowFold) {
  13123. SourceLocation DiagLoc = E->getBeginLoc();
  13124. if (getLangOpts().CPlusPlus11) {
  13125. // C++11 [expr.const]p5:
  13126. // If an expression of literal class type is used in a context where an
  13127. // integral constant expression is required, then that class type shall
  13128. // have a single non-explicit conversion function to an integral or
  13129. // unscoped enumeration type
  13130. ExprResult Converted;
  13131. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  13132. public:
  13133. CXX11ConvertDiagnoser(bool Silent)
  13134. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  13135. Silent, true) {}
  13136. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  13137. QualType T) override {
  13138. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  13139. }
  13140. SemaDiagnosticBuilder diagnoseIncomplete(
  13141. Sema &S, SourceLocation Loc, QualType T) override {
  13142. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  13143. }
  13144. SemaDiagnosticBuilder diagnoseExplicitConv(
  13145. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13146. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  13147. }
  13148. SemaDiagnosticBuilder noteExplicitConv(
  13149. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13150. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13151. << ConvTy->isEnumeralType() << ConvTy;
  13152. }
  13153. SemaDiagnosticBuilder diagnoseAmbiguous(
  13154. Sema &S, SourceLocation Loc, QualType T) override {
  13155. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  13156. }
  13157. SemaDiagnosticBuilder noteAmbiguous(
  13158. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13159. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13160. << ConvTy->isEnumeralType() << ConvTy;
  13161. }
  13162. SemaDiagnosticBuilder diagnoseConversion(
  13163. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13164. llvm_unreachable("conversion functions are permitted");
  13165. }
  13166. } ConvertDiagnoser(Diagnoser.Suppress);
  13167. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  13168. ConvertDiagnoser);
  13169. if (Converted.isInvalid())
  13170. return Converted;
  13171. E = Converted.get();
  13172. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  13173. return ExprError();
  13174. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  13175. // An ICE must be of integral or unscoped enumeration type.
  13176. if (!Diagnoser.Suppress)
  13177. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13178. return ExprError();
  13179. }
  13180. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  13181. // in the non-ICE case.
  13182. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  13183. if (Result)
  13184. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  13185. if (!isa<ConstantExpr>(E))
  13186. E = ConstantExpr::Create(Context, E);
  13187. return E;
  13188. }
  13189. Expr::EvalResult EvalResult;
  13190. SmallVector<PartialDiagnosticAt, 8> Notes;
  13191. EvalResult.Diag = &Notes;
  13192. // Try to evaluate the expression, and produce diagnostics explaining why it's
  13193. // not a constant expression as a side-effect.
  13194. bool Folded =
  13195. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  13196. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  13197. if (!isa<ConstantExpr>(E))
  13198. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  13199. // In C++11, we can rely on diagnostics being produced for any expression
  13200. // which is not a constant expression. If no diagnostics were produced, then
  13201. // this is a constant expression.
  13202. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  13203. if (Result)
  13204. *Result = EvalResult.Val.getInt();
  13205. return E;
  13206. }
  13207. // If our only note is the usual "invalid subexpression" note, just point
  13208. // the caret at its location rather than producing an essentially
  13209. // redundant note.
  13210. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  13211. diag::note_invalid_subexpr_in_const_expr) {
  13212. DiagLoc = Notes[0].first;
  13213. Notes.clear();
  13214. }
  13215. if (!Folded || !AllowFold) {
  13216. if (!Diagnoser.Suppress) {
  13217. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13218. for (const PartialDiagnosticAt &Note : Notes)
  13219. Diag(Note.first, Note.second);
  13220. }
  13221. return ExprError();
  13222. }
  13223. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  13224. for (const PartialDiagnosticAt &Note : Notes)
  13225. Diag(Note.first, Note.second);
  13226. if (Result)
  13227. *Result = EvalResult.Val.getInt();
  13228. return E;
  13229. }
  13230. namespace {
  13231. // Handle the case where we conclude a expression which we speculatively
  13232. // considered to be unevaluated is actually evaluated.
  13233. class TransformToPE : public TreeTransform<TransformToPE> {
  13234. typedef TreeTransform<TransformToPE> BaseTransform;
  13235. public:
  13236. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  13237. // Make sure we redo semantic analysis
  13238. bool AlwaysRebuild() { return true; }
  13239. bool ReplacingOriginal() { return true; }
  13240. // We need to special-case DeclRefExprs referring to FieldDecls which
  13241. // are not part of a member pointer formation; normal TreeTransforming
  13242. // doesn't catch this case because of the way we represent them in the AST.
  13243. // FIXME: This is a bit ugly; is it really the best way to handle this
  13244. // case?
  13245. //
  13246. // Error on DeclRefExprs referring to FieldDecls.
  13247. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  13248. if (isa<FieldDecl>(E->getDecl()) &&
  13249. !SemaRef.isUnevaluatedContext())
  13250. return SemaRef.Diag(E->getLocation(),
  13251. diag::err_invalid_non_static_member_use)
  13252. << E->getDecl() << E->getSourceRange();
  13253. return BaseTransform::TransformDeclRefExpr(E);
  13254. }
  13255. // Exception: filter out member pointer formation
  13256. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  13257. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  13258. return E;
  13259. return BaseTransform::TransformUnaryOperator(E);
  13260. }
  13261. // The body of a lambda-expression is in a separate expression evaluation
  13262. // context so never needs to be transformed.
  13263. // FIXME: Ideally we wouldn't transform the closure type either, and would
  13264. // just recreate the capture expressions and lambda expression.
  13265. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  13266. return SkipLambdaBody(E, Body);
  13267. }
  13268. };
  13269. }
  13270. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  13271. assert(isUnevaluatedContext() &&
  13272. "Should only transform unevaluated expressions");
  13273. ExprEvalContexts.back().Context =
  13274. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  13275. if (isUnevaluatedContext())
  13276. return E;
  13277. return TransformToPE(*this).TransformExpr(E);
  13278. }
  13279. void
  13280. Sema::PushExpressionEvaluationContext(
  13281. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  13282. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13283. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  13284. LambdaContextDecl, ExprContext);
  13285. Cleanup.reset();
  13286. if (!MaybeODRUseExprs.empty())
  13287. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  13288. }
  13289. void
  13290. Sema::PushExpressionEvaluationContext(
  13291. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  13292. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13293. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  13294. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  13295. }
  13296. namespace {
  13297. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  13298. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  13299. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  13300. if (E->getOpcode() == UO_Deref)
  13301. return CheckPossibleDeref(S, E->getSubExpr());
  13302. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  13303. return CheckPossibleDeref(S, E->getBase());
  13304. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  13305. return CheckPossibleDeref(S, E->getBase());
  13306. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  13307. QualType Inner;
  13308. QualType Ty = E->getType();
  13309. if (const auto *Ptr = Ty->getAs<PointerType>())
  13310. Inner = Ptr->getPointeeType();
  13311. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  13312. Inner = Arr->getElementType();
  13313. else
  13314. return nullptr;
  13315. if (Inner->hasAttr(attr::NoDeref))
  13316. return E;
  13317. }
  13318. return nullptr;
  13319. }
  13320. } // namespace
  13321. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  13322. for (const Expr *E : Rec.PossibleDerefs) {
  13323. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  13324. if (DeclRef) {
  13325. const ValueDecl *Decl = DeclRef->getDecl();
  13326. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  13327. << Decl->getName() << E->getSourceRange();
  13328. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  13329. } else {
  13330. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  13331. << E->getSourceRange();
  13332. }
  13333. }
  13334. Rec.PossibleDerefs.clear();
  13335. }
  13336. /// Check whether E, which is either a discarded-value expression or an
  13337. /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
  13338. /// and if so, remove it from the list of volatile-qualified assignments that
  13339. /// we are going to warn are deprecated.
  13340. void Sema::CheckUnusedVolatileAssignment(Expr *E) {
  13341. if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
  13342. return;
  13343. // Note: ignoring parens here is not justified by the standard rules, but
  13344. // ignoring parentheses seems like a more reasonable approach, and this only
  13345. // drives a deprecation warning so doesn't affect conformance.
  13346. if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
  13347. if (BO->getOpcode() == BO_Assign) {
  13348. auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
  13349. LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
  13350. LHSs.end());
  13351. }
  13352. }
  13353. }
  13354. void Sema::PopExpressionEvaluationContext() {
  13355. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  13356. unsigned NumTypos = Rec.NumTypos;
  13357. if (!Rec.Lambdas.empty()) {
  13358. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  13359. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  13360. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  13361. unsigned D;
  13362. if (Rec.isUnevaluated()) {
  13363. // C++11 [expr.prim.lambda]p2:
  13364. // A lambda-expression shall not appear in an unevaluated operand
  13365. // (Clause 5).
  13366. D = diag::err_lambda_unevaluated_operand;
  13367. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  13368. // C++1y [expr.const]p2:
  13369. // A conditional-expression e is a core constant expression unless the
  13370. // evaluation of e, following the rules of the abstract machine, would
  13371. // evaluate [...] a lambda-expression.
  13372. D = diag::err_lambda_in_constant_expression;
  13373. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  13374. // C++17 [expr.prim.lamda]p2:
  13375. // A lambda-expression shall not appear [...] in a template-argument.
  13376. D = diag::err_lambda_in_invalid_context;
  13377. } else
  13378. llvm_unreachable("Couldn't infer lambda error message.");
  13379. for (const auto *L : Rec.Lambdas)
  13380. Diag(L->getBeginLoc(), D);
  13381. }
  13382. }
  13383. WarnOnPendingNoDerefs(Rec);
  13384. // Warn on any volatile-qualified simple-assignments that are not discarded-
  13385. // value expressions nor unevaluated operands (those cases get removed from
  13386. // this list by CheckUnusedVolatileAssignment).
  13387. for (auto *BO : Rec.VolatileAssignmentLHSs)
  13388. Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
  13389. << BO->getType();
  13390. // When are coming out of an unevaluated context, clear out any
  13391. // temporaries that we may have created as part of the evaluation of
  13392. // the expression in that context: they aren't relevant because they
  13393. // will never be constructed.
  13394. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  13395. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  13396. ExprCleanupObjects.end());
  13397. Cleanup = Rec.ParentCleanup;
  13398. CleanupVarDeclMarking();
  13399. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  13400. // Otherwise, merge the contexts together.
  13401. } else {
  13402. Cleanup.mergeFrom(Rec.ParentCleanup);
  13403. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  13404. Rec.SavedMaybeODRUseExprs.end());
  13405. }
  13406. // Pop the current expression evaluation context off the stack.
  13407. ExprEvalContexts.pop_back();
  13408. // The global expression evaluation context record is never popped.
  13409. ExprEvalContexts.back().NumTypos += NumTypos;
  13410. }
  13411. void Sema::DiscardCleanupsInEvaluationContext() {
  13412. ExprCleanupObjects.erase(
  13413. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  13414. ExprCleanupObjects.end());
  13415. Cleanup.reset();
  13416. MaybeODRUseExprs.clear();
  13417. }
  13418. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13419. ExprResult Result = CheckPlaceholderExpr(E);
  13420. if (Result.isInvalid())
  13421. return ExprError();
  13422. E = Result.get();
  13423. if (!E->getType()->isVariablyModifiedType())
  13424. return E;
  13425. return TransformToPotentiallyEvaluated(E);
  13426. }
  13427. /// Are we in a context that is potentially constant evaluated per C++20
  13428. /// [expr.const]p12?
  13429. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13430. /// C++2a [expr.const]p12:
  13431. // An expression or conversion is potentially constant evaluated if it is
  13432. switch (SemaRef.ExprEvalContexts.back().Context) {
  13433. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13434. // -- a manifestly constant-evaluated expression,
  13435. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13436. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13437. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13438. // -- a potentially-evaluated expression,
  13439. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13440. // -- an immediate subexpression of a braced-init-list,
  13441. // -- [FIXME] an expression of the form & cast-expression that occurs
  13442. // within a templated entity
  13443. // -- a subexpression of one of the above that is not a subexpression of
  13444. // a nested unevaluated operand.
  13445. return true;
  13446. case Sema::ExpressionEvaluationContext::Unevaluated:
  13447. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13448. // Expressions in this context are never evaluated.
  13449. return false;
  13450. }
  13451. llvm_unreachable("Invalid context");
  13452. }
  13453. /// Return true if this function has a calling convention that requires mangling
  13454. /// in the size of the parameter pack.
  13455. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  13456. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  13457. // we don't need parameter type sizes.
  13458. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  13459. if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
  13460. TT.getArch() != llvm::Triple::x86_64))
  13461. return false;
  13462. // If this is C++ and this isn't an extern "C" function, parameters do not
  13463. // need to be complete. In this case, C++ mangling will apply, which doesn't
  13464. // use the size of the parameters.
  13465. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  13466. return false;
  13467. // Stdcall, fastcall, and vectorcall need this special treatment.
  13468. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13469. switch (CC) {
  13470. case CC_X86StdCall:
  13471. case CC_X86FastCall:
  13472. case CC_X86VectorCall:
  13473. return true;
  13474. default:
  13475. break;
  13476. }
  13477. return false;
  13478. }
  13479. /// Require that all of the parameter types of function be complete. Normally,
  13480. /// parameter types are only required to be complete when a function is called
  13481. /// or defined, but to mangle functions with certain calling conventions, the
  13482. /// mangler needs to know the size of the parameter list. In this situation,
  13483. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  13484. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  13485. /// result in a linker error. Clang doesn't implement this behavior, and instead
  13486. /// attempts to error at compile time.
  13487. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  13488. SourceLocation Loc) {
  13489. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  13490. FunctionDecl *FD;
  13491. ParmVarDecl *Param;
  13492. public:
  13493. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  13494. : FD(FD), Param(Param) {}
  13495. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13496. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13497. StringRef CCName;
  13498. switch (CC) {
  13499. case CC_X86StdCall:
  13500. CCName = "stdcall";
  13501. break;
  13502. case CC_X86FastCall:
  13503. CCName = "fastcall";
  13504. break;
  13505. case CC_X86VectorCall:
  13506. CCName = "vectorcall";
  13507. break;
  13508. default:
  13509. llvm_unreachable("CC does not need mangling");
  13510. }
  13511. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  13512. << Param->getDeclName() << FD->getDeclName() << CCName;
  13513. }
  13514. };
  13515. for (ParmVarDecl *Param : FD->parameters()) {
  13516. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  13517. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  13518. }
  13519. }
  13520. namespace {
  13521. enum class OdrUseContext {
  13522. /// Declarations in this context are not odr-used.
  13523. None,
  13524. /// Declarations in this context are formally odr-used, but this is a
  13525. /// dependent context.
  13526. Dependent,
  13527. /// Declarations in this context are odr-used but not actually used (yet).
  13528. FormallyOdrUsed,
  13529. /// Declarations in this context are used.
  13530. Used
  13531. };
  13532. }
  13533. /// Are we within a context in which references to resolved functions or to
  13534. /// variables result in odr-use?
  13535. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13536. OdrUseContext Result;
  13537. switch (SemaRef.ExprEvalContexts.back().Context) {
  13538. case Sema::ExpressionEvaluationContext::Unevaluated:
  13539. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13540. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13541. return OdrUseContext::None;
  13542. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13543. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13544. Result = OdrUseContext::Used;
  13545. break;
  13546. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13547. Result = OdrUseContext::FormallyOdrUsed;
  13548. break;
  13549. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13550. // A default argument formally results in odr-use, but doesn't actually
  13551. // result in a use in any real sense until it itself is used.
  13552. Result = OdrUseContext::FormallyOdrUsed;
  13553. break;
  13554. }
  13555. if (SemaRef.CurContext->isDependentContext())
  13556. return OdrUseContext::Dependent;
  13557. return Result;
  13558. }
  13559. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13560. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13561. return Func->isConstexpr() &&
  13562. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13563. }
  13564. /// Mark a function referenced, and check whether it is odr-used
  13565. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13566. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13567. bool MightBeOdrUse) {
  13568. assert(Func && "No function?");
  13569. Func->setReferenced();
  13570. // Recursive functions aren't really used until they're used from some other
  13571. // context.
  13572. bool IsRecursiveCall = CurContext == Func;
  13573. // C++11 [basic.def.odr]p3:
  13574. // A function whose name appears as a potentially-evaluated expression is
  13575. // odr-used if it is the unique lookup result or the selected member of a
  13576. // set of overloaded functions [...].
  13577. //
  13578. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13579. // can just check that here.
  13580. OdrUseContext OdrUse =
  13581. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13582. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13583. OdrUse = OdrUseContext::FormallyOdrUsed;
  13584. // Trivial default constructors and destructors are never actually used.
  13585. // FIXME: What about other special members?
  13586. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  13587. OdrUse == OdrUseContext::Used) {
  13588. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  13589. if (Constructor->isDefaultConstructor())
  13590. OdrUse = OdrUseContext::FormallyOdrUsed;
  13591. if (isa<CXXDestructorDecl>(Func))
  13592. OdrUse = OdrUseContext::FormallyOdrUsed;
  13593. }
  13594. // C++20 [expr.const]p12:
  13595. // A function [...] is needed for constant evaluation if it is [...] a
  13596. // constexpr function that is named by an expression that is potentially
  13597. // constant evaluated
  13598. bool NeededForConstantEvaluation =
  13599. isPotentiallyConstantEvaluatedContext(*this) &&
  13600. isImplicitlyDefinableConstexprFunction(Func);
  13601. // Determine whether we require a function definition to exist, per
  13602. // C++11 [temp.inst]p3:
  13603. // Unless a function template specialization has been explicitly
  13604. // instantiated or explicitly specialized, the function template
  13605. // specialization is implicitly instantiated when the specialization is
  13606. // referenced in a context that requires a function definition to exist.
  13607. // C++20 [temp.inst]p7:
  13608. // The existence of a definition of a [...] function is considered to
  13609. // affect the semantics of the program if the [...] function is needed for
  13610. // constant evaluation by an expression
  13611. // C++20 [basic.def.odr]p10:
  13612. // Every program shall contain exactly one definition of every non-inline
  13613. // function or variable that is odr-used in that program outside of a
  13614. // discarded statement
  13615. // C++20 [special]p1:
  13616. // The implementation will implicitly define [defaulted special members]
  13617. // if they are odr-used or needed for constant evaluation.
  13618. //
  13619. // Note that we skip the implicit instantiation of templates that are only
  13620. // used in unused default arguments or by recursive calls to themselves.
  13621. // This is formally non-conforming, but seems reasonable in practice.
  13622. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13623. NeededForConstantEvaluation);
  13624. // C++14 [temp.expl.spec]p6:
  13625. // If a template [...] is explicitly specialized then that specialization
  13626. // shall be declared before the first use of that specialization that would
  13627. // cause an implicit instantiation to take place, in every translation unit
  13628. // in which such a use occurs
  13629. if (NeedDefinition &&
  13630. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13631. Func->getMemberSpecializationInfo()))
  13632. checkSpecializationVisibility(Loc, Func);
  13633. // C++14 [except.spec]p17:
  13634. // An exception-specification is considered to be needed when:
  13635. // - the function is odr-used or, if it appears in an unevaluated operand,
  13636. // would be odr-used if the expression were potentially-evaluated;
  13637. //
  13638. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13639. // function is a pure virtual function we're calling, and in that case the
  13640. // function was selected by overload resolution and we need to resolve its
  13641. // exception specification for a different reason.
  13642. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13643. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13644. ResolveExceptionSpec(Loc, FPT);
  13645. if (getLangOpts().CUDA)
  13646. CheckCUDACall(Loc, Func);
  13647. // If we need a definition, try to create one.
  13648. if (NeedDefinition && !Func->getBody()) {
  13649. runWithSufficientStackSpace(Loc, [&] {
  13650. if (CXXConstructorDecl *Constructor =
  13651. dyn_cast<CXXConstructorDecl>(Func)) {
  13652. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13653. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13654. if (Constructor->isDefaultConstructor()) {
  13655. if (Constructor->isTrivial() &&
  13656. !Constructor->hasAttr<DLLExportAttr>())
  13657. return;
  13658. DefineImplicitDefaultConstructor(Loc, Constructor);
  13659. } else if (Constructor->isCopyConstructor()) {
  13660. DefineImplicitCopyConstructor(Loc, Constructor);
  13661. } else if (Constructor->isMoveConstructor()) {
  13662. DefineImplicitMoveConstructor(Loc, Constructor);
  13663. }
  13664. } else if (Constructor->getInheritedConstructor()) {
  13665. DefineInheritingConstructor(Loc, Constructor);
  13666. }
  13667. } else if (CXXDestructorDecl *Destructor =
  13668. dyn_cast<CXXDestructorDecl>(Func)) {
  13669. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13670. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13671. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13672. return;
  13673. DefineImplicitDestructor(Loc, Destructor);
  13674. }
  13675. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13676. MarkVTableUsed(Loc, Destructor->getParent());
  13677. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13678. if (MethodDecl->isOverloadedOperator() &&
  13679. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13680. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13681. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13682. if (MethodDecl->isCopyAssignmentOperator())
  13683. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13684. else if (MethodDecl->isMoveAssignmentOperator())
  13685. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13686. }
  13687. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13688. MethodDecl->getParent()->isLambda()) {
  13689. CXXConversionDecl *Conversion =
  13690. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13691. if (Conversion->isLambdaToBlockPointerConversion())
  13692. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13693. else
  13694. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13695. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13696. MarkVTableUsed(Loc, MethodDecl->getParent());
  13697. }
  13698. // Implicit instantiation of function templates and member functions of
  13699. // class templates.
  13700. if (Func->isImplicitlyInstantiable()) {
  13701. TemplateSpecializationKind TSK =
  13702. Func->getTemplateSpecializationKindForInstantiation();
  13703. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13704. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13705. if (FirstInstantiation) {
  13706. PointOfInstantiation = Loc;
  13707. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13708. } else if (TSK != TSK_ImplicitInstantiation) {
  13709. // Use the point of use as the point of instantiation, instead of the
  13710. // point of explicit instantiation (which we track as the actual point
  13711. // of instantiation). This gives better backtraces in diagnostics.
  13712. PointOfInstantiation = Loc;
  13713. }
  13714. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13715. Func->isConstexpr()) {
  13716. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13717. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13718. CodeSynthesisContexts.size())
  13719. PendingLocalImplicitInstantiations.push_back(
  13720. std::make_pair(Func, PointOfInstantiation));
  13721. else if (Func->isConstexpr())
  13722. // Do not defer instantiations of constexpr functions, to avoid the
  13723. // expression evaluator needing to call back into Sema if it sees a
  13724. // call to such a function.
  13725. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13726. else {
  13727. Func->setInstantiationIsPending(true);
  13728. PendingInstantiations.push_back(
  13729. std::make_pair(Func, PointOfInstantiation));
  13730. // Notify the consumer that a function was implicitly instantiated.
  13731. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13732. }
  13733. }
  13734. } else {
  13735. // Walk redefinitions, as some of them may be instantiable.
  13736. for (auto i : Func->redecls()) {
  13737. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13738. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13739. }
  13740. }
  13741. });
  13742. }
  13743. // If this is the first "real" use, act on that.
  13744. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13745. // Keep track of used but undefined functions.
  13746. if (!Func->isDefined()) {
  13747. if (mightHaveNonExternalLinkage(Func))
  13748. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13749. else if (Func->getMostRecentDecl()->isInlined() &&
  13750. !LangOpts.GNUInline &&
  13751. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13752. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13753. else if (isExternalWithNoLinkageType(Func))
  13754. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13755. }
  13756. // Some x86 Windows calling conventions mangle the size of the parameter
  13757. // pack into the name. Computing the size of the parameters requires the
  13758. // parameter types to be complete. Check that now.
  13759. if (funcHasParameterSizeMangling(*this, Func))
  13760. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  13761. Func->markUsed(Context);
  13762. }
  13763. if (LangOpts.OpenMP) {
  13764. markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
  13765. if (LangOpts.OpenMPIsDevice)
  13766. checkOpenMPDeviceFunction(Loc, Func);
  13767. else
  13768. checkOpenMPHostFunction(Loc, Func);
  13769. }
  13770. }
  13771. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13772. /// MarkVariableReferenced since it does additional checks and then
  13773. /// calls MarkVarDeclODRUsed.
  13774. /// If the variable must be captured:
  13775. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13776. /// - else capture it in the DeclContext that maps to the
  13777. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13778. static void
  13779. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13780. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13781. // Keep track of used but undefined variables.
  13782. // FIXME: We shouldn't suppress this warning for static data members.
  13783. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13784. (!Var->isExternallyVisible() || Var->isInline() ||
  13785. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13786. !(Var->isStaticDataMember() && Var->hasInit())) {
  13787. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13788. if (old.isInvalid())
  13789. old = Loc;
  13790. }
  13791. QualType CaptureType, DeclRefType;
  13792. if (SemaRef.LangOpts.OpenMP)
  13793. SemaRef.tryCaptureOpenMPLambdas(Var);
  13794. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13795. /*EllipsisLoc*/ SourceLocation(),
  13796. /*BuildAndDiagnose*/ true,
  13797. CaptureType, DeclRefType,
  13798. FunctionScopeIndexToStopAt);
  13799. Var->markUsed(SemaRef.Context);
  13800. }
  13801. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13802. SourceLocation Loc,
  13803. unsigned CapturingScopeIndex) {
  13804. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13805. }
  13806. static void
  13807. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13808. ValueDecl *var, DeclContext *DC) {
  13809. DeclContext *VarDC = var->getDeclContext();
  13810. // If the parameter still belongs to the translation unit, then
  13811. // we're actually just using one parameter in the declaration of
  13812. // the next.
  13813. if (isa<ParmVarDecl>(var) &&
  13814. isa<TranslationUnitDecl>(VarDC))
  13815. return;
  13816. // For C code, don't diagnose about capture if we're not actually in code
  13817. // right now; it's impossible to write a non-constant expression outside of
  13818. // function context, so we'll get other (more useful) diagnostics later.
  13819. //
  13820. // For C++, things get a bit more nasty... it would be nice to suppress this
  13821. // diagnostic for certain cases like using a local variable in an array bound
  13822. // for a member of a local class, but the correct predicate is not obvious.
  13823. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13824. return;
  13825. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13826. unsigned ContextKind = 3; // unknown
  13827. if (isa<CXXMethodDecl>(VarDC) &&
  13828. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13829. ContextKind = 2;
  13830. } else if (isa<FunctionDecl>(VarDC)) {
  13831. ContextKind = 0;
  13832. } else if (isa<BlockDecl>(VarDC)) {
  13833. ContextKind = 1;
  13834. }
  13835. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13836. << var << ValueKind << ContextKind << VarDC;
  13837. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13838. << var;
  13839. // FIXME: Add additional diagnostic info about class etc. which prevents
  13840. // capture.
  13841. }
  13842. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13843. bool &SubCapturesAreNested,
  13844. QualType &CaptureType,
  13845. QualType &DeclRefType) {
  13846. // Check whether we've already captured it.
  13847. if (CSI->CaptureMap.count(Var)) {
  13848. // If we found a capture, any subcaptures are nested.
  13849. SubCapturesAreNested = true;
  13850. // Retrieve the capture type for this variable.
  13851. CaptureType = CSI->getCapture(Var).getCaptureType();
  13852. // Compute the type of an expression that refers to this variable.
  13853. DeclRefType = CaptureType.getNonReferenceType();
  13854. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13855. // are mutable in the sense that user can change their value - they are
  13856. // private instances of the captured declarations.
  13857. const Capture &Cap = CSI->getCapture(Var);
  13858. if (Cap.isCopyCapture() &&
  13859. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13860. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13861. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13862. DeclRefType.addConst();
  13863. return true;
  13864. }
  13865. return false;
  13866. }
  13867. // Only block literals, captured statements, and lambda expressions can
  13868. // capture; other scopes don't work.
  13869. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13870. SourceLocation Loc,
  13871. const bool Diagnose, Sema &S) {
  13872. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13873. return getLambdaAwareParentOfDeclContext(DC);
  13874. else if (Var->hasLocalStorage()) {
  13875. if (Diagnose)
  13876. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13877. }
  13878. return nullptr;
  13879. }
  13880. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13881. // certain types of variables (unnamed, variably modified types etc.)
  13882. // so check for eligibility.
  13883. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13884. SourceLocation Loc,
  13885. const bool Diagnose, Sema &S) {
  13886. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13887. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13888. // Lambdas are not allowed to capture unnamed variables
  13889. // (e.g. anonymous unions).
  13890. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13891. // assuming that's the intent.
  13892. if (IsLambda && !Var->getDeclName()) {
  13893. if (Diagnose) {
  13894. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13895. S.Diag(Var->getLocation(), diag::note_declared_at);
  13896. }
  13897. return false;
  13898. }
  13899. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13900. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13901. if (Diagnose) {
  13902. S.Diag(Loc, diag::err_ref_vm_type);
  13903. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13904. << Var->getDeclName();
  13905. }
  13906. return false;
  13907. }
  13908. // Prohibit structs with flexible array members too.
  13909. // We cannot capture what is in the tail end of the struct.
  13910. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13911. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13912. if (Diagnose) {
  13913. if (IsBlock)
  13914. S.Diag(Loc, diag::err_ref_flexarray_type);
  13915. else
  13916. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13917. << Var->getDeclName();
  13918. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13919. << Var->getDeclName();
  13920. }
  13921. return false;
  13922. }
  13923. }
  13924. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13925. // Lambdas and captured statements are not allowed to capture __block
  13926. // variables; they don't support the expected semantics.
  13927. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13928. if (Diagnose) {
  13929. S.Diag(Loc, diag::err_capture_block_variable)
  13930. << Var->getDeclName() << !IsLambda;
  13931. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13932. << Var->getDeclName();
  13933. }
  13934. return false;
  13935. }
  13936. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13937. if (S.getLangOpts().OpenCL && IsBlock &&
  13938. Var->getType()->isBlockPointerType()) {
  13939. if (Diagnose)
  13940. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13941. return false;
  13942. }
  13943. return true;
  13944. }
  13945. // Returns true if the capture by block was successful.
  13946. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13947. SourceLocation Loc,
  13948. const bool BuildAndDiagnose,
  13949. QualType &CaptureType,
  13950. QualType &DeclRefType,
  13951. const bool Nested,
  13952. Sema &S, bool Invalid) {
  13953. bool ByRef = false;
  13954. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13955. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13956. // (decayed to pointers).
  13957. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13958. if (BuildAndDiagnose) {
  13959. S.Diag(Loc, diag::err_ref_array_type);
  13960. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13961. << Var->getDeclName();
  13962. Invalid = true;
  13963. } else {
  13964. return false;
  13965. }
  13966. }
  13967. // Forbid the block-capture of autoreleasing variables.
  13968. if (!Invalid &&
  13969. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13970. if (BuildAndDiagnose) {
  13971. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13972. << /*block*/ 0;
  13973. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13974. << Var->getDeclName();
  13975. Invalid = true;
  13976. } else {
  13977. return false;
  13978. }
  13979. }
  13980. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13981. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13982. QualType PointeeTy = PT->getPointeeType();
  13983. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13984. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13985. !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
  13986. if (BuildAndDiagnose) {
  13987. SourceLocation VarLoc = Var->getLocation();
  13988. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13989. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13990. }
  13991. }
  13992. }
  13993. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13994. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13995. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13996. // Block capture by reference does not change the capture or
  13997. // declaration reference types.
  13998. ByRef = true;
  13999. } else {
  14000. // Block capture by copy introduces 'const'.
  14001. CaptureType = CaptureType.getNonReferenceType().withConst();
  14002. DeclRefType = CaptureType;
  14003. }
  14004. // Actually capture the variable.
  14005. if (BuildAndDiagnose)
  14006. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  14007. CaptureType, Invalid);
  14008. return !Invalid;
  14009. }
  14010. /// Capture the given variable in the captured region.
  14011. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  14012. VarDecl *Var,
  14013. SourceLocation Loc,
  14014. const bool BuildAndDiagnose,
  14015. QualType &CaptureType,
  14016. QualType &DeclRefType,
  14017. const bool RefersToCapturedVariable,
  14018. Sema &S, bool Invalid) {
  14019. // By default, capture variables by reference.
  14020. bool ByRef = true;
  14021. // Using an LValue reference type is consistent with Lambdas (see below).
  14022. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  14023. if (S.isOpenMPCapturedDecl(Var)) {
  14024. bool HasConst = DeclRefType.isConstQualified();
  14025. DeclRefType = DeclRefType.getUnqualifiedType();
  14026. // Don't lose diagnostics about assignments to const.
  14027. if (HasConst)
  14028. DeclRefType.addConst();
  14029. }
  14030. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  14031. RSI->OpenMPCaptureLevel);
  14032. }
  14033. if (ByRef)
  14034. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  14035. else
  14036. CaptureType = DeclRefType;
  14037. // Actually capture the variable.
  14038. if (BuildAndDiagnose)
  14039. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  14040. Loc, SourceLocation(), CaptureType, Invalid);
  14041. return !Invalid;
  14042. }
  14043. /// Capture the given variable in the lambda.
  14044. static bool captureInLambda(LambdaScopeInfo *LSI,
  14045. VarDecl *Var,
  14046. SourceLocation Loc,
  14047. const bool BuildAndDiagnose,
  14048. QualType &CaptureType,
  14049. QualType &DeclRefType,
  14050. const bool RefersToCapturedVariable,
  14051. const Sema::TryCaptureKind Kind,
  14052. SourceLocation EllipsisLoc,
  14053. const bool IsTopScope,
  14054. Sema &S, bool Invalid) {
  14055. // Determine whether we are capturing by reference or by value.
  14056. bool ByRef = false;
  14057. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  14058. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  14059. } else {
  14060. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  14061. }
  14062. // Compute the type of the field that will capture this variable.
  14063. if (ByRef) {
  14064. // C++11 [expr.prim.lambda]p15:
  14065. // An entity is captured by reference if it is implicitly or
  14066. // explicitly captured but not captured by copy. It is
  14067. // unspecified whether additional unnamed non-static data
  14068. // members are declared in the closure type for entities
  14069. // captured by reference.
  14070. //
  14071. // FIXME: It is not clear whether we want to build an lvalue reference
  14072. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  14073. // to do the former, while EDG does the latter. Core issue 1249 will
  14074. // clarify, but for now we follow GCC because it's a more permissive and
  14075. // easily defensible position.
  14076. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  14077. } else {
  14078. // C++11 [expr.prim.lambda]p14:
  14079. // For each entity captured by copy, an unnamed non-static
  14080. // data member is declared in the closure type. The
  14081. // declaration order of these members is unspecified. The type
  14082. // of such a data member is the type of the corresponding
  14083. // captured entity if the entity is not a reference to an
  14084. // object, or the referenced type otherwise. [Note: If the
  14085. // captured entity is a reference to a function, the
  14086. // corresponding data member is also a reference to a
  14087. // function. - end note ]
  14088. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  14089. if (!RefType->getPointeeType()->isFunctionType())
  14090. CaptureType = RefType->getPointeeType();
  14091. }
  14092. // Forbid the lambda copy-capture of autoreleasing variables.
  14093. if (!Invalid &&
  14094. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  14095. if (BuildAndDiagnose) {
  14096. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  14097. S.Diag(Var->getLocation(), diag::note_previous_decl)
  14098. << Var->getDeclName();
  14099. Invalid = true;
  14100. } else {
  14101. return false;
  14102. }
  14103. }
  14104. // Make sure that by-copy captures are of a complete and non-abstract type.
  14105. if (!Invalid && BuildAndDiagnose) {
  14106. if (!CaptureType->isDependentType() &&
  14107. S.RequireCompleteType(Loc, CaptureType,
  14108. diag::err_capture_of_incomplete_type,
  14109. Var->getDeclName()))
  14110. Invalid = true;
  14111. else if (S.RequireNonAbstractType(Loc, CaptureType,
  14112. diag::err_capture_of_abstract_type))
  14113. Invalid = true;
  14114. }
  14115. }
  14116. // Compute the type of a reference to this captured variable.
  14117. if (ByRef)
  14118. DeclRefType = CaptureType.getNonReferenceType();
  14119. else {
  14120. // C++ [expr.prim.lambda]p5:
  14121. // The closure type for a lambda-expression has a public inline
  14122. // function call operator [...]. This function call operator is
  14123. // declared const (9.3.1) if and only if the lambda-expression's
  14124. // parameter-declaration-clause is not followed by mutable.
  14125. DeclRefType = CaptureType.getNonReferenceType();
  14126. if (!LSI->Mutable && !CaptureType->isReferenceType())
  14127. DeclRefType.addConst();
  14128. }
  14129. // Add the capture.
  14130. if (BuildAndDiagnose)
  14131. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  14132. Loc, EllipsisLoc, CaptureType, Invalid);
  14133. return !Invalid;
  14134. }
  14135. bool Sema::tryCaptureVariable(
  14136. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  14137. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  14138. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  14139. // An init-capture is notionally from the context surrounding its
  14140. // declaration, but its parent DC is the lambda class.
  14141. DeclContext *VarDC = Var->getDeclContext();
  14142. if (Var->isInitCapture())
  14143. VarDC = VarDC->getParent();
  14144. DeclContext *DC = CurContext;
  14145. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  14146. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  14147. // We need to sync up the Declaration Context with the
  14148. // FunctionScopeIndexToStopAt
  14149. if (FunctionScopeIndexToStopAt) {
  14150. unsigned FSIndex = FunctionScopes.size() - 1;
  14151. while (FSIndex != MaxFunctionScopesIndex) {
  14152. DC = getLambdaAwareParentOfDeclContext(DC);
  14153. --FSIndex;
  14154. }
  14155. }
  14156. // If the variable is declared in the current context, there is no need to
  14157. // capture it.
  14158. if (VarDC == DC) return true;
  14159. // Capture global variables if it is required to use private copy of this
  14160. // variable.
  14161. bool IsGlobal = !Var->hasLocalStorage();
  14162. if (IsGlobal &&
  14163. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  14164. MaxFunctionScopesIndex)))
  14165. return true;
  14166. Var = Var->getCanonicalDecl();
  14167. // Walk up the stack to determine whether we can capture the variable,
  14168. // performing the "simple" checks that don't depend on type. We stop when
  14169. // we've either hit the declared scope of the variable or find an existing
  14170. // capture of that variable. We start from the innermost capturing-entity
  14171. // (the DC) and ensure that all intervening capturing-entities
  14172. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  14173. // declcontext can either capture the variable or have already captured
  14174. // the variable.
  14175. CaptureType = Var->getType();
  14176. DeclRefType = CaptureType.getNonReferenceType();
  14177. bool Nested = false;
  14178. bool Explicit = (Kind != TryCapture_Implicit);
  14179. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  14180. do {
  14181. // Only block literals, captured statements, and lambda expressions can
  14182. // capture; other scopes don't work.
  14183. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  14184. ExprLoc,
  14185. BuildAndDiagnose,
  14186. *this);
  14187. // We need to check for the parent *first* because, if we *have*
  14188. // private-captured a global variable, we need to recursively capture it in
  14189. // intermediate blocks, lambdas, etc.
  14190. if (!ParentDC) {
  14191. if (IsGlobal) {
  14192. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  14193. break;
  14194. }
  14195. return true;
  14196. }
  14197. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  14198. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  14199. // Check whether we've already captured it.
  14200. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  14201. DeclRefType)) {
  14202. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  14203. break;
  14204. }
  14205. // If we are instantiating a generic lambda call operator body,
  14206. // we do not want to capture new variables. What was captured
  14207. // during either a lambdas transformation or initial parsing
  14208. // should be used.
  14209. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  14210. if (BuildAndDiagnose) {
  14211. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14212. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  14213. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14214. Diag(Var->getLocation(), diag::note_previous_decl)
  14215. << Var->getDeclName();
  14216. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  14217. } else
  14218. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  14219. }
  14220. return true;
  14221. }
  14222. // Try to capture variable-length arrays types.
  14223. if (Var->getType()->isVariablyModifiedType()) {
  14224. // We're going to walk down into the type and look for VLA
  14225. // expressions.
  14226. QualType QTy = Var->getType();
  14227. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14228. QTy = PVD->getOriginalType();
  14229. captureVariablyModifiedType(Context, QTy, CSI);
  14230. }
  14231. if (getLangOpts().OpenMP) {
  14232. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14233. // OpenMP private variables should not be captured in outer scope, so
  14234. // just break here. Similarly, global variables that are captured in a
  14235. // target region should not be captured outside the scope of the region.
  14236. if (RSI->CapRegionKind == CR_OpenMP) {
  14237. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  14238. // If the variable is private (i.e. not captured) and has variably
  14239. // modified type, we still need to capture the type for correct
  14240. // codegen in all regions, associated with the construct. Currently,
  14241. // it is captured in the innermost captured region only.
  14242. if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
  14243. QualType QTy = Var->getType();
  14244. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14245. QTy = PVD->getOriginalType();
  14246. for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
  14247. I < E; ++I) {
  14248. auto *OuterRSI = cast<CapturedRegionScopeInfo>(
  14249. FunctionScopes[FunctionScopesIndex - I]);
  14250. assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
  14251. "Wrong number of captured regions associated with the "
  14252. "OpenMP construct.");
  14253. captureVariablyModifiedType(Context, QTy, OuterRSI);
  14254. }
  14255. }
  14256. bool IsTargetCap = !IsOpenMPPrivateDecl &&
  14257. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  14258. // When we detect target captures we are looking from inside the
  14259. // target region, therefore we need to propagate the capture from the
  14260. // enclosing region. Therefore, the capture is not initially nested.
  14261. if (IsTargetCap)
  14262. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  14263. if (IsTargetCap || IsOpenMPPrivateDecl) {
  14264. Nested = !IsTargetCap;
  14265. DeclRefType = DeclRefType.getUnqualifiedType();
  14266. CaptureType = Context.getLValueReferenceType(DeclRefType);
  14267. break;
  14268. }
  14269. }
  14270. }
  14271. }
  14272. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  14273. // No capture-default, and this is not an explicit capture
  14274. // so cannot capture this variable.
  14275. if (BuildAndDiagnose) {
  14276. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14277. Diag(Var->getLocation(), diag::note_previous_decl)
  14278. << Var->getDeclName();
  14279. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  14280. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  14281. diag::note_lambda_decl);
  14282. // FIXME: If we error out because an outer lambda can not implicitly
  14283. // capture a variable that an inner lambda explicitly captures, we
  14284. // should have the inner lambda do the explicit capture - because
  14285. // it makes for cleaner diagnostics later. This would purely be done
  14286. // so that the diagnostic does not misleadingly claim that a variable
  14287. // can not be captured by a lambda implicitly even though it is captured
  14288. // explicitly. Suggestion:
  14289. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  14290. // at the function head
  14291. // - cache the StartingDeclContext - this must be a lambda
  14292. // - captureInLambda in the innermost lambda the variable.
  14293. }
  14294. return true;
  14295. }
  14296. FunctionScopesIndex--;
  14297. DC = ParentDC;
  14298. Explicit = false;
  14299. } while (!VarDC->Equals(DC));
  14300. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  14301. // computing the type of the capture at each step, checking type-specific
  14302. // requirements, and adding captures if requested.
  14303. // If the variable had already been captured previously, we start capturing
  14304. // at the lambda nested within that one.
  14305. bool Invalid = false;
  14306. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  14307. ++I) {
  14308. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  14309. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  14310. // certain types of variables (unnamed, variably modified types etc.)
  14311. // so check for eligibility.
  14312. if (!Invalid)
  14313. Invalid =
  14314. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  14315. // After encountering an error, if we're actually supposed to capture, keep
  14316. // capturing in nested contexts to suppress any follow-on diagnostics.
  14317. if (Invalid && !BuildAndDiagnose)
  14318. return true;
  14319. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  14320. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14321. DeclRefType, Nested, *this, Invalid);
  14322. Nested = true;
  14323. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14324. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  14325. CaptureType, DeclRefType, Nested,
  14326. *this, Invalid);
  14327. Nested = true;
  14328. } else {
  14329. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14330. Invalid =
  14331. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14332. DeclRefType, Nested, Kind, EllipsisLoc,
  14333. /*IsTopScope*/ I == N - 1, *this, Invalid);
  14334. Nested = true;
  14335. }
  14336. if (Invalid && !BuildAndDiagnose)
  14337. return true;
  14338. }
  14339. return Invalid;
  14340. }
  14341. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  14342. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  14343. QualType CaptureType;
  14344. QualType DeclRefType;
  14345. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  14346. /*BuildAndDiagnose=*/true, CaptureType,
  14347. DeclRefType, nullptr);
  14348. }
  14349. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  14350. QualType CaptureType;
  14351. QualType DeclRefType;
  14352. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14353. /*BuildAndDiagnose=*/false, CaptureType,
  14354. DeclRefType, nullptr);
  14355. }
  14356. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  14357. QualType CaptureType;
  14358. QualType DeclRefType;
  14359. // Determine whether we can capture this variable.
  14360. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14361. /*BuildAndDiagnose=*/false, CaptureType,
  14362. DeclRefType, nullptr))
  14363. return QualType();
  14364. return DeclRefType;
  14365. }
  14366. namespace {
  14367. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  14368. // The produced TemplateArgumentListInfo* points to data stored within this
  14369. // object, so should only be used in contexts where the pointer will not be
  14370. // used after the CopiedTemplateArgs object is destroyed.
  14371. class CopiedTemplateArgs {
  14372. bool HasArgs;
  14373. TemplateArgumentListInfo TemplateArgStorage;
  14374. public:
  14375. template<typename RefExpr>
  14376. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  14377. if (HasArgs)
  14378. E->copyTemplateArgumentsInto(TemplateArgStorage);
  14379. }
  14380. operator TemplateArgumentListInfo*()
  14381. #ifdef __has_cpp_attribute
  14382. #if __has_cpp_attribute(clang::lifetimebound)
  14383. [[clang::lifetimebound]]
  14384. #endif
  14385. #endif
  14386. {
  14387. return HasArgs ? &TemplateArgStorage : nullptr;
  14388. }
  14389. };
  14390. }
  14391. /// Walk the set of potential results of an expression and mark them all as
  14392. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  14393. ///
  14394. /// \return A new expression if we found any potential results, ExprEmpty() if
  14395. /// not, and ExprError() if we diagnosed an error.
  14396. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  14397. NonOdrUseReason NOUR) {
  14398. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  14399. // an object that satisfies the requirements for appearing in a
  14400. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  14401. // is immediately applied." This function handles the lvalue-to-rvalue
  14402. // conversion part.
  14403. //
  14404. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  14405. // transform it into the relevant kind of non-odr-use node and rebuild the
  14406. // tree of nodes leading to it.
  14407. //
  14408. // This is a mini-TreeTransform that only transforms a restricted subset of
  14409. // nodes (and only certain operands of them).
  14410. // Rebuild a subexpression.
  14411. auto Rebuild = [&](Expr *Sub) {
  14412. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  14413. };
  14414. // Check whether a potential result satisfies the requirements of NOUR.
  14415. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  14416. // Any entity other than a VarDecl is always odr-used whenever it's named
  14417. // in a potentially-evaluated expression.
  14418. auto *VD = dyn_cast<VarDecl>(D);
  14419. if (!VD)
  14420. return true;
  14421. // C++2a [basic.def.odr]p4:
  14422. // A variable x whose name appears as a potentially-evalauted expression
  14423. // e is odr-used by e unless
  14424. // -- x is a reference that is usable in constant expressions, or
  14425. // -- x is a variable of non-reference type that is usable in constant
  14426. // expressions and has no mutable subobjects, and e is an element of
  14427. // the set of potential results of an expression of
  14428. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14429. // conversion is applied, or
  14430. // -- x is a variable of non-reference type, and e is an element of the
  14431. // set of potential results of a discarded-value expression to which
  14432. // the lvalue-to-rvalue conversion is not applied
  14433. //
  14434. // We check the first bullet and the "potentially-evaluated" condition in
  14435. // BuildDeclRefExpr. We check the type requirements in the second bullet
  14436. // in CheckLValueToRValueConversionOperand below.
  14437. switch (NOUR) {
  14438. case NOUR_None:
  14439. case NOUR_Unevaluated:
  14440. llvm_unreachable("unexpected non-odr-use-reason");
  14441. case NOUR_Constant:
  14442. // Constant references were handled when they were built.
  14443. if (VD->getType()->isReferenceType())
  14444. return true;
  14445. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  14446. if (RD->hasMutableFields())
  14447. return true;
  14448. if (!VD->isUsableInConstantExpressions(S.Context))
  14449. return true;
  14450. break;
  14451. case NOUR_Discarded:
  14452. if (VD->getType()->isReferenceType())
  14453. return true;
  14454. break;
  14455. }
  14456. return false;
  14457. };
  14458. // Mark that this expression does not constitute an odr-use.
  14459. auto MarkNotOdrUsed = [&] {
  14460. S.MaybeODRUseExprs.erase(E);
  14461. if (LambdaScopeInfo *LSI = S.getCurLambda())
  14462. LSI->markVariableExprAsNonODRUsed(E);
  14463. };
  14464. // C++2a [basic.def.odr]p2:
  14465. // The set of potential results of an expression e is defined as follows:
  14466. switch (E->getStmtClass()) {
  14467. // -- If e is an id-expression, ...
  14468. case Expr::DeclRefExprClass: {
  14469. auto *DRE = cast<DeclRefExpr>(E);
  14470. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  14471. break;
  14472. // Rebuild as a non-odr-use DeclRefExpr.
  14473. MarkNotOdrUsed();
  14474. return DeclRefExpr::Create(
  14475. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  14476. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  14477. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  14478. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  14479. }
  14480. case Expr::FunctionParmPackExprClass: {
  14481. auto *FPPE = cast<FunctionParmPackExpr>(E);
  14482. // If any of the declarations in the pack is odr-used, then the expression
  14483. // as a whole constitutes an odr-use.
  14484. for (VarDecl *D : *FPPE)
  14485. if (IsPotentialResultOdrUsed(D))
  14486. return ExprEmpty();
  14487. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  14488. // nothing cares about whether we marked this as an odr-use, but it might
  14489. // be useful for non-compiler tools.
  14490. MarkNotOdrUsed();
  14491. break;
  14492. }
  14493. // -- If e is a subscripting operation with an array operand...
  14494. case Expr::ArraySubscriptExprClass: {
  14495. auto *ASE = cast<ArraySubscriptExpr>(E);
  14496. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  14497. if (!OldBase->getType()->isArrayType())
  14498. break;
  14499. ExprResult Base = Rebuild(OldBase);
  14500. if (!Base.isUsable())
  14501. return Base;
  14502. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  14503. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  14504. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  14505. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  14506. ASE->getRBracketLoc());
  14507. }
  14508. case Expr::MemberExprClass: {
  14509. auto *ME = cast<MemberExpr>(E);
  14510. // -- If e is a class member access expression [...] naming a non-static
  14511. // data member...
  14512. if (isa<FieldDecl>(ME->getMemberDecl())) {
  14513. ExprResult Base = Rebuild(ME->getBase());
  14514. if (!Base.isUsable())
  14515. return Base;
  14516. return MemberExpr::Create(
  14517. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  14518. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  14519. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  14520. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  14521. ME->getObjectKind(), ME->isNonOdrUse());
  14522. }
  14523. if (ME->getMemberDecl()->isCXXInstanceMember())
  14524. break;
  14525. // -- If e is a class member access expression naming a static data member,
  14526. // ...
  14527. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  14528. break;
  14529. // Rebuild as a non-odr-use MemberExpr.
  14530. MarkNotOdrUsed();
  14531. return MemberExpr::Create(
  14532. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  14533. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  14534. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  14535. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  14536. return ExprEmpty();
  14537. }
  14538. case Expr::BinaryOperatorClass: {
  14539. auto *BO = cast<BinaryOperator>(E);
  14540. Expr *LHS = BO->getLHS();
  14541. Expr *RHS = BO->getRHS();
  14542. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  14543. if (BO->getOpcode() == BO_PtrMemD) {
  14544. ExprResult Sub = Rebuild(LHS);
  14545. if (!Sub.isUsable())
  14546. return Sub;
  14547. LHS = Sub.get();
  14548. // -- If e is a comma expression, ...
  14549. } else if (BO->getOpcode() == BO_Comma) {
  14550. ExprResult Sub = Rebuild(RHS);
  14551. if (!Sub.isUsable())
  14552. return Sub;
  14553. RHS = Sub.get();
  14554. } else {
  14555. break;
  14556. }
  14557. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  14558. LHS, RHS);
  14559. }
  14560. // -- If e has the form (e1)...
  14561. case Expr::ParenExprClass: {
  14562. auto *PE = cast<ParenExpr>(E);
  14563. ExprResult Sub = Rebuild(PE->getSubExpr());
  14564. if (!Sub.isUsable())
  14565. return Sub;
  14566. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  14567. }
  14568. // -- If e is a glvalue conditional expression, ...
  14569. // We don't apply this to a binary conditional operator. FIXME: Should we?
  14570. case Expr::ConditionalOperatorClass: {
  14571. auto *CO = cast<ConditionalOperator>(E);
  14572. ExprResult LHS = Rebuild(CO->getLHS());
  14573. if (LHS.isInvalid())
  14574. return ExprError();
  14575. ExprResult RHS = Rebuild(CO->getRHS());
  14576. if (RHS.isInvalid())
  14577. return ExprError();
  14578. if (!LHS.isUsable() && !RHS.isUsable())
  14579. return ExprEmpty();
  14580. if (!LHS.isUsable())
  14581. LHS = CO->getLHS();
  14582. if (!RHS.isUsable())
  14583. RHS = CO->getRHS();
  14584. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  14585. CO->getCond(), LHS.get(), RHS.get());
  14586. }
  14587. // [Clang extension]
  14588. // -- If e has the form __extension__ e1...
  14589. case Expr::UnaryOperatorClass: {
  14590. auto *UO = cast<UnaryOperator>(E);
  14591. if (UO->getOpcode() != UO_Extension)
  14592. break;
  14593. ExprResult Sub = Rebuild(UO->getSubExpr());
  14594. if (!Sub.isUsable())
  14595. return Sub;
  14596. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  14597. Sub.get());
  14598. }
  14599. // [Clang extension]
  14600. // -- If e has the form _Generic(...), the set of potential results is the
  14601. // union of the sets of potential results of the associated expressions.
  14602. case Expr::GenericSelectionExprClass: {
  14603. auto *GSE = cast<GenericSelectionExpr>(E);
  14604. SmallVector<Expr *, 4> AssocExprs;
  14605. bool AnyChanged = false;
  14606. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  14607. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  14608. if (AssocExpr.isInvalid())
  14609. return ExprError();
  14610. if (AssocExpr.isUsable()) {
  14611. AssocExprs.push_back(AssocExpr.get());
  14612. AnyChanged = true;
  14613. } else {
  14614. AssocExprs.push_back(OrigAssocExpr);
  14615. }
  14616. }
  14617. return AnyChanged ? S.CreateGenericSelectionExpr(
  14618. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  14619. GSE->getRParenLoc(), GSE->getControllingExpr(),
  14620. GSE->getAssocTypeSourceInfos(), AssocExprs)
  14621. : ExprEmpty();
  14622. }
  14623. // [Clang extension]
  14624. // -- If e has the form __builtin_choose_expr(...), the set of potential
  14625. // results is the union of the sets of potential results of the
  14626. // second and third subexpressions.
  14627. case Expr::ChooseExprClass: {
  14628. auto *CE = cast<ChooseExpr>(E);
  14629. ExprResult LHS = Rebuild(CE->getLHS());
  14630. if (LHS.isInvalid())
  14631. return ExprError();
  14632. ExprResult RHS = Rebuild(CE->getLHS());
  14633. if (RHS.isInvalid())
  14634. return ExprError();
  14635. if (!LHS.get() && !RHS.get())
  14636. return ExprEmpty();
  14637. if (!LHS.isUsable())
  14638. LHS = CE->getLHS();
  14639. if (!RHS.isUsable())
  14640. RHS = CE->getRHS();
  14641. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  14642. RHS.get(), CE->getRParenLoc());
  14643. }
  14644. // Step through non-syntactic nodes.
  14645. case Expr::ConstantExprClass: {
  14646. auto *CE = cast<ConstantExpr>(E);
  14647. ExprResult Sub = Rebuild(CE->getSubExpr());
  14648. if (!Sub.isUsable())
  14649. return Sub;
  14650. return ConstantExpr::Create(S.Context, Sub.get());
  14651. }
  14652. // We could mostly rely on the recursive rebuilding to rebuild implicit
  14653. // casts, but not at the top level, so rebuild them here.
  14654. case Expr::ImplicitCastExprClass: {
  14655. auto *ICE = cast<ImplicitCastExpr>(E);
  14656. // Only step through the narrow set of cast kinds we expect to encounter.
  14657. // Anything else suggests we've left the region in which potential results
  14658. // can be found.
  14659. switch (ICE->getCastKind()) {
  14660. case CK_NoOp:
  14661. case CK_DerivedToBase:
  14662. case CK_UncheckedDerivedToBase: {
  14663. ExprResult Sub = Rebuild(ICE->getSubExpr());
  14664. if (!Sub.isUsable())
  14665. return Sub;
  14666. CXXCastPath Path(ICE->path());
  14667. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  14668. ICE->getValueKind(), &Path);
  14669. }
  14670. default:
  14671. break;
  14672. }
  14673. break;
  14674. }
  14675. default:
  14676. break;
  14677. }
  14678. // Can't traverse through this node. Nothing to do.
  14679. return ExprEmpty();
  14680. }
  14681. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  14682. // Check whether the operand is or contains an object of non-trivial C union
  14683. // type.
  14684. if (E->getType().isVolatileQualified() &&
  14685. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  14686. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  14687. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  14688. Sema::NTCUC_LValueToRValueVolatile,
  14689. NTCUK_Destruct|NTCUK_Copy);
  14690. // C++2a [basic.def.odr]p4:
  14691. // [...] an expression of non-volatile-qualified non-class type to which
  14692. // the lvalue-to-rvalue conversion is applied [...]
  14693. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  14694. return E;
  14695. ExprResult Result =
  14696. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  14697. if (Result.isInvalid())
  14698. return ExprError();
  14699. return Result.get() ? Result : E;
  14700. }
  14701. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  14702. Res = CorrectDelayedTyposInExpr(Res);
  14703. if (!Res.isUsable())
  14704. return Res;
  14705. // If a constant-expression is a reference to a variable where we delay
  14706. // deciding whether it is an odr-use, just assume we will apply the
  14707. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  14708. // (a non-type template argument), we have special handling anyway.
  14709. return CheckLValueToRValueConversionOperand(Res.get());
  14710. }
  14711. void Sema::CleanupVarDeclMarking() {
  14712. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  14713. // call.
  14714. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  14715. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  14716. for (Expr *E : LocalMaybeODRUseExprs) {
  14717. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  14718. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  14719. DRE->getLocation(), *this);
  14720. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  14721. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  14722. *this);
  14723. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  14724. for (VarDecl *VD : *FP)
  14725. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  14726. } else {
  14727. llvm_unreachable("Unexpected expression");
  14728. }
  14729. }
  14730. assert(MaybeODRUseExprs.empty() &&
  14731. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  14732. }
  14733. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  14734. VarDecl *Var, Expr *E) {
  14735. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  14736. isa<FunctionParmPackExpr>(E)) &&
  14737. "Invalid Expr argument to DoMarkVarDeclReferenced");
  14738. Var->setReferenced();
  14739. if (Var->isInvalidDecl())
  14740. return;
  14741. auto *MSI = Var->getMemberSpecializationInfo();
  14742. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  14743. : Var->getTemplateSpecializationKind();
  14744. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  14745. bool UsableInConstantExpr =
  14746. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  14747. // C++20 [expr.const]p12:
  14748. // A variable [...] is needed for constant evaluation if it is [...] a
  14749. // variable whose name appears as a potentially constant evaluated
  14750. // expression that is either a contexpr variable or is of non-volatile
  14751. // const-qualified integral type or of reference type
  14752. bool NeededForConstantEvaluation =
  14753. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  14754. bool NeedDefinition =
  14755. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  14756. VarTemplateSpecializationDecl *VarSpec =
  14757. dyn_cast<VarTemplateSpecializationDecl>(Var);
  14758. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  14759. "Can't instantiate a partial template specialization.");
  14760. // If this might be a member specialization of a static data member, check
  14761. // the specialization is visible. We already did the checks for variable
  14762. // template specializations when we created them.
  14763. if (NeedDefinition && TSK != TSK_Undeclared &&
  14764. !isa<VarTemplateSpecializationDecl>(Var))
  14765. SemaRef.checkSpecializationVisibility(Loc, Var);
  14766. // Perform implicit instantiation of static data members, static data member
  14767. // templates of class templates, and variable template specializations. Delay
  14768. // instantiations of variable templates, except for those that could be used
  14769. // in a constant expression.
  14770. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  14771. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  14772. // instantiation declaration if a variable is usable in a constant
  14773. // expression (among other cases).
  14774. bool TryInstantiating =
  14775. TSK == TSK_ImplicitInstantiation ||
  14776. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  14777. if (TryInstantiating) {
  14778. SourceLocation PointOfInstantiation =
  14779. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  14780. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  14781. if (FirstInstantiation) {
  14782. PointOfInstantiation = Loc;
  14783. if (MSI)
  14784. MSI->setPointOfInstantiation(PointOfInstantiation);
  14785. else
  14786. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  14787. }
  14788. bool InstantiationDependent = false;
  14789. bool IsNonDependent =
  14790. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  14791. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  14792. : true;
  14793. // Do not instantiate specializations that are still type-dependent.
  14794. if (IsNonDependent) {
  14795. if (UsableInConstantExpr) {
  14796. // Do not defer instantiations of variables that could be used in a
  14797. // constant expression.
  14798. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  14799. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  14800. });
  14801. } else if (FirstInstantiation ||
  14802. isa<VarTemplateSpecializationDecl>(Var)) {
  14803. // FIXME: For a specialization of a variable template, we don't
  14804. // distinguish between "declaration and type implicitly instantiated"
  14805. // and "implicit instantiation of definition requested", so we have
  14806. // no direct way to avoid enqueueing the pending instantiation
  14807. // multiple times.
  14808. SemaRef.PendingInstantiations
  14809. .push_back(std::make_pair(Var, PointOfInstantiation));
  14810. }
  14811. }
  14812. }
  14813. }
  14814. // C++2a [basic.def.odr]p4:
  14815. // A variable x whose name appears as a potentially-evaluated expression e
  14816. // is odr-used by e unless
  14817. // -- x is a reference that is usable in constant expressions
  14818. // -- x is a variable of non-reference type that is usable in constant
  14819. // expressions and has no mutable subobjects [FIXME], and e is an
  14820. // element of the set of potential results of an expression of
  14821. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14822. // conversion is applied
  14823. // -- x is a variable of non-reference type, and e is an element of the set
  14824. // of potential results of a discarded-value expression to which the
  14825. // lvalue-to-rvalue conversion is not applied [FIXME]
  14826. //
  14827. // We check the first part of the second bullet here, and
  14828. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  14829. // FIXME: To get the third bullet right, we need to delay this even for
  14830. // variables that are not usable in constant expressions.
  14831. // If we already know this isn't an odr-use, there's nothing more to do.
  14832. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  14833. if (DRE->isNonOdrUse())
  14834. return;
  14835. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  14836. if (ME->isNonOdrUse())
  14837. return;
  14838. switch (OdrUse) {
  14839. case OdrUseContext::None:
  14840. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  14841. "missing non-odr-use marking for unevaluated decl ref");
  14842. break;
  14843. case OdrUseContext::FormallyOdrUsed:
  14844. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14845. // behavior.
  14846. break;
  14847. case OdrUseContext::Used:
  14848. // If we might later find that this expression isn't actually an odr-use,
  14849. // delay the marking.
  14850. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  14851. SemaRef.MaybeODRUseExprs.insert(E);
  14852. else
  14853. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  14854. break;
  14855. case OdrUseContext::Dependent:
  14856. // If this is a dependent context, we don't need to mark variables as
  14857. // odr-used, but we may still need to track them for lambda capture.
  14858. // FIXME: Do we also need to do this inside dependent typeid expressions
  14859. // (which are modeled as unevaluated at this point)?
  14860. const bool RefersToEnclosingScope =
  14861. (SemaRef.CurContext != Var->getDeclContext() &&
  14862. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14863. if (RefersToEnclosingScope) {
  14864. LambdaScopeInfo *const LSI =
  14865. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14866. if (LSI && (!LSI->CallOperator ||
  14867. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14868. // If a variable could potentially be odr-used, defer marking it so
  14869. // until we finish analyzing the full expression for any
  14870. // lvalue-to-rvalue
  14871. // or discarded value conversions that would obviate odr-use.
  14872. // Add it to the list of potential captures that will be analyzed
  14873. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14874. // unless the variable is a reference that was initialized by a constant
  14875. // expression (this will never need to be captured or odr-used).
  14876. //
  14877. // FIXME: We can simplify this a lot after implementing P0588R1.
  14878. assert(E && "Capture variable should be used in an expression.");
  14879. if (!Var->getType()->isReferenceType() ||
  14880. !Var->isUsableInConstantExpressions(SemaRef.Context))
  14881. LSI->addPotentialCapture(E->IgnoreParens());
  14882. }
  14883. }
  14884. break;
  14885. }
  14886. }
  14887. /// Mark a variable referenced, and check whether it is odr-used
  14888. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14889. /// used directly for normal expressions referring to VarDecl.
  14890. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14891. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14892. }
  14893. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14894. Decl *D, Expr *E, bool MightBeOdrUse) {
  14895. if (SemaRef.isInOpenMPDeclareTargetContext())
  14896. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14897. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14898. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14899. return;
  14900. }
  14901. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14902. // If this is a call to a method via a cast, also mark the method in the
  14903. // derived class used in case codegen can devirtualize the call.
  14904. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14905. if (!ME)
  14906. return;
  14907. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14908. if (!MD)
  14909. return;
  14910. // Only attempt to devirtualize if this is truly a virtual call.
  14911. bool IsVirtualCall = MD->isVirtual() &&
  14912. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14913. if (!IsVirtualCall)
  14914. return;
  14915. // If it's possible to devirtualize the call, mark the called function
  14916. // referenced.
  14917. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14918. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14919. if (DM)
  14920. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14921. }
  14922. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14923. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14924. // TODO: update this with DR# once a defect report is filed.
  14925. // C++11 defect. The address of a pure member should not be an ODR use, even
  14926. // if it's a qualified reference.
  14927. bool OdrUse = true;
  14928. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14929. if (Method->isVirtual() &&
  14930. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14931. OdrUse = false;
  14932. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14933. }
  14934. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14935. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14936. // C++11 [basic.def.odr]p2:
  14937. // A non-overloaded function whose name appears as a potentially-evaluated
  14938. // expression or a member of a set of candidate functions, if selected by
  14939. // overload resolution when referred to from a potentially-evaluated
  14940. // expression, is odr-used, unless it is a pure virtual function and its
  14941. // name is not explicitly qualified.
  14942. bool MightBeOdrUse = true;
  14943. if (E->performsVirtualDispatch(getLangOpts())) {
  14944. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14945. if (Method->isPure())
  14946. MightBeOdrUse = false;
  14947. }
  14948. SourceLocation Loc =
  14949. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14950. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14951. }
  14952. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14953. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14954. for (VarDecl *VD : *E)
  14955. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14956. }
  14957. /// Perform marking for a reference to an arbitrary declaration. It
  14958. /// marks the declaration referenced, and performs odr-use checking for
  14959. /// functions and variables. This method should not be used when building a
  14960. /// normal expression which refers to a variable.
  14961. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14962. bool MightBeOdrUse) {
  14963. if (MightBeOdrUse) {
  14964. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14965. MarkVariableReferenced(Loc, VD);
  14966. return;
  14967. }
  14968. }
  14969. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14970. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14971. return;
  14972. }
  14973. D->setReferenced();
  14974. }
  14975. namespace {
  14976. // Mark all of the declarations used by a type as referenced.
  14977. // FIXME: Not fully implemented yet! We need to have a better understanding
  14978. // of when we're entering a context we should not recurse into.
  14979. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14980. // TreeTransforms rebuilding the type in a new context. Rather than
  14981. // duplicating the TreeTransform logic, we should consider reusing it here.
  14982. // Currently that causes problems when rebuilding LambdaExprs.
  14983. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14984. Sema &S;
  14985. SourceLocation Loc;
  14986. public:
  14987. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14988. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14989. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14990. };
  14991. }
  14992. bool MarkReferencedDecls::TraverseTemplateArgument(
  14993. const TemplateArgument &Arg) {
  14994. {
  14995. // A non-type template argument is a constant-evaluated context.
  14996. EnterExpressionEvaluationContext Evaluated(
  14997. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14998. if (Arg.getKind() == TemplateArgument::Declaration) {
  14999. if (Decl *D = Arg.getAsDecl())
  15000. S.MarkAnyDeclReferenced(Loc, D, true);
  15001. } else if (Arg.getKind() == TemplateArgument::Expression) {
  15002. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  15003. }
  15004. }
  15005. return Inherited::TraverseTemplateArgument(Arg);
  15006. }
  15007. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  15008. MarkReferencedDecls Marker(*this, Loc);
  15009. Marker.TraverseType(T);
  15010. }
  15011. namespace {
  15012. /// Helper class that marks all of the declarations referenced by
  15013. /// potentially-evaluated subexpressions as "referenced".
  15014. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  15015. Sema &S;
  15016. bool SkipLocalVariables;
  15017. public:
  15018. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  15019. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  15020. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  15021. void VisitDeclRefExpr(DeclRefExpr *E) {
  15022. // If we were asked not to visit local variables, don't.
  15023. if (SkipLocalVariables) {
  15024. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  15025. if (VD->hasLocalStorage())
  15026. return;
  15027. }
  15028. S.MarkDeclRefReferenced(E);
  15029. }
  15030. void VisitMemberExpr(MemberExpr *E) {
  15031. S.MarkMemberReferenced(E);
  15032. Inherited::VisitMemberExpr(E);
  15033. }
  15034. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  15035. S.MarkFunctionReferenced(
  15036. E->getBeginLoc(),
  15037. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  15038. Visit(E->getSubExpr());
  15039. }
  15040. void VisitCXXNewExpr(CXXNewExpr *E) {
  15041. if (E->getOperatorNew())
  15042. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  15043. if (E->getOperatorDelete())
  15044. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  15045. Inherited::VisitCXXNewExpr(E);
  15046. }
  15047. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  15048. if (E->getOperatorDelete())
  15049. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  15050. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  15051. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  15052. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  15053. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  15054. }
  15055. Inherited::VisitCXXDeleteExpr(E);
  15056. }
  15057. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  15058. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  15059. Inherited::VisitCXXConstructExpr(E);
  15060. }
  15061. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  15062. Visit(E->getExpr());
  15063. }
  15064. };
  15065. }
  15066. /// Mark any declarations that appear within this expression or any
  15067. /// potentially-evaluated subexpressions as "referenced".
  15068. ///
  15069. /// \param SkipLocalVariables If true, don't mark local variables as
  15070. /// 'referenced'.
  15071. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  15072. bool SkipLocalVariables) {
  15073. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  15074. }
  15075. /// Emit a diagnostic that describes an effect on the run-time behavior
  15076. /// of the program being compiled.
  15077. ///
  15078. /// This routine emits the given diagnostic when the code currently being
  15079. /// type-checked is "potentially evaluated", meaning that there is a
  15080. /// possibility that the code will actually be executable. Code in sizeof()
  15081. /// expressions, code used only during overload resolution, etc., are not
  15082. /// potentially evaluated. This routine will suppress such diagnostics or,
  15083. /// in the absolutely nutty case of potentially potentially evaluated
  15084. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  15085. /// later.
  15086. ///
  15087. /// This routine should be used for all diagnostics that describe the run-time
  15088. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  15089. /// Failure to do so will likely result in spurious diagnostics or failures
  15090. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  15091. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  15092. const PartialDiagnostic &PD) {
  15093. switch (ExprEvalContexts.back().Context) {
  15094. case ExpressionEvaluationContext::Unevaluated:
  15095. case ExpressionEvaluationContext::UnevaluatedList:
  15096. case ExpressionEvaluationContext::UnevaluatedAbstract:
  15097. case ExpressionEvaluationContext::DiscardedStatement:
  15098. // The argument will never be evaluated, so don't complain.
  15099. break;
  15100. case ExpressionEvaluationContext::ConstantEvaluated:
  15101. // Relevant diagnostics should be produced by constant evaluation.
  15102. break;
  15103. case ExpressionEvaluationContext::PotentiallyEvaluated:
  15104. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  15105. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  15106. FunctionScopes.back()->PossiblyUnreachableDiags.
  15107. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  15108. return true;
  15109. }
  15110. // The initializer of a constexpr variable or of the first declaration of a
  15111. // static data member is not syntactically a constant evaluated constant,
  15112. // but nonetheless is always required to be a constant expression, so we
  15113. // can skip diagnosing.
  15114. // FIXME: Using the mangling context here is a hack.
  15115. if (auto *VD = dyn_cast_or_null<VarDecl>(
  15116. ExprEvalContexts.back().ManglingContextDecl)) {
  15117. if (VD->isConstexpr() ||
  15118. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  15119. break;
  15120. // FIXME: For any other kind of variable, we should build a CFG for its
  15121. // initializer and check whether the context in question is reachable.
  15122. }
  15123. Diag(Loc, PD);
  15124. return true;
  15125. }
  15126. return false;
  15127. }
  15128. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  15129. const PartialDiagnostic &PD) {
  15130. return DiagRuntimeBehavior(
  15131. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  15132. }
  15133. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  15134. CallExpr *CE, FunctionDecl *FD) {
  15135. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  15136. return false;
  15137. // If we're inside a decltype's expression, don't check for a valid return
  15138. // type or construct temporaries until we know whether this is the last call.
  15139. if (ExprEvalContexts.back().ExprContext ==
  15140. ExpressionEvaluationContextRecord::EK_Decltype) {
  15141. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  15142. return false;
  15143. }
  15144. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  15145. FunctionDecl *FD;
  15146. CallExpr *CE;
  15147. public:
  15148. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  15149. : FD(FD), CE(CE) { }
  15150. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  15151. if (!FD) {
  15152. S.Diag(Loc, diag::err_call_incomplete_return)
  15153. << T << CE->getSourceRange();
  15154. return;
  15155. }
  15156. S.Diag(Loc, diag::err_call_function_incomplete_return)
  15157. << CE->getSourceRange() << FD->getDeclName() << T;
  15158. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  15159. << FD->getDeclName();
  15160. }
  15161. } Diagnoser(FD, CE);
  15162. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  15163. return true;
  15164. return false;
  15165. }
  15166. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  15167. // will prevent this condition from triggering, which is what we want.
  15168. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  15169. SourceLocation Loc;
  15170. unsigned diagnostic = diag::warn_condition_is_assignment;
  15171. bool IsOrAssign = false;
  15172. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  15173. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  15174. return;
  15175. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  15176. // Greylist some idioms by putting them into a warning subcategory.
  15177. if (ObjCMessageExpr *ME
  15178. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  15179. Selector Sel = ME->getSelector();
  15180. // self = [<foo> init...]
  15181. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  15182. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15183. // <foo> = [<bar> nextObject]
  15184. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  15185. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15186. }
  15187. Loc = Op->getOperatorLoc();
  15188. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  15189. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  15190. return;
  15191. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  15192. Loc = Op->getOperatorLoc();
  15193. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  15194. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  15195. else {
  15196. // Not an assignment.
  15197. return;
  15198. }
  15199. Diag(Loc, diagnostic) << E->getSourceRange();
  15200. SourceLocation Open = E->getBeginLoc();
  15201. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  15202. Diag(Loc, diag::note_condition_assign_silence)
  15203. << FixItHint::CreateInsertion(Open, "(")
  15204. << FixItHint::CreateInsertion(Close, ")");
  15205. if (IsOrAssign)
  15206. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  15207. << FixItHint::CreateReplacement(Loc, "!=");
  15208. else
  15209. Diag(Loc, diag::note_condition_assign_to_comparison)
  15210. << FixItHint::CreateReplacement(Loc, "==");
  15211. }
  15212. /// Redundant parentheses over an equality comparison can indicate
  15213. /// that the user intended an assignment used as condition.
  15214. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  15215. // Don't warn if the parens came from a macro.
  15216. SourceLocation parenLoc = ParenE->getBeginLoc();
  15217. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  15218. return;
  15219. // Don't warn for dependent expressions.
  15220. if (ParenE->isTypeDependent())
  15221. return;
  15222. Expr *E = ParenE->IgnoreParens();
  15223. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  15224. if (opE->getOpcode() == BO_EQ &&
  15225. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  15226. == Expr::MLV_Valid) {
  15227. SourceLocation Loc = opE->getOperatorLoc();
  15228. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  15229. SourceRange ParenERange = ParenE->getSourceRange();
  15230. Diag(Loc, diag::note_equality_comparison_silence)
  15231. << FixItHint::CreateRemoval(ParenERange.getBegin())
  15232. << FixItHint::CreateRemoval(ParenERange.getEnd());
  15233. Diag(Loc, diag::note_equality_comparison_to_assign)
  15234. << FixItHint::CreateReplacement(Loc, "=");
  15235. }
  15236. }
  15237. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  15238. bool IsConstexpr) {
  15239. DiagnoseAssignmentAsCondition(E);
  15240. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  15241. DiagnoseEqualityWithExtraParens(parenE);
  15242. ExprResult result = CheckPlaceholderExpr(E);
  15243. if (result.isInvalid()) return ExprError();
  15244. E = result.get();
  15245. if (!E->isTypeDependent()) {
  15246. if (getLangOpts().CPlusPlus)
  15247. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  15248. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  15249. if (ERes.isInvalid())
  15250. return ExprError();
  15251. E = ERes.get();
  15252. QualType T = E->getType();
  15253. if (!T->isScalarType()) { // C99 6.8.4.1p1
  15254. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  15255. << T << E->getSourceRange();
  15256. return ExprError();
  15257. }
  15258. CheckBoolLikeConversion(E, Loc);
  15259. }
  15260. return E;
  15261. }
  15262. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  15263. Expr *SubExpr, ConditionKind CK) {
  15264. // Empty conditions are valid in for-statements.
  15265. if (!SubExpr)
  15266. return ConditionResult();
  15267. ExprResult Cond;
  15268. switch (CK) {
  15269. case ConditionKind::Boolean:
  15270. Cond = CheckBooleanCondition(Loc, SubExpr);
  15271. break;
  15272. case ConditionKind::ConstexprIf:
  15273. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  15274. break;
  15275. case ConditionKind::Switch:
  15276. Cond = CheckSwitchCondition(Loc, SubExpr);
  15277. break;
  15278. }
  15279. if (Cond.isInvalid())
  15280. return ConditionError();
  15281. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  15282. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  15283. if (!FullExpr.get())
  15284. return ConditionError();
  15285. return ConditionResult(*this, nullptr, FullExpr,
  15286. CK == ConditionKind::ConstexprIf);
  15287. }
  15288. namespace {
  15289. /// A visitor for rebuilding a call to an __unknown_any expression
  15290. /// to have an appropriate type.
  15291. struct RebuildUnknownAnyFunction
  15292. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  15293. Sema &S;
  15294. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  15295. ExprResult VisitStmt(Stmt *S) {
  15296. llvm_unreachable("unexpected statement!");
  15297. }
  15298. ExprResult VisitExpr(Expr *E) {
  15299. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  15300. << E->getSourceRange();
  15301. return ExprError();
  15302. }
  15303. /// Rebuild an expression which simply semantically wraps another
  15304. /// expression which it shares the type and value kind of.
  15305. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15306. ExprResult SubResult = Visit(E->getSubExpr());
  15307. if (SubResult.isInvalid()) return ExprError();
  15308. Expr *SubExpr = SubResult.get();
  15309. E->setSubExpr(SubExpr);
  15310. E->setType(SubExpr->getType());
  15311. E->setValueKind(SubExpr->getValueKind());
  15312. assert(E->getObjectKind() == OK_Ordinary);
  15313. return E;
  15314. }
  15315. ExprResult VisitParenExpr(ParenExpr *E) {
  15316. return rebuildSugarExpr(E);
  15317. }
  15318. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15319. return rebuildSugarExpr(E);
  15320. }
  15321. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15322. ExprResult SubResult = Visit(E->getSubExpr());
  15323. if (SubResult.isInvalid()) return ExprError();
  15324. Expr *SubExpr = SubResult.get();
  15325. E->setSubExpr(SubExpr);
  15326. E->setType(S.Context.getPointerType(SubExpr->getType()));
  15327. assert(E->getValueKind() == VK_RValue);
  15328. assert(E->getObjectKind() == OK_Ordinary);
  15329. return E;
  15330. }
  15331. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  15332. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  15333. E->setType(VD->getType());
  15334. assert(E->getValueKind() == VK_RValue);
  15335. if (S.getLangOpts().CPlusPlus &&
  15336. !(isa<CXXMethodDecl>(VD) &&
  15337. cast<CXXMethodDecl>(VD)->isInstance()))
  15338. E->setValueKind(VK_LValue);
  15339. return E;
  15340. }
  15341. ExprResult VisitMemberExpr(MemberExpr *E) {
  15342. return resolveDecl(E, E->getMemberDecl());
  15343. }
  15344. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15345. return resolveDecl(E, E->getDecl());
  15346. }
  15347. };
  15348. }
  15349. /// Given a function expression of unknown-any type, try to rebuild it
  15350. /// to have a function type.
  15351. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  15352. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  15353. if (Result.isInvalid()) return ExprError();
  15354. return S.DefaultFunctionArrayConversion(Result.get());
  15355. }
  15356. namespace {
  15357. /// A visitor for rebuilding an expression of type __unknown_anytype
  15358. /// into one which resolves the type directly on the referring
  15359. /// expression. Strict preservation of the original source
  15360. /// structure is not a goal.
  15361. struct RebuildUnknownAnyExpr
  15362. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  15363. Sema &S;
  15364. /// The current destination type.
  15365. QualType DestType;
  15366. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  15367. : S(S), DestType(CastType) {}
  15368. ExprResult VisitStmt(Stmt *S) {
  15369. llvm_unreachable("unexpected statement!");
  15370. }
  15371. ExprResult VisitExpr(Expr *E) {
  15372. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15373. << E->getSourceRange();
  15374. return ExprError();
  15375. }
  15376. ExprResult VisitCallExpr(CallExpr *E);
  15377. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  15378. /// Rebuild an expression which simply semantically wraps another
  15379. /// expression which it shares the type and value kind of.
  15380. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15381. ExprResult SubResult = Visit(E->getSubExpr());
  15382. if (SubResult.isInvalid()) return ExprError();
  15383. Expr *SubExpr = SubResult.get();
  15384. E->setSubExpr(SubExpr);
  15385. E->setType(SubExpr->getType());
  15386. E->setValueKind(SubExpr->getValueKind());
  15387. assert(E->getObjectKind() == OK_Ordinary);
  15388. return E;
  15389. }
  15390. ExprResult VisitParenExpr(ParenExpr *E) {
  15391. return rebuildSugarExpr(E);
  15392. }
  15393. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15394. return rebuildSugarExpr(E);
  15395. }
  15396. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15397. const PointerType *Ptr = DestType->getAs<PointerType>();
  15398. if (!Ptr) {
  15399. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  15400. << E->getSourceRange();
  15401. return ExprError();
  15402. }
  15403. if (isa<CallExpr>(E->getSubExpr())) {
  15404. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  15405. << E->getSourceRange();
  15406. return ExprError();
  15407. }
  15408. assert(E->getValueKind() == VK_RValue);
  15409. assert(E->getObjectKind() == OK_Ordinary);
  15410. E->setType(DestType);
  15411. // Build the sub-expression as if it were an object of the pointee type.
  15412. DestType = Ptr->getPointeeType();
  15413. ExprResult SubResult = Visit(E->getSubExpr());
  15414. if (SubResult.isInvalid()) return ExprError();
  15415. E->setSubExpr(SubResult.get());
  15416. return E;
  15417. }
  15418. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  15419. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  15420. ExprResult VisitMemberExpr(MemberExpr *E) {
  15421. return resolveDecl(E, E->getMemberDecl());
  15422. }
  15423. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15424. return resolveDecl(E, E->getDecl());
  15425. }
  15426. };
  15427. }
  15428. /// Rebuilds a call expression which yielded __unknown_anytype.
  15429. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  15430. Expr *CalleeExpr = E->getCallee();
  15431. enum FnKind {
  15432. FK_MemberFunction,
  15433. FK_FunctionPointer,
  15434. FK_BlockPointer
  15435. };
  15436. FnKind Kind;
  15437. QualType CalleeType = CalleeExpr->getType();
  15438. if (CalleeType == S.Context.BoundMemberTy) {
  15439. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  15440. Kind = FK_MemberFunction;
  15441. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  15442. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  15443. CalleeType = Ptr->getPointeeType();
  15444. Kind = FK_FunctionPointer;
  15445. } else {
  15446. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  15447. Kind = FK_BlockPointer;
  15448. }
  15449. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  15450. // Verify that this is a legal result type of a function.
  15451. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15452. unsigned diagID = diag::err_func_returning_array_function;
  15453. if (Kind == FK_BlockPointer)
  15454. diagID = diag::err_block_returning_array_function;
  15455. S.Diag(E->getExprLoc(), diagID)
  15456. << DestType->isFunctionType() << DestType;
  15457. return ExprError();
  15458. }
  15459. // Otherwise, go ahead and set DestType as the call's result.
  15460. E->setType(DestType.getNonLValueExprType(S.Context));
  15461. E->setValueKind(Expr::getValueKindForType(DestType));
  15462. assert(E->getObjectKind() == OK_Ordinary);
  15463. // Rebuild the function type, replacing the result type with DestType.
  15464. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  15465. if (Proto) {
  15466. // __unknown_anytype(...) is a special case used by the debugger when
  15467. // it has no idea what a function's signature is.
  15468. //
  15469. // We want to build this call essentially under the K&R
  15470. // unprototyped rules, but making a FunctionNoProtoType in C++
  15471. // would foul up all sorts of assumptions. However, we cannot
  15472. // simply pass all arguments as variadic arguments, nor can we
  15473. // portably just call the function under a non-variadic type; see
  15474. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  15475. // However, it turns out that in practice it is generally safe to
  15476. // call a function declared as "A foo(B,C,D);" under the prototype
  15477. // "A foo(B,C,D,...);". The only known exception is with the
  15478. // Windows ABI, where any variadic function is implicitly cdecl
  15479. // regardless of its normal CC. Therefore we change the parameter
  15480. // types to match the types of the arguments.
  15481. //
  15482. // This is a hack, but it is far superior to moving the
  15483. // corresponding target-specific code from IR-gen to Sema/AST.
  15484. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  15485. SmallVector<QualType, 8> ArgTypes;
  15486. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  15487. ArgTypes.reserve(E->getNumArgs());
  15488. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  15489. Expr *Arg = E->getArg(i);
  15490. QualType ArgType = Arg->getType();
  15491. if (E->isLValue()) {
  15492. ArgType = S.Context.getLValueReferenceType(ArgType);
  15493. } else if (E->isXValue()) {
  15494. ArgType = S.Context.getRValueReferenceType(ArgType);
  15495. }
  15496. ArgTypes.push_back(ArgType);
  15497. }
  15498. ParamTypes = ArgTypes;
  15499. }
  15500. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  15501. Proto->getExtProtoInfo());
  15502. } else {
  15503. DestType = S.Context.getFunctionNoProtoType(DestType,
  15504. FnType->getExtInfo());
  15505. }
  15506. // Rebuild the appropriate pointer-to-function type.
  15507. switch (Kind) {
  15508. case FK_MemberFunction:
  15509. // Nothing to do.
  15510. break;
  15511. case FK_FunctionPointer:
  15512. DestType = S.Context.getPointerType(DestType);
  15513. break;
  15514. case FK_BlockPointer:
  15515. DestType = S.Context.getBlockPointerType(DestType);
  15516. break;
  15517. }
  15518. // Finally, we can recurse.
  15519. ExprResult CalleeResult = Visit(CalleeExpr);
  15520. if (!CalleeResult.isUsable()) return ExprError();
  15521. E->setCallee(CalleeResult.get());
  15522. // Bind a temporary if necessary.
  15523. return S.MaybeBindToTemporary(E);
  15524. }
  15525. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  15526. // Verify that this is a legal result type of a call.
  15527. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15528. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  15529. << DestType->isFunctionType() << DestType;
  15530. return ExprError();
  15531. }
  15532. // Rewrite the method result type if available.
  15533. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  15534. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  15535. Method->setReturnType(DestType);
  15536. }
  15537. // Change the type of the message.
  15538. E->setType(DestType.getNonReferenceType());
  15539. E->setValueKind(Expr::getValueKindForType(DestType));
  15540. return S.MaybeBindToTemporary(E);
  15541. }
  15542. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  15543. // The only case we should ever see here is a function-to-pointer decay.
  15544. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  15545. assert(E->getValueKind() == VK_RValue);
  15546. assert(E->getObjectKind() == OK_Ordinary);
  15547. E->setType(DestType);
  15548. // Rebuild the sub-expression as the pointee (function) type.
  15549. DestType = DestType->castAs<PointerType>()->getPointeeType();
  15550. ExprResult Result = Visit(E->getSubExpr());
  15551. if (!Result.isUsable()) return ExprError();
  15552. E->setSubExpr(Result.get());
  15553. return E;
  15554. } else if (E->getCastKind() == CK_LValueToRValue) {
  15555. assert(E->getValueKind() == VK_RValue);
  15556. assert(E->getObjectKind() == OK_Ordinary);
  15557. assert(isa<BlockPointerType>(E->getType()));
  15558. E->setType(DestType);
  15559. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  15560. DestType = S.Context.getLValueReferenceType(DestType);
  15561. ExprResult Result = Visit(E->getSubExpr());
  15562. if (!Result.isUsable()) return ExprError();
  15563. E->setSubExpr(Result.get());
  15564. return E;
  15565. } else {
  15566. llvm_unreachable("Unhandled cast type!");
  15567. }
  15568. }
  15569. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  15570. ExprValueKind ValueKind = VK_LValue;
  15571. QualType Type = DestType;
  15572. // We know how to make this work for certain kinds of decls:
  15573. // - functions
  15574. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  15575. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  15576. DestType = Ptr->getPointeeType();
  15577. ExprResult Result = resolveDecl(E, VD);
  15578. if (Result.isInvalid()) return ExprError();
  15579. return S.ImpCastExprToType(Result.get(), Type,
  15580. CK_FunctionToPointerDecay, VK_RValue);
  15581. }
  15582. if (!Type->isFunctionType()) {
  15583. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  15584. << VD << E->getSourceRange();
  15585. return ExprError();
  15586. }
  15587. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  15588. // We must match the FunctionDecl's type to the hack introduced in
  15589. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  15590. // type. See the lengthy commentary in that routine.
  15591. QualType FDT = FD->getType();
  15592. const FunctionType *FnType = FDT->castAs<FunctionType>();
  15593. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  15594. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  15595. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  15596. SourceLocation Loc = FD->getLocation();
  15597. FunctionDecl *NewFD = FunctionDecl::Create(
  15598. S.Context, FD->getDeclContext(), Loc, Loc,
  15599. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  15600. SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
  15601. /*ConstexprKind*/ CSK_unspecified);
  15602. if (FD->getQualifier())
  15603. NewFD->setQualifierInfo(FD->getQualifierLoc());
  15604. SmallVector<ParmVarDecl*, 16> Params;
  15605. for (const auto &AI : FT->param_types()) {
  15606. ParmVarDecl *Param =
  15607. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  15608. Param->setScopeInfo(0, Params.size());
  15609. Params.push_back(Param);
  15610. }
  15611. NewFD->setParams(Params);
  15612. DRE->setDecl(NewFD);
  15613. VD = DRE->getDecl();
  15614. }
  15615. }
  15616. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  15617. if (MD->isInstance()) {
  15618. ValueKind = VK_RValue;
  15619. Type = S.Context.BoundMemberTy;
  15620. }
  15621. // Function references aren't l-values in C.
  15622. if (!S.getLangOpts().CPlusPlus)
  15623. ValueKind = VK_RValue;
  15624. // - variables
  15625. } else if (isa<VarDecl>(VD)) {
  15626. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  15627. Type = RefTy->getPointeeType();
  15628. } else if (Type->isFunctionType()) {
  15629. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  15630. << VD << E->getSourceRange();
  15631. return ExprError();
  15632. }
  15633. // - nothing else
  15634. } else {
  15635. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  15636. << VD << E->getSourceRange();
  15637. return ExprError();
  15638. }
  15639. // Modifying the declaration like this is friendly to IR-gen but
  15640. // also really dangerous.
  15641. VD->setType(DestType);
  15642. E->setType(Type);
  15643. E->setValueKind(ValueKind);
  15644. return E;
  15645. }
  15646. /// Check a cast of an unknown-any type. We intentionally only
  15647. /// trigger this for C-style casts.
  15648. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  15649. Expr *CastExpr, CastKind &CastKind,
  15650. ExprValueKind &VK, CXXCastPath &Path) {
  15651. // The type we're casting to must be either void or complete.
  15652. if (!CastType->isVoidType() &&
  15653. RequireCompleteType(TypeRange.getBegin(), CastType,
  15654. diag::err_typecheck_cast_to_incomplete))
  15655. return ExprError();
  15656. // Rewrite the casted expression from scratch.
  15657. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  15658. if (!result.isUsable()) return ExprError();
  15659. CastExpr = result.get();
  15660. VK = CastExpr->getValueKind();
  15661. CastKind = CK_NoOp;
  15662. return CastExpr;
  15663. }
  15664. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  15665. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  15666. }
  15667. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  15668. Expr *arg, QualType &paramType) {
  15669. // If the syntactic form of the argument is not an explicit cast of
  15670. // any sort, just do default argument promotion.
  15671. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  15672. if (!castArg) {
  15673. ExprResult result = DefaultArgumentPromotion(arg);
  15674. if (result.isInvalid()) return ExprError();
  15675. paramType = result.get()->getType();
  15676. return result;
  15677. }
  15678. // Otherwise, use the type that was written in the explicit cast.
  15679. assert(!arg->hasPlaceholderType());
  15680. paramType = castArg->getTypeAsWritten();
  15681. // Copy-initialize a parameter of that type.
  15682. InitializedEntity entity =
  15683. InitializedEntity::InitializeParameter(Context, paramType,
  15684. /*consumed*/ false);
  15685. return PerformCopyInitialization(entity, callLoc, arg);
  15686. }
  15687. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  15688. Expr *orig = E;
  15689. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  15690. while (true) {
  15691. E = E->IgnoreParenImpCasts();
  15692. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  15693. E = call->getCallee();
  15694. diagID = diag::err_uncasted_call_of_unknown_any;
  15695. } else {
  15696. break;
  15697. }
  15698. }
  15699. SourceLocation loc;
  15700. NamedDecl *d;
  15701. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  15702. loc = ref->getLocation();
  15703. d = ref->getDecl();
  15704. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  15705. loc = mem->getMemberLoc();
  15706. d = mem->getMemberDecl();
  15707. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  15708. diagID = diag::err_uncasted_call_of_unknown_any;
  15709. loc = msg->getSelectorStartLoc();
  15710. d = msg->getMethodDecl();
  15711. if (!d) {
  15712. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  15713. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  15714. << orig->getSourceRange();
  15715. return ExprError();
  15716. }
  15717. } else {
  15718. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15719. << E->getSourceRange();
  15720. return ExprError();
  15721. }
  15722. S.Diag(loc, diagID) << d << orig->getSourceRange();
  15723. // Never recoverable.
  15724. return ExprError();
  15725. }
  15726. /// Check for operands with placeholder types and complain if found.
  15727. /// Returns ExprError() if there was an error and no recovery was possible.
  15728. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  15729. if (!getLangOpts().CPlusPlus) {
  15730. // C cannot handle TypoExpr nodes on either side of a binop because it
  15731. // doesn't handle dependent types properly, so make sure any TypoExprs have
  15732. // been dealt with before checking the operands.
  15733. ExprResult Result = CorrectDelayedTyposInExpr(E);
  15734. if (!Result.isUsable()) return ExprError();
  15735. E = Result.get();
  15736. }
  15737. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  15738. if (!placeholderType) return E;
  15739. switch (placeholderType->getKind()) {
  15740. // Overloaded expressions.
  15741. case BuiltinType::Overload: {
  15742. // Try to resolve a single function template specialization.
  15743. // This is obligatory.
  15744. ExprResult Result = E;
  15745. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  15746. return Result;
  15747. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  15748. // leaves Result unchanged on failure.
  15749. Result = E;
  15750. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  15751. return Result;
  15752. // If that failed, try to recover with a call.
  15753. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  15754. /*complain*/ true);
  15755. return Result;
  15756. }
  15757. // Bound member functions.
  15758. case BuiltinType::BoundMember: {
  15759. ExprResult result = E;
  15760. const Expr *BME = E->IgnoreParens();
  15761. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  15762. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  15763. if (isa<CXXPseudoDestructorExpr>(BME)) {
  15764. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  15765. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  15766. if (ME->getMemberNameInfo().getName().getNameKind() ==
  15767. DeclarationName::CXXDestructorName)
  15768. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  15769. }
  15770. tryToRecoverWithCall(result, PD,
  15771. /*complain*/ true);
  15772. return result;
  15773. }
  15774. // ARC unbridged casts.
  15775. case BuiltinType::ARCUnbridgedCast: {
  15776. Expr *realCast = stripARCUnbridgedCast(E);
  15777. diagnoseARCUnbridgedCast(realCast);
  15778. return realCast;
  15779. }
  15780. // Expressions of unknown type.
  15781. case BuiltinType::UnknownAny:
  15782. return diagnoseUnknownAnyExpr(*this, E);
  15783. // Pseudo-objects.
  15784. case BuiltinType::PseudoObject:
  15785. return checkPseudoObjectRValue(E);
  15786. case BuiltinType::BuiltinFn: {
  15787. // Accept __noop without parens by implicitly converting it to a call expr.
  15788. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  15789. if (DRE) {
  15790. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  15791. if (FD->getBuiltinID() == Builtin::BI__noop) {
  15792. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  15793. CK_BuiltinFnToFnPtr)
  15794. .get();
  15795. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  15796. VK_RValue, SourceLocation());
  15797. }
  15798. }
  15799. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  15800. return ExprError();
  15801. }
  15802. // Expressions of unknown type.
  15803. case BuiltinType::OMPArraySection:
  15804. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15805. return ExprError();
  15806. // Everything else should be impossible.
  15807. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15808. case BuiltinType::Id:
  15809. #include "clang/Basic/OpenCLImageTypes.def"
  15810. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15811. case BuiltinType::Id:
  15812. #include "clang/Basic/OpenCLExtensionTypes.def"
  15813. #define SVE_TYPE(Name, Id, SingletonId) \
  15814. case BuiltinType::Id:
  15815. #include "clang/Basic/AArch64SVEACLETypes.def"
  15816. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15817. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15818. #include "clang/AST/BuiltinTypes.def"
  15819. break;
  15820. }
  15821. llvm_unreachable("invalid placeholder type!");
  15822. }
  15823. bool Sema::CheckCaseExpression(Expr *E) {
  15824. if (E->isTypeDependent())
  15825. return true;
  15826. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15827. return E->getType()->isIntegralOrEnumerationType();
  15828. return false;
  15829. }
  15830. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15831. ExprResult
  15832. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15833. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15834. "Unknown Objective-C Boolean value!");
  15835. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15836. if (!Context.getBOOLDecl()) {
  15837. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15838. Sema::LookupOrdinaryName);
  15839. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15840. NamedDecl *ND = Result.getFoundDecl();
  15841. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15842. Context.setBOOLDecl(TD);
  15843. }
  15844. }
  15845. if (Context.getBOOLDecl())
  15846. BoolT = Context.getBOOLType();
  15847. return new (Context)
  15848. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15849. }
  15850. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15851. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15852. SourceLocation RParen) {
  15853. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15854. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15855. return Spec.getPlatform() == Platform;
  15856. });
  15857. VersionTuple Version;
  15858. if (Spec != AvailSpecs.end())
  15859. Version = Spec->getVersion();
  15860. // The use of `@available` in the enclosing function should be analyzed to
  15861. // warn when it's used inappropriately (i.e. not if(@available)).
  15862. if (getCurFunctionOrMethodDecl())
  15863. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15864. else if (getCurBlock() || getCurLambda())
  15865. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15866. return new (Context)
  15867. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15868. }