SemaExpr.cpp 681 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610
  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. // In Microsoft mode, if we are performing lookup from within a friend
  1754. // function definition declared at class scope then we must set
  1755. // DC to the lexical parent to be able to search into the parent
  1756. // class.
  1757. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1758. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1759. DC->getLexicalParent()->isRecord())
  1760. DC = DC->getLexicalParent();
  1761. else
  1762. DC = DC->getParent();
  1763. }
  1764. // We didn't find anything, so try to correct for a typo.
  1765. TypoCorrection Corrected;
  1766. if (S && Out) {
  1767. SourceLocation TypoLoc = R.getNameLoc();
  1768. assert(!ExplicitTemplateArgs &&
  1769. "Diagnosing an empty lookup with explicit template args!");
  1770. *Out = CorrectTypoDelayed(
  1771. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1772. [=](const TypoCorrection &TC) {
  1773. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1774. diagnostic, diagnostic_suggest);
  1775. },
  1776. nullptr, CTK_ErrorRecovery);
  1777. if (*Out)
  1778. return true;
  1779. } else if (S &&
  1780. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1781. S, &SS, CCC, CTK_ErrorRecovery))) {
  1782. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1783. bool DroppedSpecifier =
  1784. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1785. R.setLookupName(Corrected.getCorrection());
  1786. bool AcceptableWithRecovery = false;
  1787. bool AcceptableWithoutRecovery = false;
  1788. NamedDecl *ND = Corrected.getFoundDecl();
  1789. if (ND) {
  1790. if (Corrected.isOverloaded()) {
  1791. OverloadCandidateSet OCS(R.getNameLoc(),
  1792. OverloadCandidateSet::CSK_Normal);
  1793. OverloadCandidateSet::iterator Best;
  1794. for (NamedDecl *CD : Corrected) {
  1795. if (FunctionTemplateDecl *FTD =
  1796. dyn_cast<FunctionTemplateDecl>(CD))
  1797. AddTemplateOverloadCandidate(
  1798. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1799. Args, OCS);
  1800. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1801. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1802. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1803. Args, OCS);
  1804. }
  1805. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1806. case OR_Success:
  1807. ND = Best->FoundDecl;
  1808. Corrected.setCorrectionDecl(ND);
  1809. break;
  1810. default:
  1811. // FIXME: Arbitrarily pick the first declaration for the note.
  1812. Corrected.setCorrectionDecl(ND);
  1813. break;
  1814. }
  1815. }
  1816. R.addDecl(ND);
  1817. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1818. CXXRecordDecl *Record = nullptr;
  1819. if (Corrected.getCorrectionSpecifier()) {
  1820. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1821. Record = Ty->getAsCXXRecordDecl();
  1822. }
  1823. if (!Record)
  1824. Record = cast<CXXRecordDecl>(
  1825. ND->getDeclContext()->getRedeclContext());
  1826. R.setNamingClass(Record);
  1827. }
  1828. auto *UnderlyingND = ND->getUnderlyingDecl();
  1829. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1830. isa<FunctionTemplateDecl>(UnderlyingND);
  1831. // FIXME: If we ended up with a typo for a type name or
  1832. // Objective-C class name, we're in trouble because the parser
  1833. // is in the wrong place to recover. Suggest the typo
  1834. // correction, but don't make it a fix-it since we're not going
  1835. // to recover well anyway.
  1836. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  1837. getAsTypeTemplateDecl(UnderlyingND) ||
  1838. isa<ObjCInterfaceDecl>(UnderlyingND);
  1839. } else {
  1840. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1841. // because we aren't able to recover.
  1842. AcceptableWithoutRecovery = true;
  1843. }
  1844. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1845. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1846. ? diag::note_implicit_param_decl
  1847. : diag::note_previous_decl;
  1848. if (SS.isEmpty())
  1849. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1850. PDiag(NoteID), AcceptableWithRecovery);
  1851. else
  1852. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1853. << Name << computeDeclContext(SS, false)
  1854. << DroppedSpecifier << SS.getRange(),
  1855. PDiag(NoteID), AcceptableWithRecovery);
  1856. // Tell the callee whether to try to recover.
  1857. return !AcceptableWithRecovery;
  1858. }
  1859. }
  1860. R.clear();
  1861. // Emit a special diagnostic for failed member lookups.
  1862. // FIXME: computing the declaration context might fail here (?)
  1863. if (!SS.isEmpty()) {
  1864. Diag(R.getNameLoc(), diag::err_no_member)
  1865. << Name << computeDeclContext(SS, false)
  1866. << SS.getRange();
  1867. return true;
  1868. }
  1869. // Give up, we can't recover.
  1870. Diag(R.getNameLoc(), diagnostic) << Name;
  1871. return true;
  1872. }
  1873. /// In Microsoft mode, if we are inside a template class whose parent class has
  1874. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1875. /// assume the identifier is a member of a dependent base class. We can only
  1876. /// recover successfully in static methods, instance methods, and other contexts
  1877. /// where 'this' is available. This doesn't precisely match MSVC's
  1878. /// instantiation model, but it's close enough.
  1879. static Expr *
  1880. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1881. DeclarationNameInfo &NameInfo,
  1882. SourceLocation TemplateKWLoc,
  1883. const TemplateArgumentListInfo *TemplateArgs) {
  1884. // Only try to recover from lookup into dependent bases in static methods or
  1885. // contexts where 'this' is available.
  1886. QualType ThisType = S.getCurrentThisType();
  1887. const CXXRecordDecl *RD = nullptr;
  1888. if (!ThisType.isNull())
  1889. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1890. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1891. RD = MD->getParent();
  1892. if (!RD || !RD->hasAnyDependentBases())
  1893. return nullptr;
  1894. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1895. // is available, suggest inserting 'this->' as a fixit.
  1896. SourceLocation Loc = NameInfo.getLoc();
  1897. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1898. DB << NameInfo.getName() << RD;
  1899. if (!ThisType.isNull()) {
  1900. DB << FixItHint::CreateInsertion(Loc, "this->");
  1901. return CXXDependentScopeMemberExpr::Create(
  1902. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1903. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1904. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  1905. }
  1906. // Synthesize a fake NNS that points to the derived class. This will
  1907. // perform name lookup during template instantiation.
  1908. CXXScopeSpec SS;
  1909. auto *NNS =
  1910. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1911. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1912. return DependentScopeDeclRefExpr::Create(
  1913. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1914. TemplateArgs);
  1915. }
  1916. ExprResult
  1917. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1918. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1919. bool HasTrailingLParen, bool IsAddressOfOperand,
  1920. CorrectionCandidateCallback *CCC,
  1921. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1922. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1923. "cannot be direct & operand and have a trailing lparen");
  1924. if (SS.isInvalid())
  1925. return ExprError();
  1926. TemplateArgumentListInfo TemplateArgsBuffer;
  1927. // Decompose the UnqualifiedId into the following data.
  1928. DeclarationNameInfo NameInfo;
  1929. const TemplateArgumentListInfo *TemplateArgs;
  1930. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1931. DeclarationName Name = NameInfo.getName();
  1932. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1933. SourceLocation NameLoc = NameInfo.getLoc();
  1934. if (II && II->isEditorPlaceholder()) {
  1935. // FIXME: When typed placeholders are supported we can create a typed
  1936. // placeholder expression node.
  1937. return ExprError();
  1938. }
  1939. // C++ [temp.dep.expr]p3:
  1940. // An id-expression is type-dependent if it contains:
  1941. // -- an identifier that was declared with a dependent type,
  1942. // (note: handled after lookup)
  1943. // -- a template-id that is dependent,
  1944. // (note: handled in BuildTemplateIdExpr)
  1945. // -- a conversion-function-id that specifies a dependent type,
  1946. // -- a nested-name-specifier that contains a class-name that
  1947. // names a dependent type.
  1948. // Determine whether this is a member of an unknown specialization;
  1949. // we need to handle these differently.
  1950. bool DependentID = false;
  1951. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1952. Name.getCXXNameType()->isDependentType()) {
  1953. DependentID = true;
  1954. } else if (SS.isSet()) {
  1955. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1956. if (RequireCompleteDeclContext(SS, DC))
  1957. return ExprError();
  1958. } else {
  1959. DependentID = true;
  1960. }
  1961. }
  1962. if (DependentID)
  1963. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1964. IsAddressOfOperand, TemplateArgs);
  1965. // Perform the required lookup.
  1966. LookupResult R(*this, NameInfo,
  1967. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1968. ? LookupObjCImplicitSelfParam
  1969. : LookupOrdinaryName);
  1970. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1971. // Lookup the template name again to correctly establish the context in
  1972. // which it was found. This is really unfortunate as we already did the
  1973. // lookup to determine that it was a template name in the first place. If
  1974. // this becomes a performance hit, we can work harder to preserve those
  1975. // results until we get here but it's likely not worth it.
  1976. bool MemberOfUnknownSpecialization;
  1977. AssumedTemplateKind AssumedTemplate;
  1978. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1979. MemberOfUnknownSpecialization, TemplateKWLoc,
  1980. &AssumedTemplate))
  1981. return ExprError();
  1982. if (MemberOfUnknownSpecialization ||
  1983. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1984. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1985. IsAddressOfOperand, TemplateArgs);
  1986. } else {
  1987. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1988. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1989. // If the result might be in a dependent base class, this is a dependent
  1990. // id-expression.
  1991. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1992. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1993. IsAddressOfOperand, TemplateArgs);
  1994. // If this reference is in an Objective-C method, then we need to do
  1995. // some special Objective-C lookup, too.
  1996. if (IvarLookupFollowUp) {
  1997. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1998. if (E.isInvalid())
  1999. return ExprError();
  2000. if (Expr *Ex = E.getAs<Expr>())
  2001. return Ex;
  2002. }
  2003. }
  2004. if (R.isAmbiguous())
  2005. return ExprError();
  2006. // This could be an implicitly declared function reference (legal in C90,
  2007. // extension in C99, forbidden in C++).
  2008. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  2009. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2010. if (D) R.addDecl(D);
  2011. }
  2012. // Determine whether this name might be a candidate for
  2013. // argument-dependent lookup.
  2014. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2015. if (R.empty() && !ADL) {
  2016. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2017. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2018. TemplateKWLoc, TemplateArgs))
  2019. return E;
  2020. }
  2021. // Don't diagnose an empty lookup for inline assembly.
  2022. if (IsInlineAsmIdentifier)
  2023. return ExprError();
  2024. // If this name wasn't predeclared and if this is not a function
  2025. // call, diagnose the problem.
  2026. TypoExpr *TE = nullptr;
  2027. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2028. : nullptr);
  2029. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2030. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2031. "Typo correction callback misconfigured");
  2032. if (CCC) {
  2033. // Make sure the callback knows what the typo being diagnosed is.
  2034. CCC->setTypoName(II);
  2035. if (SS.isValid())
  2036. CCC->setTypoNNS(SS.getScopeRep());
  2037. }
  2038. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2039. // a template name, but we happen to have always already looked up the name
  2040. // before we get here if it must be a template name.
  2041. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2042. None, &TE)) {
  2043. if (TE && KeywordReplacement) {
  2044. auto &State = getTypoExprState(TE);
  2045. auto BestTC = State.Consumer->getNextCorrection();
  2046. if (BestTC.isKeyword()) {
  2047. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2048. if (State.DiagHandler)
  2049. State.DiagHandler(BestTC);
  2050. KeywordReplacement->startToken();
  2051. KeywordReplacement->setKind(II->getTokenID());
  2052. KeywordReplacement->setIdentifierInfo(II);
  2053. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2054. // Clean up the state associated with the TypoExpr, since it has
  2055. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2056. clearDelayedTypo(TE);
  2057. // Signal that a correction to a keyword was performed by returning a
  2058. // valid-but-null ExprResult.
  2059. return (Expr*)nullptr;
  2060. }
  2061. State.Consumer->resetCorrectionStream();
  2062. }
  2063. return TE ? TE : ExprError();
  2064. }
  2065. assert(!R.empty() &&
  2066. "DiagnoseEmptyLookup returned false but added no results");
  2067. // If we found an Objective-C instance variable, let
  2068. // LookupInObjCMethod build the appropriate expression to
  2069. // reference the ivar.
  2070. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2071. R.clear();
  2072. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2073. // In a hopelessly buggy code, Objective-C instance variable
  2074. // lookup fails and no expression will be built to reference it.
  2075. if (!E.isInvalid() && !E.get())
  2076. return ExprError();
  2077. return E;
  2078. }
  2079. }
  2080. // This is guaranteed from this point on.
  2081. assert(!R.empty() || ADL);
  2082. // Check whether this might be a C++ implicit instance member access.
  2083. // C++ [class.mfct.non-static]p3:
  2084. // When an id-expression that is not part of a class member access
  2085. // syntax and not used to form a pointer to member is used in the
  2086. // body of a non-static member function of class X, if name lookup
  2087. // resolves the name in the id-expression to a non-static non-type
  2088. // member of some class C, the id-expression is transformed into a
  2089. // class member access expression using (*this) as the
  2090. // postfix-expression to the left of the . operator.
  2091. //
  2092. // But we don't actually need to do this for '&' operands if R
  2093. // resolved to a function or overloaded function set, because the
  2094. // expression is ill-formed if it actually works out to be a
  2095. // non-static member function:
  2096. //
  2097. // C++ [expr.ref]p4:
  2098. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2099. // [t]he expression can be used only as the left-hand operand of a
  2100. // member function call.
  2101. //
  2102. // There are other safeguards against such uses, but it's important
  2103. // to get this right here so that we don't end up making a
  2104. // spuriously dependent expression if we're inside a dependent
  2105. // instance method.
  2106. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2107. bool MightBeImplicitMember;
  2108. if (!IsAddressOfOperand)
  2109. MightBeImplicitMember = true;
  2110. else if (!SS.isEmpty())
  2111. MightBeImplicitMember = false;
  2112. else if (R.isOverloadedResult())
  2113. MightBeImplicitMember = false;
  2114. else if (R.isUnresolvableResult())
  2115. MightBeImplicitMember = true;
  2116. else
  2117. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2118. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2119. isa<MSPropertyDecl>(R.getFoundDecl());
  2120. if (MightBeImplicitMember)
  2121. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2122. R, TemplateArgs, S);
  2123. }
  2124. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2125. // In C++1y, if this is a variable template id, then check it
  2126. // in BuildTemplateIdExpr().
  2127. // The single lookup result must be a variable template declaration.
  2128. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2129. Id.TemplateId->Kind == TNK_Var_template) {
  2130. assert(R.getAsSingle<VarTemplateDecl>() &&
  2131. "There should only be one declaration found.");
  2132. }
  2133. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2134. }
  2135. return BuildDeclarationNameExpr(SS, R, ADL);
  2136. }
  2137. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2138. /// declaration name, generally during template instantiation.
  2139. /// There's a large number of things which don't need to be done along
  2140. /// this path.
  2141. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2142. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2143. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2144. DeclContext *DC = computeDeclContext(SS, false);
  2145. if (!DC)
  2146. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2147. NameInfo, /*TemplateArgs=*/nullptr);
  2148. if (RequireCompleteDeclContext(SS, DC))
  2149. return ExprError();
  2150. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2151. LookupQualifiedName(R, DC);
  2152. if (R.isAmbiguous())
  2153. return ExprError();
  2154. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2155. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2156. NameInfo, /*TemplateArgs=*/nullptr);
  2157. if (R.empty()) {
  2158. Diag(NameInfo.getLoc(), diag::err_no_member)
  2159. << NameInfo.getName() << DC << SS.getRange();
  2160. return ExprError();
  2161. }
  2162. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2163. // Diagnose a missing typename if this resolved unambiguously to a type in
  2164. // a dependent context. If we can recover with a type, downgrade this to
  2165. // a warning in Microsoft compatibility mode.
  2166. unsigned DiagID = diag::err_typename_missing;
  2167. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2168. DiagID = diag::ext_typename_missing;
  2169. SourceLocation Loc = SS.getBeginLoc();
  2170. auto D = Diag(Loc, DiagID);
  2171. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2172. << SourceRange(Loc, NameInfo.getEndLoc());
  2173. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2174. // context.
  2175. if (!RecoveryTSI)
  2176. return ExprError();
  2177. // Only issue the fixit if we're prepared to recover.
  2178. D << FixItHint::CreateInsertion(Loc, "typename ");
  2179. // Recover by pretending this was an elaborated type.
  2180. QualType Ty = Context.getTypeDeclType(TD);
  2181. TypeLocBuilder TLB;
  2182. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2183. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2184. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2185. QTL.setElaboratedKeywordLoc(SourceLocation());
  2186. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2187. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2188. return ExprEmpty();
  2189. }
  2190. // Defend against this resolving to an implicit member access. We usually
  2191. // won't get here if this might be a legitimate a class member (we end up in
  2192. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2193. // a pointer-to-member or in an unevaluated context in C++11.
  2194. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2195. return BuildPossibleImplicitMemberExpr(SS,
  2196. /*TemplateKWLoc=*/SourceLocation(),
  2197. R, /*TemplateArgs=*/nullptr, S);
  2198. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2199. }
  2200. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2201. /// detected that we're currently inside an ObjC method. Perform some
  2202. /// additional lookup.
  2203. ///
  2204. /// Ideally, most of this would be done by lookup, but there's
  2205. /// actually quite a lot of extra work involved.
  2206. ///
  2207. /// Returns a null sentinel to indicate trivial success.
  2208. ExprResult
  2209. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2210. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2211. SourceLocation Loc = Lookup.getNameLoc();
  2212. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2213. // Check for error condition which is already reported.
  2214. if (!CurMethod)
  2215. return ExprError();
  2216. // There are two cases to handle here. 1) scoped lookup could have failed,
  2217. // in which case we should look for an ivar. 2) scoped lookup could have
  2218. // found a decl, but that decl is outside the current instance method (i.e.
  2219. // a global variable). In these two cases, we do a lookup for an ivar with
  2220. // this name, if the lookup sucedes, we replace it our current decl.
  2221. // If we're in a class method, we don't normally want to look for
  2222. // ivars. But if we don't find anything else, and there's an
  2223. // ivar, that's an error.
  2224. bool IsClassMethod = CurMethod->isClassMethod();
  2225. bool LookForIvars;
  2226. if (Lookup.empty())
  2227. LookForIvars = true;
  2228. else if (IsClassMethod)
  2229. LookForIvars = false;
  2230. else
  2231. LookForIvars = (Lookup.isSingleResult() &&
  2232. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2233. ObjCInterfaceDecl *IFace = nullptr;
  2234. if (LookForIvars) {
  2235. IFace = CurMethod->getClassInterface();
  2236. ObjCInterfaceDecl *ClassDeclared;
  2237. ObjCIvarDecl *IV = nullptr;
  2238. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2239. // Diagnose using an ivar in a class method.
  2240. if (IsClassMethod)
  2241. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2242. << IV->getDeclName());
  2243. // If we're referencing an invalid decl, just return this as a silent
  2244. // error node. The error diagnostic was already emitted on the decl.
  2245. if (IV->isInvalidDecl())
  2246. return ExprError();
  2247. // Check if referencing a field with __attribute__((deprecated)).
  2248. if (DiagnoseUseOfDecl(IV, Loc))
  2249. return ExprError();
  2250. // Diagnose the use of an ivar outside of the declaring class.
  2251. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2252. !declaresSameEntity(ClassDeclared, IFace) &&
  2253. !getLangOpts().DebuggerSupport)
  2254. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2255. // FIXME: This should use a new expr for a direct reference, don't
  2256. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2257. IdentifierInfo &II = Context.Idents.get("self");
  2258. UnqualifiedId SelfName;
  2259. SelfName.setIdentifier(&II, SourceLocation());
  2260. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2261. CXXScopeSpec SelfScopeSpec;
  2262. SourceLocation TemplateKWLoc;
  2263. ExprResult SelfExpr =
  2264. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2265. /*HasTrailingLParen=*/false,
  2266. /*IsAddressOfOperand=*/false);
  2267. if (SelfExpr.isInvalid())
  2268. return ExprError();
  2269. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2270. if (SelfExpr.isInvalid())
  2271. return ExprError();
  2272. MarkAnyDeclReferenced(Loc, IV, true);
  2273. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2274. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2275. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2276. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2277. ObjCIvarRefExpr *Result = new (Context)
  2278. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2279. IV->getLocation(), SelfExpr.get(), true, true);
  2280. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2281. if (!isUnevaluatedContext() &&
  2282. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2283. getCurFunction()->recordUseOfWeak(Result);
  2284. }
  2285. if (getLangOpts().ObjCAutoRefCount)
  2286. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2287. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2288. return Result;
  2289. }
  2290. } else if (CurMethod->isInstanceMethod()) {
  2291. // We should warn if a local variable hides an ivar.
  2292. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2293. ObjCInterfaceDecl *ClassDeclared;
  2294. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2295. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2296. declaresSameEntity(IFace, ClassDeclared))
  2297. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2298. }
  2299. }
  2300. } else if (Lookup.isSingleResult() &&
  2301. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2302. // If accessing a stand-alone ivar in a class method, this is an error.
  2303. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2304. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2305. << IV->getDeclName());
  2306. }
  2307. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2308. // FIXME. Consolidate this with similar code in LookupName.
  2309. if (unsigned BuiltinID = II->getBuiltinID()) {
  2310. if (!(getLangOpts().CPlusPlus &&
  2311. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2312. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2313. S, Lookup.isForRedeclaration(),
  2314. Lookup.getNameLoc());
  2315. if (D) Lookup.addDecl(D);
  2316. }
  2317. }
  2318. }
  2319. // Sentinel value saying that we didn't do anything special.
  2320. return ExprResult((Expr *)nullptr);
  2321. }
  2322. /// Cast a base object to a member's actual type.
  2323. ///
  2324. /// Logically this happens in three phases:
  2325. ///
  2326. /// * First we cast from the base type to the naming class.
  2327. /// The naming class is the class into which we were looking
  2328. /// when we found the member; it's the qualifier type if a
  2329. /// qualifier was provided, and otherwise it's the base type.
  2330. ///
  2331. /// * Next we cast from the naming class to the declaring class.
  2332. /// If the member we found was brought into a class's scope by
  2333. /// a using declaration, this is that class; otherwise it's
  2334. /// the class declaring the member.
  2335. ///
  2336. /// * Finally we cast from the declaring class to the "true"
  2337. /// declaring class of the member. This conversion does not
  2338. /// obey access control.
  2339. ExprResult
  2340. Sema::PerformObjectMemberConversion(Expr *From,
  2341. NestedNameSpecifier *Qualifier,
  2342. NamedDecl *FoundDecl,
  2343. NamedDecl *Member) {
  2344. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2345. if (!RD)
  2346. return From;
  2347. QualType DestRecordType;
  2348. QualType DestType;
  2349. QualType FromRecordType;
  2350. QualType FromType = From->getType();
  2351. bool PointerConversions = false;
  2352. if (isa<FieldDecl>(Member)) {
  2353. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2354. auto FromPtrType = FromType->getAs<PointerType>();
  2355. DestRecordType = Context.getAddrSpaceQualType(
  2356. DestRecordType, FromPtrType
  2357. ? FromType->getPointeeType().getAddressSpace()
  2358. : FromType.getAddressSpace());
  2359. if (FromPtrType) {
  2360. DestType = Context.getPointerType(DestRecordType);
  2361. FromRecordType = FromPtrType->getPointeeType();
  2362. PointerConversions = true;
  2363. } else {
  2364. DestType = DestRecordType;
  2365. FromRecordType = FromType;
  2366. }
  2367. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2368. if (Method->isStatic())
  2369. return From;
  2370. DestType = Method->getThisType();
  2371. DestRecordType = DestType->getPointeeType();
  2372. if (FromType->getAs<PointerType>()) {
  2373. FromRecordType = FromType->getPointeeType();
  2374. PointerConversions = true;
  2375. } else {
  2376. FromRecordType = FromType;
  2377. DestType = DestRecordType;
  2378. }
  2379. } else {
  2380. // No conversion necessary.
  2381. return From;
  2382. }
  2383. if (DestType->isDependentType() || FromType->isDependentType())
  2384. return From;
  2385. // If the unqualified types are the same, no conversion is necessary.
  2386. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2387. return From;
  2388. SourceRange FromRange = From->getSourceRange();
  2389. SourceLocation FromLoc = FromRange.getBegin();
  2390. ExprValueKind VK = From->getValueKind();
  2391. // C++ [class.member.lookup]p8:
  2392. // [...] Ambiguities can often be resolved by qualifying a name with its
  2393. // class name.
  2394. //
  2395. // If the member was a qualified name and the qualified referred to a
  2396. // specific base subobject type, we'll cast to that intermediate type
  2397. // first and then to the object in which the member is declared. That allows
  2398. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2399. //
  2400. // class Base { public: int x; };
  2401. // class Derived1 : public Base { };
  2402. // class Derived2 : public Base { };
  2403. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2404. //
  2405. // void VeryDerived::f() {
  2406. // x = 17; // error: ambiguous base subobjects
  2407. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2408. // }
  2409. if (Qualifier && Qualifier->getAsType()) {
  2410. QualType QType = QualType(Qualifier->getAsType(), 0);
  2411. assert(QType->isRecordType() && "lookup done with non-record type");
  2412. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2413. // In C++98, the qualifier type doesn't actually have to be a base
  2414. // type of the object type, in which case we just ignore it.
  2415. // Otherwise build the appropriate casts.
  2416. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2417. CXXCastPath BasePath;
  2418. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2419. FromLoc, FromRange, &BasePath))
  2420. return ExprError();
  2421. if (PointerConversions)
  2422. QType = Context.getPointerType(QType);
  2423. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2424. VK, &BasePath).get();
  2425. FromType = QType;
  2426. FromRecordType = QRecordType;
  2427. // If the qualifier type was the same as the destination type,
  2428. // we're done.
  2429. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2430. return From;
  2431. }
  2432. }
  2433. bool IgnoreAccess = false;
  2434. // If we actually found the member through a using declaration, cast
  2435. // down to the using declaration's type.
  2436. //
  2437. // Pointer equality is fine here because only one declaration of a
  2438. // class ever has member declarations.
  2439. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2440. assert(isa<UsingShadowDecl>(FoundDecl));
  2441. QualType URecordType = Context.getTypeDeclType(
  2442. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2443. // We only need to do this if the naming-class to declaring-class
  2444. // conversion is non-trivial.
  2445. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2446. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2447. CXXCastPath BasePath;
  2448. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2449. FromLoc, FromRange, &BasePath))
  2450. return ExprError();
  2451. QualType UType = URecordType;
  2452. if (PointerConversions)
  2453. UType = Context.getPointerType(UType);
  2454. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2455. VK, &BasePath).get();
  2456. FromType = UType;
  2457. FromRecordType = URecordType;
  2458. }
  2459. // We don't do access control for the conversion from the
  2460. // declaring class to the true declaring class.
  2461. IgnoreAccess = true;
  2462. }
  2463. CXXCastPath BasePath;
  2464. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2465. FromLoc, FromRange, &BasePath,
  2466. IgnoreAccess))
  2467. return ExprError();
  2468. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2469. VK, &BasePath);
  2470. }
  2471. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2472. const LookupResult &R,
  2473. bool HasTrailingLParen) {
  2474. // Only when used directly as the postfix-expression of a call.
  2475. if (!HasTrailingLParen)
  2476. return false;
  2477. // Never if a scope specifier was provided.
  2478. if (SS.isSet())
  2479. return false;
  2480. // Only in C++ or ObjC++.
  2481. if (!getLangOpts().CPlusPlus)
  2482. return false;
  2483. // Turn off ADL when we find certain kinds of declarations during
  2484. // normal lookup:
  2485. for (NamedDecl *D : R) {
  2486. // C++0x [basic.lookup.argdep]p3:
  2487. // -- a declaration of a class member
  2488. // Since using decls preserve this property, we check this on the
  2489. // original decl.
  2490. if (D->isCXXClassMember())
  2491. return false;
  2492. // C++0x [basic.lookup.argdep]p3:
  2493. // -- a block-scope function declaration that is not a
  2494. // using-declaration
  2495. // NOTE: we also trigger this for function templates (in fact, we
  2496. // don't check the decl type at all, since all other decl types
  2497. // turn off ADL anyway).
  2498. if (isa<UsingShadowDecl>(D))
  2499. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2500. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2501. return false;
  2502. // C++0x [basic.lookup.argdep]p3:
  2503. // -- a declaration that is neither a function or a function
  2504. // template
  2505. // And also for builtin functions.
  2506. if (isa<FunctionDecl>(D)) {
  2507. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2508. // But also builtin functions.
  2509. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2510. return false;
  2511. } else if (!isa<FunctionTemplateDecl>(D))
  2512. return false;
  2513. }
  2514. return true;
  2515. }
  2516. /// Diagnoses obvious problems with the use of the given declaration
  2517. /// as an expression. This is only actually called for lookups that
  2518. /// were not overloaded, and it doesn't promise that the declaration
  2519. /// will in fact be used.
  2520. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2521. if (D->isInvalidDecl())
  2522. return true;
  2523. if (isa<TypedefNameDecl>(D)) {
  2524. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2525. return true;
  2526. }
  2527. if (isa<ObjCInterfaceDecl>(D)) {
  2528. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2529. return true;
  2530. }
  2531. if (isa<NamespaceDecl>(D)) {
  2532. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2533. return true;
  2534. }
  2535. return false;
  2536. }
  2537. // Certain multiversion types should be treated as overloaded even when there is
  2538. // only one result.
  2539. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2540. assert(R.isSingleResult() && "Expected only a single result");
  2541. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2542. return FD &&
  2543. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2544. }
  2545. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2546. LookupResult &R, bool NeedsADL,
  2547. bool AcceptInvalidDecl) {
  2548. // If this is a single, fully-resolved result and we don't need ADL,
  2549. // just build an ordinary singleton decl ref.
  2550. if (!NeedsADL && R.isSingleResult() &&
  2551. !R.getAsSingle<FunctionTemplateDecl>() &&
  2552. !ShouldLookupResultBeMultiVersionOverload(R))
  2553. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2554. R.getRepresentativeDecl(), nullptr,
  2555. AcceptInvalidDecl);
  2556. // We only need to check the declaration if there's exactly one
  2557. // result, because in the overloaded case the results can only be
  2558. // functions and function templates.
  2559. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2560. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2561. return ExprError();
  2562. // Otherwise, just build an unresolved lookup expression. Suppress
  2563. // any lookup-related diagnostics; we'll hash these out later, when
  2564. // we've picked a target.
  2565. R.suppressDiagnostics();
  2566. UnresolvedLookupExpr *ULE
  2567. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2568. SS.getWithLocInContext(Context),
  2569. R.getLookupNameInfo(),
  2570. NeedsADL, R.isOverloadedResult(),
  2571. R.begin(), R.end());
  2572. return ULE;
  2573. }
  2574. static void
  2575. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2576. ValueDecl *var, DeclContext *DC);
  2577. /// Complete semantic analysis for a reference to the given declaration.
  2578. ExprResult Sema::BuildDeclarationNameExpr(
  2579. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2580. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2581. bool AcceptInvalidDecl) {
  2582. assert(D && "Cannot refer to a NULL declaration");
  2583. assert(!isa<FunctionTemplateDecl>(D) &&
  2584. "Cannot refer unambiguously to a function template");
  2585. SourceLocation Loc = NameInfo.getLoc();
  2586. if (CheckDeclInExpr(*this, Loc, D))
  2587. return ExprError();
  2588. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2589. // Specifically diagnose references to class templates that are missing
  2590. // a template argument list.
  2591. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2592. return ExprError();
  2593. }
  2594. // Make sure that we're referring to a value.
  2595. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2596. if (!VD) {
  2597. Diag(Loc, diag::err_ref_non_value)
  2598. << D << SS.getRange();
  2599. Diag(D->getLocation(), diag::note_declared_at);
  2600. return ExprError();
  2601. }
  2602. // Check whether this declaration can be used. Note that we suppress
  2603. // this check when we're going to perform argument-dependent lookup
  2604. // on this function name, because this might not be the function
  2605. // that overload resolution actually selects.
  2606. if (DiagnoseUseOfDecl(VD, Loc))
  2607. return ExprError();
  2608. // Only create DeclRefExpr's for valid Decl's.
  2609. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2610. return ExprError();
  2611. // Handle members of anonymous structs and unions. If we got here,
  2612. // and the reference is to a class member indirect field, then this
  2613. // must be the subject of a pointer-to-member expression.
  2614. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2615. if (!indirectField->isCXXClassMember())
  2616. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2617. indirectField);
  2618. {
  2619. QualType type = VD->getType();
  2620. if (type.isNull())
  2621. return ExprError();
  2622. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2623. // C++ [except.spec]p17:
  2624. // An exception-specification is considered to be needed when:
  2625. // - in an expression, the function is the unique lookup result or
  2626. // the selected member of a set of overloaded functions.
  2627. ResolveExceptionSpec(Loc, FPT);
  2628. type = VD->getType();
  2629. }
  2630. ExprValueKind valueKind = VK_RValue;
  2631. switch (D->getKind()) {
  2632. // Ignore all the non-ValueDecl kinds.
  2633. #define ABSTRACT_DECL(kind)
  2634. #define VALUE(type, base)
  2635. #define DECL(type, base) \
  2636. case Decl::type:
  2637. #include "clang/AST/DeclNodes.inc"
  2638. llvm_unreachable("invalid value decl kind");
  2639. // These shouldn't make it here.
  2640. case Decl::ObjCAtDefsField:
  2641. llvm_unreachable("forming non-member reference to ivar?");
  2642. // Enum constants are always r-values and never references.
  2643. // Unresolved using declarations are dependent.
  2644. case Decl::EnumConstant:
  2645. case Decl::UnresolvedUsingValue:
  2646. case Decl::OMPDeclareReduction:
  2647. case Decl::OMPDeclareMapper:
  2648. valueKind = VK_RValue;
  2649. break;
  2650. // Fields and indirect fields that got here must be for
  2651. // pointer-to-member expressions; we just call them l-values for
  2652. // internal consistency, because this subexpression doesn't really
  2653. // exist in the high-level semantics.
  2654. case Decl::Field:
  2655. case Decl::IndirectField:
  2656. case Decl::ObjCIvar:
  2657. assert(getLangOpts().CPlusPlus &&
  2658. "building reference to field in C?");
  2659. // These can't have reference type in well-formed programs, but
  2660. // for internal consistency we do this anyway.
  2661. type = type.getNonReferenceType();
  2662. valueKind = VK_LValue;
  2663. break;
  2664. // Non-type template parameters are either l-values or r-values
  2665. // depending on the type.
  2666. case Decl::NonTypeTemplateParm: {
  2667. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2668. type = reftype->getPointeeType();
  2669. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2670. break;
  2671. }
  2672. // For non-references, we need to strip qualifiers just in case
  2673. // the template parameter was declared as 'const int' or whatever.
  2674. valueKind = VK_RValue;
  2675. type = type.getUnqualifiedType();
  2676. break;
  2677. }
  2678. case Decl::Var:
  2679. case Decl::VarTemplateSpecialization:
  2680. case Decl::VarTemplatePartialSpecialization:
  2681. case Decl::Decomposition:
  2682. case Decl::OMPCapturedExpr:
  2683. // In C, "extern void blah;" is valid and is an r-value.
  2684. if (!getLangOpts().CPlusPlus &&
  2685. !type.hasQualifiers() &&
  2686. type->isVoidType()) {
  2687. valueKind = VK_RValue;
  2688. break;
  2689. }
  2690. LLVM_FALLTHROUGH;
  2691. case Decl::ImplicitParam:
  2692. case Decl::ParmVar: {
  2693. // These are always l-values.
  2694. valueKind = VK_LValue;
  2695. type = type.getNonReferenceType();
  2696. // FIXME: Does the addition of const really only apply in
  2697. // potentially-evaluated contexts? Since the variable isn't actually
  2698. // captured in an unevaluated context, it seems that the answer is no.
  2699. if (!isUnevaluatedContext()) {
  2700. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2701. if (!CapturedType.isNull())
  2702. type = CapturedType;
  2703. }
  2704. break;
  2705. }
  2706. case Decl::Binding: {
  2707. // These are always lvalues.
  2708. valueKind = VK_LValue;
  2709. type = type.getNonReferenceType();
  2710. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2711. // decides how that's supposed to work.
  2712. auto *BD = cast<BindingDecl>(VD);
  2713. if (BD->getDeclContext() != CurContext) {
  2714. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2715. if (DD && DD->hasLocalStorage())
  2716. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2717. }
  2718. break;
  2719. }
  2720. case Decl::Function: {
  2721. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2722. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2723. type = Context.BuiltinFnTy;
  2724. valueKind = VK_RValue;
  2725. break;
  2726. }
  2727. }
  2728. const FunctionType *fty = type->castAs<FunctionType>();
  2729. // If we're referring to a function with an __unknown_anytype
  2730. // result type, make the entire expression __unknown_anytype.
  2731. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2732. type = Context.UnknownAnyTy;
  2733. valueKind = VK_RValue;
  2734. break;
  2735. }
  2736. // Functions are l-values in C++.
  2737. if (getLangOpts().CPlusPlus) {
  2738. valueKind = VK_LValue;
  2739. break;
  2740. }
  2741. // C99 DR 316 says that, if a function type comes from a
  2742. // function definition (without a prototype), that type is only
  2743. // used for checking compatibility. Therefore, when referencing
  2744. // the function, we pretend that we don't have the full function
  2745. // type.
  2746. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2747. isa<FunctionProtoType>(fty))
  2748. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2749. fty->getExtInfo());
  2750. // Functions are r-values in C.
  2751. valueKind = VK_RValue;
  2752. break;
  2753. }
  2754. case Decl::CXXDeductionGuide:
  2755. llvm_unreachable("building reference to deduction guide");
  2756. case Decl::MSProperty:
  2757. valueKind = VK_LValue;
  2758. break;
  2759. case Decl::CXXMethod:
  2760. // If we're referring to a method with an __unknown_anytype
  2761. // result type, make the entire expression __unknown_anytype.
  2762. // This should only be possible with a type written directly.
  2763. if (const FunctionProtoType *proto
  2764. = dyn_cast<FunctionProtoType>(VD->getType()))
  2765. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2766. type = Context.UnknownAnyTy;
  2767. valueKind = VK_RValue;
  2768. break;
  2769. }
  2770. // C++ methods are l-values if static, r-values if non-static.
  2771. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2772. valueKind = VK_LValue;
  2773. break;
  2774. }
  2775. LLVM_FALLTHROUGH;
  2776. case Decl::CXXConversion:
  2777. case Decl::CXXDestructor:
  2778. case Decl::CXXConstructor:
  2779. valueKind = VK_RValue;
  2780. break;
  2781. }
  2782. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2783. /*FIXME: TemplateKWLoc*/ SourceLocation(),
  2784. TemplateArgs);
  2785. }
  2786. }
  2787. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2788. SmallString<32> &Target) {
  2789. Target.resize(CharByteWidth * (Source.size() + 1));
  2790. char *ResultPtr = &Target[0];
  2791. const llvm::UTF8 *ErrorPtr;
  2792. bool success =
  2793. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2794. (void)success;
  2795. assert(success);
  2796. Target.resize(ResultPtr - &Target[0]);
  2797. }
  2798. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2799. PredefinedExpr::IdentKind IK) {
  2800. // Pick the current block, lambda, captured statement or function.
  2801. Decl *currentDecl = nullptr;
  2802. if (const BlockScopeInfo *BSI = getCurBlock())
  2803. currentDecl = BSI->TheDecl;
  2804. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2805. currentDecl = LSI->CallOperator;
  2806. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2807. currentDecl = CSI->TheCapturedDecl;
  2808. else
  2809. currentDecl = getCurFunctionOrMethodDecl();
  2810. if (!currentDecl) {
  2811. Diag(Loc, diag::ext_predef_outside_function);
  2812. currentDecl = Context.getTranslationUnitDecl();
  2813. }
  2814. QualType ResTy;
  2815. StringLiteral *SL = nullptr;
  2816. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2817. ResTy = Context.DependentTy;
  2818. else {
  2819. // Pre-defined identifiers are of type char[x], where x is the length of
  2820. // the string.
  2821. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2822. unsigned Length = Str.length();
  2823. llvm::APInt LengthI(32, Length + 1);
  2824. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2825. ResTy =
  2826. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2827. SmallString<32> RawChars;
  2828. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2829. Str, RawChars);
  2830. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2831. /*IndexTypeQuals*/ 0);
  2832. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2833. /*Pascal*/ false, ResTy, Loc);
  2834. } else {
  2835. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2836. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2837. /*IndexTypeQuals*/ 0);
  2838. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2839. /*Pascal*/ false, ResTy, Loc);
  2840. }
  2841. }
  2842. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2843. }
  2844. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2845. PredefinedExpr::IdentKind IK;
  2846. switch (Kind) {
  2847. default: llvm_unreachable("Unknown simple primary expr!");
  2848. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2849. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2850. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2851. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2852. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2853. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2854. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2855. }
  2856. return BuildPredefinedExpr(Loc, IK);
  2857. }
  2858. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2859. SmallString<16> CharBuffer;
  2860. bool Invalid = false;
  2861. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2862. if (Invalid)
  2863. return ExprError();
  2864. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2865. PP, Tok.getKind());
  2866. if (Literal.hadError())
  2867. return ExprError();
  2868. QualType Ty;
  2869. if (Literal.isWide())
  2870. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2871. else if (Literal.isUTF8() && getLangOpts().Char8)
  2872. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2873. else if (Literal.isUTF16())
  2874. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2875. else if (Literal.isUTF32())
  2876. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2877. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2878. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2879. else
  2880. Ty = Context.CharTy; // 'x' -> char in C++
  2881. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2882. if (Literal.isWide())
  2883. Kind = CharacterLiteral::Wide;
  2884. else if (Literal.isUTF16())
  2885. Kind = CharacterLiteral::UTF16;
  2886. else if (Literal.isUTF32())
  2887. Kind = CharacterLiteral::UTF32;
  2888. else if (Literal.isUTF8())
  2889. Kind = CharacterLiteral::UTF8;
  2890. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2891. Tok.getLocation());
  2892. if (Literal.getUDSuffix().empty())
  2893. return Lit;
  2894. // We're building a user-defined literal.
  2895. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2896. SourceLocation UDSuffixLoc =
  2897. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2898. // Make sure we're allowed user-defined literals here.
  2899. if (!UDLScope)
  2900. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2901. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2902. // operator "" X (ch)
  2903. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2904. Lit, Tok.getLocation());
  2905. }
  2906. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2907. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2908. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2909. Context.IntTy, Loc);
  2910. }
  2911. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2912. QualType Ty, SourceLocation Loc) {
  2913. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2914. using llvm::APFloat;
  2915. APFloat Val(Format);
  2916. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2917. // Overflow is always an error, but underflow is only an error if
  2918. // we underflowed to zero (APFloat reports denormals as underflow).
  2919. if ((result & APFloat::opOverflow) ||
  2920. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2921. unsigned diagnostic;
  2922. SmallString<20> buffer;
  2923. if (result & APFloat::opOverflow) {
  2924. diagnostic = diag::warn_float_overflow;
  2925. APFloat::getLargest(Format).toString(buffer);
  2926. } else {
  2927. diagnostic = diag::warn_float_underflow;
  2928. APFloat::getSmallest(Format).toString(buffer);
  2929. }
  2930. S.Diag(Loc, diagnostic)
  2931. << Ty
  2932. << StringRef(buffer.data(), buffer.size());
  2933. }
  2934. bool isExact = (result == APFloat::opOK);
  2935. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2936. }
  2937. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2938. assert(E && "Invalid expression");
  2939. if (E->isValueDependent())
  2940. return false;
  2941. QualType QT = E->getType();
  2942. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2943. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2944. return true;
  2945. }
  2946. llvm::APSInt ValueAPS;
  2947. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2948. if (R.isInvalid())
  2949. return true;
  2950. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2951. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2952. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2953. << ValueAPS.toString(10) << ValueIsPositive;
  2954. return true;
  2955. }
  2956. return false;
  2957. }
  2958. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2959. // Fast path for a single digit (which is quite common). A single digit
  2960. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2961. if (Tok.getLength() == 1) {
  2962. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2963. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2964. }
  2965. SmallString<128> SpellingBuffer;
  2966. // NumericLiteralParser wants to overread by one character. Add padding to
  2967. // the buffer in case the token is copied to the buffer. If getSpelling()
  2968. // returns a StringRef to the memory buffer, it should have a null char at
  2969. // the EOF, so it is also safe.
  2970. SpellingBuffer.resize(Tok.getLength() + 1);
  2971. // Get the spelling of the token, which eliminates trigraphs, etc.
  2972. bool Invalid = false;
  2973. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2974. if (Invalid)
  2975. return ExprError();
  2976. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2977. if (Literal.hadError)
  2978. return ExprError();
  2979. if (Literal.hasUDSuffix()) {
  2980. // We're building a user-defined literal.
  2981. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2982. SourceLocation UDSuffixLoc =
  2983. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2984. // Make sure we're allowed user-defined literals here.
  2985. if (!UDLScope)
  2986. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2987. QualType CookedTy;
  2988. if (Literal.isFloatingLiteral()) {
  2989. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2990. // long double, the literal is treated as a call of the form
  2991. // operator "" X (f L)
  2992. CookedTy = Context.LongDoubleTy;
  2993. } else {
  2994. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2995. // unsigned long long, the literal is treated as a call of the form
  2996. // operator "" X (n ULL)
  2997. CookedTy = Context.UnsignedLongLongTy;
  2998. }
  2999. DeclarationName OpName =
  3000. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  3001. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  3002. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  3003. SourceLocation TokLoc = Tok.getLocation();
  3004. // Perform literal operator lookup to determine if we're building a raw
  3005. // literal or a cooked one.
  3006. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  3007. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  3008. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3009. /*AllowStringTemplate*/ false,
  3010. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3011. case LOLR_ErrorNoDiagnostic:
  3012. // Lookup failure for imaginary constants isn't fatal, there's still the
  3013. // GNU extension producing _Complex types.
  3014. break;
  3015. case LOLR_Error:
  3016. return ExprError();
  3017. case LOLR_Cooked: {
  3018. Expr *Lit;
  3019. if (Literal.isFloatingLiteral()) {
  3020. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3021. } else {
  3022. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3023. if (Literal.GetIntegerValue(ResultVal))
  3024. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3025. << /* Unsigned */ 1;
  3026. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3027. Tok.getLocation());
  3028. }
  3029. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3030. }
  3031. case LOLR_Raw: {
  3032. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3033. // literal is treated as a call of the form
  3034. // operator "" X ("n")
  3035. unsigned Length = Literal.getUDSuffixOffset();
  3036. QualType StrTy = Context.getConstantArrayType(
  3037. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3038. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  3039. Expr *Lit = StringLiteral::Create(
  3040. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3041. /*Pascal*/false, StrTy, &TokLoc, 1);
  3042. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3043. }
  3044. case LOLR_Template: {
  3045. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3046. // template), L is treated as a call fo the form
  3047. // operator "" X <'c1', 'c2', ... 'ck'>()
  3048. // where n is the source character sequence c1 c2 ... ck.
  3049. TemplateArgumentListInfo ExplicitArgs;
  3050. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3051. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3052. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3053. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3054. Value = TokSpelling[I];
  3055. TemplateArgument Arg(Context, Value, Context.CharTy);
  3056. TemplateArgumentLocInfo ArgInfo;
  3057. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3058. }
  3059. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3060. &ExplicitArgs);
  3061. }
  3062. case LOLR_StringTemplate:
  3063. llvm_unreachable("unexpected literal operator lookup result");
  3064. }
  3065. }
  3066. Expr *Res;
  3067. if (Literal.isFixedPointLiteral()) {
  3068. QualType Ty;
  3069. if (Literal.isAccum) {
  3070. if (Literal.isHalf) {
  3071. Ty = Context.ShortAccumTy;
  3072. } else if (Literal.isLong) {
  3073. Ty = Context.LongAccumTy;
  3074. } else {
  3075. Ty = Context.AccumTy;
  3076. }
  3077. } else if (Literal.isFract) {
  3078. if (Literal.isHalf) {
  3079. Ty = Context.ShortFractTy;
  3080. } else if (Literal.isLong) {
  3081. Ty = Context.LongFractTy;
  3082. } else {
  3083. Ty = Context.FractTy;
  3084. }
  3085. }
  3086. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3087. bool isSigned = !Literal.isUnsigned;
  3088. unsigned scale = Context.getFixedPointScale(Ty);
  3089. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3090. llvm::APInt Val(bit_width, 0, isSigned);
  3091. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3092. bool ValIsZero = Val.isNullValue() && !Overflowed;
  3093. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3094. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3095. // Clause 6.4.4 - The value of a constant shall be in the range of
  3096. // representable values for its type, with exception for constants of a
  3097. // fract type with a value of exactly 1; such a constant shall denote
  3098. // the maximal value for the type.
  3099. --Val;
  3100. else if (Val.ugt(MaxVal) || Overflowed)
  3101. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3102. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3103. Tok.getLocation(), scale);
  3104. } else if (Literal.isFloatingLiteral()) {
  3105. QualType Ty;
  3106. if (Literal.isHalf){
  3107. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  3108. Ty = Context.HalfTy;
  3109. else {
  3110. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3111. return ExprError();
  3112. }
  3113. } else if (Literal.isFloat)
  3114. Ty = Context.FloatTy;
  3115. else if (Literal.isLong)
  3116. Ty = Context.LongDoubleTy;
  3117. else if (Literal.isFloat16)
  3118. Ty = Context.Float16Ty;
  3119. else if (Literal.isFloat128)
  3120. Ty = Context.Float128Ty;
  3121. else
  3122. Ty = Context.DoubleTy;
  3123. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3124. if (Ty == Context.DoubleTy) {
  3125. if (getLangOpts().SinglePrecisionConstants) {
  3126. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  3127. if (BTy->getKind() != BuiltinType::Float) {
  3128. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3129. }
  3130. } else if (getLangOpts().OpenCL &&
  3131. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  3132. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3133. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3134. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3135. }
  3136. }
  3137. } else if (!Literal.isIntegerLiteral()) {
  3138. return ExprError();
  3139. } else {
  3140. QualType Ty;
  3141. // 'long long' is a C99 or C++11 feature.
  3142. if (!getLangOpts().C99 && Literal.isLongLong) {
  3143. if (getLangOpts().CPlusPlus)
  3144. Diag(Tok.getLocation(),
  3145. getLangOpts().CPlusPlus11 ?
  3146. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3147. else
  3148. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3149. }
  3150. // Get the value in the widest-possible width.
  3151. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3152. llvm::APInt ResultVal(MaxWidth, 0);
  3153. if (Literal.GetIntegerValue(ResultVal)) {
  3154. // If this value didn't fit into uintmax_t, error and force to ull.
  3155. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3156. << /* Unsigned */ 1;
  3157. Ty = Context.UnsignedLongLongTy;
  3158. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3159. "long long is not intmax_t?");
  3160. } else {
  3161. // If this value fits into a ULL, try to figure out what else it fits into
  3162. // according to the rules of C99 6.4.4.1p5.
  3163. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3164. // be an unsigned int.
  3165. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3166. // Check from smallest to largest, picking the smallest type we can.
  3167. unsigned Width = 0;
  3168. // Microsoft specific integer suffixes are explicitly sized.
  3169. if (Literal.MicrosoftInteger) {
  3170. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3171. Width = 8;
  3172. Ty = Context.CharTy;
  3173. } else {
  3174. Width = Literal.MicrosoftInteger;
  3175. Ty = Context.getIntTypeForBitwidth(Width,
  3176. /*Signed=*/!Literal.isUnsigned);
  3177. }
  3178. }
  3179. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3180. // Are int/unsigned possibilities?
  3181. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3182. // Does it fit in a unsigned int?
  3183. if (ResultVal.isIntN(IntSize)) {
  3184. // Does it fit in a signed int?
  3185. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3186. Ty = Context.IntTy;
  3187. else if (AllowUnsigned)
  3188. Ty = Context.UnsignedIntTy;
  3189. Width = IntSize;
  3190. }
  3191. }
  3192. // Are long/unsigned long possibilities?
  3193. if (Ty.isNull() && !Literal.isLongLong) {
  3194. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3195. // Does it fit in a unsigned long?
  3196. if (ResultVal.isIntN(LongSize)) {
  3197. // Does it fit in a signed long?
  3198. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3199. Ty = Context.LongTy;
  3200. else if (AllowUnsigned)
  3201. Ty = Context.UnsignedLongTy;
  3202. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3203. // is compatible.
  3204. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3205. const unsigned LongLongSize =
  3206. Context.getTargetInfo().getLongLongWidth();
  3207. Diag(Tok.getLocation(),
  3208. getLangOpts().CPlusPlus
  3209. ? Literal.isLong
  3210. ? diag::warn_old_implicitly_unsigned_long_cxx
  3211. : /*C++98 UB*/ diag::
  3212. ext_old_implicitly_unsigned_long_cxx
  3213. : diag::warn_old_implicitly_unsigned_long)
  3214. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3215. : /*will be ill-formed*/ 1);
  3216. Ty = Context.UnsignedLongTy;
  3217. }
  3218. Width = LongSize;
  3219. }
  3220. }
  3221. // Check long long if needed.
  3222. if (Ty.isNull()) {
  3223. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3224. // Does it fit in a unsigned long long?
  3225. if (ResultVal.isIntN(LongLongSize)) {
  3226. // Does it fit in a signed long long?
  3227. // To be compatible with MSVC, hex integer literals ending with the
  3228. // LL or i64 suffix are always signed in Microsoft mode.
  3229. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3230. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3231. Ty = Context.LongLongTy;
  3232. else if (AllowUnsigned)
  3233. Ty = Context.UnsignedLongLongTy;
  3234. Width = LongLongSize;
  3235. }
  3236. }
  3237. // If we still couldn't decide a type, we probably have something that
  3238. // does not fit in a signed long long, but has no U suffix.
  3239. if (Ty.isNull()) {
  3240. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3241. Ty = Context.UnsignedLongLongTy;
  3242. Width = Context.getTargetInfo().getLongLongWidth();
  3243. }
  3244. if (ResultVal.getBitWidth() != Width)
  3245. ResultVal = ResultVal.trunc(Width);
  3246. }
  3247. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3248. }
  3249. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3250. if (Literal.isImaginary) {
  3251. Res = new (Context) ImaginaryLiteral(Res,
  3252. Context.getComplexType(Res->getType()));
  3253. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3254. }
  3255. return Res;
  3256. }
  3257. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3258. assert(E && "ActOnParenExpr() missing expr");
  3259. return new (Context) ParenExpr(L, R, E);
  3260. }
  3261. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3262. SourceLocation Loc,
  3263. SourceRange ArgRange) {
  3264. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3265. // scalar or vector data type argument..."
  3266. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3267. // type (C99 6.2.5p18) or void.
  3268. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3269. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3270. << T << ArgRange;
  3271. return true;
  3272. }
  3273. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3274. "Scalar types should always be complete");
  3275. return false;
  3276. }
  3277. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3278. SourceLocation Loc,
  3279. SourceRange ArgRange,
  3280. UnaryExprOrTypeTrait TraitKind) {
  3281. // Invalid types must be hard errors for SFINAE in C++.
  3282. if (S.LangOpts.CPlusPlus)
  3283. return true;
  3284. // C99 6.5.3.4p1:
  3285. if (T->isFunctionType() &&
  3286. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3287. TraitKind == UETT_PreferredAlignOf)) {
  3288. // sizeof(function)/alignof(function) is allowed as an extension.
  3289. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3290. << TraitKind << ArgRange;
  3291. return false;
  3292. }
  3293. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3294. // this is an error (OpenCL v1.1 s6.3.k)
  3295. if (T->isVoidType()) {
  3296. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3297. : diag::ext_sizeof_alignof_void_type;
  3298. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3299. return false;
  3300. }
  3301. return true;
  3302. }
  3303. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3304. SourceLocation Loc,
  3305. SourceRange ArgRange,
  3306. UnaryExprOrTypeTrait TraitKind) {
  3307. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3308. // runtime doesn't allow it.
  3309. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3310. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3311. << T << (TraitKind == UETT_SizeOf)
  3312. << ArgRange;
  3313. return true;
  3314. }
  3315. return false;
  3316. }
  3317. /// Check whether E is a pointer from a decayed array type (the decayed
  3318. /// pointer type is equal to T) and emit a warning if it is.
  3319. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3320. Expr *E) {
  3321. // Don't warn if the operation changed the type.
  3322. if (T != E->getType())
  3323. return;
  3324. // Now look for array decays.
  3325. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3326. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3327. return;
  3328. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3329. << ICE->getType()
  3330. << ICE->getSubExpr()->getType();
  3331. }
  3332. /// Check the constraints on expression operands to unary type expression
  3333. /// and type traits.
  3334. ///
  3335. /// Completes any types necessary and validates the constraints on the operand
  3336. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3337. /// the expression as it completes the type for that expression through template
  3338. /// instantiation, etc.
  3339. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3340. UnaryExprOrTypeTrait ExprKind) {
  3341. QualType ExprTy = E->getType();
  3342. assert(!ExprTy->isReferenceType());
  3343. if (ExprKind == UETT_VecStep)
  3344. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3345. E->getSourceRange());
  3346. // Whitelist some types as extensions
  3347. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3348. E->getSourceRange(), ExprKind))
  3349. return false;
  3350. // 'alignof' applied to an expression only requires the base element type of
  3351. // the expression to be complete. 'sizeof' requires the expression's type to
  3352. // be complete (and will attempt to complete it if it's an array of unknown
  3353. // bound).
  3354. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3355. if (RequireCompleteType(E->getExprLoc(),
  3356. Context.getBaseElementType(E->getType()),
  3357. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3358. E->getSourceRange()))
  3359. return true;
  3360. } else {
  3361. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3362. ExprKind, E->getSourceRange()))
  3363. return true;
  3364. }
  3365. // Completing the expression's type may have changed it.
  3366. ExprTy = E->getType();
  3367. assert(!ExprTy->isReferenceType());
  3368. if (ExprTy->isFunctionType()) {
  3369. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3370. << ExprKind << E->getSourceRange();
  3371. return true;
  3372. }
  3373. // The operand for sizeof and alignof is in an unevaluated expression context,
  3374. // so side effects could result in unintended consequences.
  3375. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3376. ExprKind == UETT_PreferredAlignOf) &&
  3377. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3378. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3379. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3380. E->getSourceRange(), ExprKind))
  3381. return true;
  3382. if (ExprKind == UETT_SizeOf) {
  3383. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3384. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3385. QualType OType = PVD->getOriginalType();
  3386. QualType Type = PVD->getType();
  3387. if (Type->isPointerType() && OType->isArrayType()) {
  3388. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3389. << Type << OType;
  3390. Diag(PVD->getLocation(), diag::note_declared_at);
  3391. }
  3392. }
  3393. }
  3394. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3395. // decays into a pointer and returns an unintended result. This is most
  3396. // likely a typo for "sizeof(array) op x".
  3397. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3398. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3399. BO->getLHS());
  3400. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3401. BO->getRHS());
  3402. }
  3403. }
  3404. return false;
  3405. }
  3406. /// Check the constraints on operands to unary expression and type
  3407. /// traits.
  3408. ///
  3409. /// This will complete any types necessary, and validate the various constraints
  3410. /// on those operands.
  3411. ///
  3412. /// The UsualUnaryConversions() function is *not* called by this routine.
  3413. /// C99 6.3.2.1p[2-4] all state:
  3414. /// Except when it is the operand of the sizeof operator ...
  3415. ///
  3416. /// C++ [expr.sizeof]p4
  3417. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3418. /// standard conversions are not applied to the operand of sizeof.
  3419. ///
  3420. /// This policy is followed for all of the unary trait expressions.
  3421. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3422. SourceLocation OpLoc,
  3423. SourceRange ExprRange,
  3424. UnaryExprOrTypeTrait ExprKind) {
  3425. if (ExprType->isDependentType())
  3426. return false;
  3427. // C++ [expr.sizeof]p2:
  3428. // When applied to a reference or a reference type, the result
  3429. // is the size of the referenced type.
  3430. // C++11 [expr.alignof]p3:
  3431. // When alignof is applied to a reference type, the result
  3432. // shall be the alignment of the referenced type.
  3433. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3434. ExprType = Ref->getPointeeType();
  3435. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3436. // When alignof or _Alignof is applied to an array type, the result
  3437. // is the alignment of the element type.
  3438. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3439. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3440. ExprType = Context.getBaseElementType(ExprType);
  3441. if (ExprKind == UETT_VecStep)
  3442. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3443. // Whitelist some types as extensions
  3444. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3445. ExprKind))
  3446. return false;
  3447. if (RequireCompleteType(OpLoc, ExprType,
  3448. diag::err_sizeof_alignof_incomplete_type,
  3449. ExprKind, ExprRange))
  3450. return true;
  3451. if (ExprType->isFunctionType()) {
  3452. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3453. << ExprKind << ExprRange;
  3454. return true;
  3455. }
  3456. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3457. ExprKind))
  3458. return true;
  3459. return false;
  3460. }
  3461. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3462. E = E->IgnoreParens();
  3463. // Cannot know anything else if the expression is dependent.
  3464. if (E->isTypeDependent())
  3465. return false;
  3466. if (E->getObjectKind() == OK_BitField) {
  3467. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3468. << 1 << E->getSourceRange();
  3469. return true;
  3470. }
  3471. ValueDecl *D = nullptr;
  3472. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3473. D = DRE->getDecl();
  3474. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3475. D = ME->getMemberDecl();
  3476. }
  3477. // If it's a field, require the containing struct to have a
  3478. // complete definition so that we can compute the layout.
  3479. //
  3480. // This can happen in C++11 onwards, either by naming the member
  3481. // in a way that is not transformed into a member access expression
  3482. // (in an unevaluated operand, for instance), or by naming the member
  3483. // in a trailing-return-type.
  3484. //
  3485. // For the record, since __alignof__ on expressions is a GCC
  3486. // extension, GCC seems to permit this but always gives the
  3487. // nonsensical answer 0.
  3488. //
  3489. // We don't really need the layout here --- we could instead just
  3490. // directly check for all the appropriate alignment-lowing
  3491. // attributes --- but that would require duplicating a lot of
  3492. // logic that just isn't worth duplicating for such a marginal
  3493. // use-case.
  3494. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3495. // Fast path this check, since we at least know the record has a
  3496. // definition if we can find a member of it.
  3497. if (!FD->getParent()->isCompleteDefinition()) {
  3498. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3499. << E->getSourceRange();
  3500. return true;
  3501. }
  3502. // Otherwise, if it's a field, and the field doesn't have
  3503. // reference type, then it must have a complete type (or be a
  3504. // flexible array member, which we explicitly want to
  3505. // white-list anyway), which makes the following checks trivial.
  3506. if (!FD->getType()->isReferenceType())
  3507. return false;
  3508. }
  3509. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3510. }
  3511. bool Sema::CheckVecStepExpr(Expr *E) {
  3512. E = E->IgnoreParens();
  3513. // Cannot know anything else if the expression is dependent.
  3514. if (E->isTypeDependent())
  3515. return false;
  3516. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3517. }
  3518. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3519. CapturingScopeInfo *CSI) {
  3520. assert(T->isVariablyModifiedType());
  3521. assert(CSI != nullptr);
  3522. // We're going to walk down into the type and look for VLA expressions.
  3523. do {
  3524. const Type *Ty = T.getTypePtr();
  3525. switch (Ty->getTypeClass()) {
  3526. #define TYPE(Class, Base)
  3527. #define ABSTRACT_TYPE(Class, Base)
  3528. #define NON_CANONICAL_TYPE(Class, Base)
  3529. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3530. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3531. #include "clang/AST/TypeNodes.def"
  3532. T = QualType();
  3533. break;
  3534. // These types are never variably-modified.
  3535. case Type::Builtin:
  3536. case Type::Complex:
  3537. case Type::Vector:
  3538. case Type::ExtVector:
  3539. case Type::Record:
  3540. case Type::Enum:
  3541. case Type::Elaborated:
  3542. case Type::TemplateSpecialization:
  3543. case Type::ObjCObject:
  3544. case Type::ObjCInterface:
  3545. case Type::ObjCObjectPointer:
  3546. case Type::ObjCTypeParam:
  3547. case Type::Pipe:
  3548. llvm_unreachable("type class is never variably-modified!");
  3549. case Type::Adjusted:
  3550. T = cast<AdjustedType>(Ty)->getOriginalType();
  3551. break;
  3552. case Type::Decayed:
  3553. T = cast<DecayedType>(Ty)->getPointeeType();
  3554. break;
  3555. case Type::Pointer:
  3556. T = cast<PointerType>(Ty)->getPointeeType();
  3557. break;
  3558. case Type::BlockPointer:
  3559. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3560. break;
  3561. case Type::LValueReference:
  3562. case Type::RValueReference:
  3563. T = cast<ReferenceType>(Ty)->getPointeeType();
  3564. break;
  3565. case Type::MemberPointer:
  3566. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3567. break;
  3568. case Type::ConstantArray:
  3569. case Type::IncompleteArray:
  3570. // Losing element qualification here is fine.
  3571. T = cast<ArrayType>(Ty)->getElementType();
  3572. break;
  3573. case Type::VariableArray: {
  3574. // Losing element qualification here is fine.
  3575. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3576. // Unknown size indication requires no size computation.
  3577. // Otherwise, evaluate and record it.
  3578. auto Size = VAT->getSizeExpr();
  3579. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3580. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3581. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3582. T = VAT->getElementType();
  3583. break;
  3584. }
  3585. case Type::FunctionProto:
  3586. case Type::FunctionNoProto:
  3587. T = cast<FunctionType>(Ty)->getReturnType();
  3588. break;
  3589. case Type::Paren:
  3590. case Type::TypeOf:
  3591. case Type::UnaryTransform:
  3592. case Type::Attributed:
  3593. case Type::SubstTemplateTypeParm:
  3594. case Type::PackExpansion:
  3595. case Type::MacroQualified:
  3596. // Keep walking after single level desugaring.
  3597. T = T.getSingleStepDesugaredType(Context);
  3598. break;
  3599. case Type::Typedef:
  3600. T = cast<TypedefType>(Ty)->desugar();
  3601. break;
  3602. case Type::Decltype:
  3603. T = cast<DecltypeType>(Ty)->desugar();
  3604. break;
  3605. case Type::Auto:
  3606. case Type::DeducedTemplateSpecialization:
  3607. T = cast<DeducedType>(Ty)->getDeducedType();
  3608. break;
  3609. case Type::TypeOfExpr:
  3610. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3611. break;
  3612. case Type::Atomic:
  3613. T = cast<AtomicType>(Ty)->getValueType();
  3614. break;
  3615. }
  3616. } while (!T.isNull() && T->isVariablyModifiedType());
  3617. }
  3618. /// Build a sizeof or alignof expression given a type operand.
  3619. ExprResult
  3620. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3621. SourceLocation OpLoc,
  3622. UnaryExprOrTypeTrait ExprKind,
  3623. SourceRange R) {
  3624. if (!TInfo)
  3625. return ExprError();
  3626. QualType T = TInfo->getType();
  3627. if (!T->isDependentType() &&
  3628. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3629. return ExprError();
  3630. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3631. if (auto *TT = T->getAs<TypedefType>()) {
  3632. for (auto I = FunctionScopes.rbegin(),
  3633. E = std::prev(FunctionScopes.rend());
  3634. I != E; ++I) {
  3635. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3636. if (CSI == nullptr)
  3637. break;
  3638. DeclContext *DC = nullptr;
  3639. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3640. DC = LSI->CallOperator;
  3641. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3642. DC = CRSI->TheCapturedDecl;
  3643. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3644. DC = BSI->TheDecl;
  3645. if (DC) {
  3646. if (DC->containsDecl(TT->getDecl()))
  3647. break;
  3648. captureVariablyModifiedType(Context, T, CSI);
  3649. }
  3650. }
  3651. }
  3652. }
  3653. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3654. return new (Context) UnaryExprOrTypeTraitExpr(
  3655. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3656. }
  3657. /// Build a sizeof or alignof expression given an expression
  3658. /// operand.
  3659. ExprResult
  3660. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3661. UnaryExprOrTypeTrait ExprKind) {
  3662. ExprResult PE = CheckPlaceholderExpr(E);
  3663. if (PE.isInvalid())
  3664. return ExprError();
  3665. E = PE.get();
  3666. // Verify that the operand is valid.
  3667. bool isInvalid = false;
  3668. if (E->isTypeDependent()) {
  3669. // Delay type-checking for type-dependent expressions.
  3670. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3671. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3672. } else if (ExprKind == UETT_VecStep) {
  3673. isInvalid = CheckVecStepExpr(E);
  3674. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3675. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3676. isInvalid = true;
  3677. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3678. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3679. isInvalid = true;
  3680. } else {
  3681. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3682. }
  3683. if (isInvalid)
  3684. return ExprError();
  3685. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3686. PE = TransformToPotentiallyEvaluated(E);
  3687. if (PE.isInvalid()) return ExprError();
  3688. E = PE.get();
  3689. }
  3690. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3691. return new (Context) UnaryExprOrTypeTraitExpr(
  3692. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3693. }
  3694. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3695. /// expr and the same for @c alignof and @c __alignof
  3696. /// Note that the ArgRange is invalid if isType is false.
  3697. ExprResult
  3698. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3699. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3700. void *TyOrEx, SourceRange ArgRange) {
  3701. // If error parsing type, ignore.
  3702. if (!TyOrEx) return ExprError();
  3703. if (IsType) {
  3704. TypeSourceInfo *TInfo;
  3705. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3706. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3707. }
  3708. Expr *ArgEx = (Expr *)TyOrEx;
  3709. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3710. return Result;
  3711. }
  3712. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3713. bool IsReal) {
  3714. if (V.get()->isTypeDependent())
  3715. return S.Context.DependentTy;
  3716. // _Real and _Imag are only l-values for normal l-values.
  3717. if (V.get()->getObjectKind() != OK_Ordinary) {
  3718. V = S.DefaultLvalueConversion(V.get());
  3719. if (V.isInvalid())
  3720. return QualType();
  3721. }
  3722. // These operators return the element type of a complex type.
  3723. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3724. return CT->getElementType();
  3725. // Otherwise they pass through real integer and floating point types here.
  3726. if (V.get()->getType()->isArithmeticType())
  3727. return V.get()->getType();
  3728. // Test for placeholders.
  3729. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3730. if (PR.isInvalid()) return QualType();
  3731. if (PR.get() != V.get()) {
  3732. V = PR;
  3733. return CheckRealImagOperand(S, V, Loc, IsReal);
  3734. }
  3735. // Reject anything else.
  3736. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3737. << (IsReal ? "__real" : "__imag");
  3738. return QualType();
  3739. }
  3740. ExprResult
  3741. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3742. tok::TokenKind Kind, Expr *Input) {
  3743. UnaryOperatorKind Opc;
  3744. switch (Kind) {
  3745. default: llvm_unreachable("Unknown unary op!");
  3746. case tok::plusplus: Opc = UO_PostInc; break;
  3747. case tok::minusminus: Opc = UO_PostDec; break;
  3748. }
  3749. // Since this might is a postfix expression, get rid of ParenListExprs.
  3750. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3751. if (Result.isInvalid()) return ExprError();
  3752. Input = Result.get();
  3753. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3754. }
  3755. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3756. ///
  3757. /// \return true on error
  3758. static bool checkArithmeticOnObjCPointer(Sema &S,
  3759. SourceLocation opLoc,
  3760. Expr *op) {
  3761. assert(op->getType()->isObjCObjectPointerType());
  3762. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3763. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3764. return false;
  3765. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3766. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3767. << op->getSourceRange();
  3768. return true;
  3769. }
  3770. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3771. auto *BaseNoParens = Base->IgnoreParens();
  3772. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3773. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3774. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3775. }
  3776. ExprResult
  3777. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3778. Expr *idx, SourceLocation rbLoc) {
  3779. if (base && !base->getType().isNull() &&
  3780. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3781. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3782. /*Length=*/nullptr, rbLoc);
  3783. // Since this might be a postfix expression, get rid of ParenListExprs.
  3784. if (isa<ParenListExpr>(base)) {
  3785. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3786. if (result.isInvalid()) return ExprError();
  3787. base = result.get();
  3788. }
  3789. // Handle any non-overload placeholder types in the base and index
  3790. // expressions. We can't handle overloads here because the other
  3791. // operand might be an overloadable type, in which case the overload
  3792. // resolution for the operator overload should get the first crack
  3793. // at the overload.
  3794. bool IsMSPropertySubscript = false;
  3795. if (base->getType()->isNonOverloadPlaceholderType()) {
  3796. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3797. if (!IsMSPropertySubscript) {
  3798. ExprResult result = CheckPlaceholderExpr(base);
  3799. if (result.isInvalid())
  3800. return ExprError();
  3801. base = result.get();
  3802. }
  3803. }
  3804. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3805. ExprResult result = CheckPlaceholderExpr(idx);
  3806. if (result.isInvalid()) return ExprError();
  3807. idx = result.get();
  3808. }
  3809. // Build an unanalyzed expression if either operand is type-dependent.
  3810. if (getLangOpts().CPlusPlus &&
  3811. (base->isTypeDependent() || idx->isTypeDependent())) {
  3812. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3813. VK_LValue, OK_Ordinary, rbLoc);
  3814. }
  3815. // MSDN, property (C++)
  3816. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3817. // This attribute can also be used in the declaration of an empty array in a
  3818. // class or structure definition. For example:
  3819. // __declspec(property(get=GetX, put=PutX)) int x[];
  3820. // The above statement indicates that x[] can be used with one or more array
  3821. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3822. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3823. if (IsMSPropertySubscript) {
  3824. // Build MS property subscript expression if base is MS property reference
  3825. // or MS property subscript.
  3826. return new (Context) MSPropertySubscriptExpr(
  3827. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3828. }
  3829. // Use C++ overloaded-operator rules if either operand has record
  3830. // type. The spec says to do this if either type is *overloadable*,
  3831. // but enum types can't declare subscript operators or conversion
  3832. // operators, so there's nothing interesting for overload resolution
  3833. // to do if there aren't any record types involved.
  3834. //
  3835. // ObjC pointers have their own subscripting logic that is not tied
  3836. // to overload resolution and so should not take this path.
  3837. if (getLangOpts().CPlusPlus &&
  3838. (base->getType()->isRecordType() ||
  3839. (!base->getType()->isObjCObjectPointerType() &&
  3840. idx->getType()->isRecordType()))) {
  3841. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3842. }
  3843. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3844. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  3845. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  3846. return Res;
  3847. }
  3848. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  3849. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3850. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  3851. // For expressions like `&(*s).b`, the base is recorded and what should be
  3852. // checked.
  3853. const MemberExpr *Member = nullptr;
  3854. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  3855. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  3856. LastRecord.PossibleDerefs.erase(StrippedExpr);
  3857. }
  3858. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  3859. QualType ResultTy = E->getType();
  3860. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3861. // Bail if the element is an array since it is not memory access.
  3862. if (isa<ArrayType>(ResultTy))
  3863. return;
  3864. if (ResultTy->hasAttr(attr::NoDeref)) {
  3865. LastRecord.PossibleDerefs.insert(E);
  3866. return;
  3867. }
  3868. // Check if the base type is a pointer to a member access of a struct
  3869. // marked with noderef.
  3870. const Expr *Base = E->getBase();
  3871. QualType BaseTy = Base->getType();
  3872. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  3873. // Not a pointer access
  3874. return;
  3875. const MemberExpr *Member = nullptr;
  3876. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  3877. Member->isArrow())
  3878. Base = Member->getBase();
  3879. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  3880. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  3881. LastRecord.PossibleDerefs.insert(E);
  3882. }
  3883. }
  3884. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3885. Expr *LowerBound,
  3886. SourceLocation ColonLoc, Expr *Length,
  3887. SourceLocation RBLoc) {
  3888. if (Base->getType()->isPlaceholderType() &&
  3889. !Base->getType()->isSpecificPlaceholderType(
  3890. BuiltinType::OMPArraySection)) {
  3891. ExprResult Result = CheckPlaceholderExpr(Base);
  3892. if (Result.isInvalid())
  3893. return ExprError();
  3894. Base = Result.get();
  3895. }
  3896. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3897. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3898. if (Result.isInvalid())
  3899. return ExprError();
  3900. Result = DefaultLvalueConversion(Result.get());
  3901. if (Result.isInvalid())
  3902. return ExprError();
  3903. LowerBound = Result.get();
  3904. }
  3905. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3906. ExprResult Result = CheckPlaceholderExpr(Length);
  3907. if (Result.isInvalid())
  3908. return ExprError();
  3909. Result = DefaultLvalueConversion(Result.get());
  3910. if (Result.isInvalid())
  3911. return ExprError();
  3912. Length = Result.get();
  3913. }
  3914. // Build an unanalyzed expression if either operand is type-dependent.
  3915. if (Base->isTypeDependent() ||
  3916. (LowerBound &&
  3917. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3918. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3919. return new (Context)
  3920. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3921. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3922. }
  3923. // Perform default conversions.
  3924. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3925. QualType ResultTy;
  3926. if (OriginalTy->isAnyPointerType()) {
  3927. ResultTy = OriginalTy->getPointeeType();
  3928. } else if (OriginalTy->isArrayType()) {
  3929. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3930. } else {
  3931. return ExprError(
  3932. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3933. << Base->getSourceRange());
  3934. }
  3935. // C99 6.5.2.1p1
  3936. if (LowerBound) {
  3937. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3938. LowerBound);
  3939. if (Res.isInvalid())
  3940. return ExprError(Diag(LowerBound->getExprLoc(),
  3941. diag::err_omp_typecheck_section_not_integer)
  3942. << 0 << LowerBound->getSourceRange());
  3943. LowerBound = Res.get();
  3944. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3945. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3946. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3947. << 0 << LowerBound->getSourceRange();
  3948. }
  3949. if (Length) {
  3950. auto Res =
  3951. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3952. if (Res.isInvalid())
  3953. return ExprError(Diag(Length->getExprLoc(),
  3954. diag::err_omp_typecheck_section_not_integer)
  3955. << 1 << Length->getSourceRange());
  3956. Length = Res.get();
  3957. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3958. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3959. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3960. << 1 << Length->getSourceRange();
  3961. }
  3962. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3963. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3964. // type. Note that functions are not objects, and that (in C99 parlance)
  3965. // incomplete types are not object types.
  3966. if (ResultTy->isFunctionType()) {
  3967. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3968. << ResultTy << Base->getSourceRange();
  3969. return ExprError();
  3970. }
  3971. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3972. diag::err_omp_section_incomplete_type, Base))
  3973. return ExprError();
  3974. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3975. Expr::EvalResult Result;
  3976. if (LowerBound->EvaluateAsInt(Result, Context)) {
  3977. // OpenMP 4.5, [2.4 Array Sections]
  3978. // The array section must be a subset of the original array.
  3979. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  3980. if (LowerBoundValue.isNegative()) {
  3981. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3982. << LowerBound->getSourceRange();
  3983. return ExprError();
  3984. }
  3985. }
  3986. }
  3987. if (Length) {
  3988. Expr::EvalResult Result;
  3989. if (Length->EvaluateAsInt(Result, Context)) {
  3990. // OpenMP 4.5, [2.4 Array Sections]
  3991. // The length must evaluate to non-negative integers.
  3992. llvm::APSInt LengthValue = Result.Val.getInt();
  3993. if (LengthValue.isNegative()) {
  3994. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3995. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3996. << Length->getSourceRange();
  3997. return ExprError();
  3998. }
  3999. }
  4000. } else if (ColonLoc.isValid() &&
  4001. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4002. !OriginalTy->isVariableArrayType()))) {
  4003. // OpenMP 4.5, [2.4 Array Sections]
  4004. // When the size of the array dimension is not known, the length must be
  4005. // specified explicitly.
  4006. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  4007. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4008. return ExprError();
  4009. }
  4010. if (!Base->getType()->isSpecificPlaceholderType(
  4011. BuiltinType::OMPArraySection)) {
  4012. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4013. if (Result.isInvalid())
  4014. return ExprError();
  4015. Base = Result.get();
  4016. }
  4017. return new (Context)
  4018. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  4019. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  4020. }
  4021. ExprResult
  4022. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4023. Expr *Idx, SourceLocation RLoc) {
  4024. Expr *LHSExp = Base;
  4025. Expr *RHSExp = Idx;
  4026. ExprValueKind VK = VK_LValue;
  4027. ExprObjectKind OK = OK_Ordinary;
  4028. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4029. // a non-lvalue array, and an lvalue otherwise.
  4030. if (getLangOpts().CPlusPlus11) {
  4031. for (auto *Op : {LHSExp, RHSExp}) {
  4032. Op = Op->IgnoreImplicit();
  4033. if (Op->getType()->isArrayType() && !Op->isLValue())
  4034. VK = VK_XValue;
  4035. }
  4036. }
  4037. // Perform default conversions.
  4038. if (!LHSExp->getType()->getAs<VectorType>()) {
  4039. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4040. if (Result.isInvalid())
  4041. return ExprError();
  4042. LHSExp = Result.get();
  4043. }
  4044. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4045. if (Result.isInvalid())
  4046. return ExprError();
  4047. RHSExp = Result.get();
  4048. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4049. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4050. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4051. // in the subscript position. As a result, we need to derive the array base
  4052. // and index from the expression types.
  4053. Expr *BaseExpr, *IndexExpr;
  4054. QualType ResultType;
  4055. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4056. BaseExpr = LHSExp;
  4057. IndexExpr = RHSExp;
  4058. ResultType = Context.DependentTy;
  4059. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4060. BaseExpr = LHSExp;
  4061. IndexExpr = RHSExp;
  4062. ResultType = PTy->getPointeeType();
  4063. } else if (const ObjCObjectPointerType *PTy =
  4064. LHSTy->getAs<ObjCObjectPointerType>()) {
  4065. BaseExpr = LHSExp;
  4066. IndexExpr = RHSExp;
  4067. // Use custom logic if this should be the pseudo-object subscript
  4068. // expression.
  4069. if (!LangOpts.isSubscriptPointerArithmetic())
  4070. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4071. nullptr);
  4072. ResultType = PTy->getPointeeType();
  4073. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4074. // Handle the uncommon case of "123[Ptr]".
  4075. BaseExpr = RHSExp;
  4076. IndexExpr = LHSExp;
  4077. ResultType = PTy->getPointeeType();
  4078. } else if (const ObjCObjectPointerType *PTy =
  4079. RHSTy->getAs<ObjCObjectPointerType>()) {
  4080. // Handle the uncommon case of "123[Ptr]".
  4081. BaseExpr = RHSExp;
  4082. IndexExpr = LHSExp;
  4083. ResultType = PTy->getPointeeType();
  4084. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4085. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4086. << ResultType << BaseExpr->getSourceRange();
  4087. return ExprError();
  4088. }
  4089. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4090. BaseExpr = LHSExp; // vectors: V[123]
  4091. IndexExpr = RHSExp;
  4092. // We apply C++ DR1213 to vector subscripting too.
  4093. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  4094. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4095. if (Materialized.isInvalid())
  4096. return ExprError();
  4097. LHSExp = Materialized.get();
  4098. }
  4099. VK = LHSExp->getValueKind();
  4100. if (VK != VK_RValue)
  4101. OK = OK_VectorComponent;
  4102. ResultType = VTy->getElementType();
  4103. QualType BaseType = BaseExpr->getType();
  4104. Qualifiers BaseQuals = BaseType.getQualifiers();
  4105. Qualifiers MemberQuals = ResultType.getQualifiers();
  4106. Qualifiers Combined = BaseQuals + MemberQuals;
  4107. if (Combined != MemberQuals)
  4108. ResultType = Context.getQualifiedType(ResultType, Combined);
  4109. } else if (LHSTy->isArrayType()) {
  4110. // If we see an array that wasn't promoted by
  4111. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4112. // wasn't promoted because of the C90 rule that doesn't
  4113. // allow promoting non-lvalue arrays. Warn, then
  4114. // force the promotion here.
  4115. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4116. << LHSExp->getSourceRange();
  4117. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4118. CK_ArrayToPointerDecay).get();
  4119. LHSTy = LHSExp->getType();
  4120. BaseExpr = LHSExp;
  4121. IndexExpr = RHSExp;
  4122. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  4123. } else if (RHSTy->isArrayType()) {
  4124. // Same as previous, except for 123[f().a] case
  4125. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4126. << RHSExp->getSourceRange();
  4127. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4128. CK_ArrayToPointerDecay).get();
  4129. RHSTy = RHSExp->getType();
  4130. BaseExpr = RHSExp;
  4131. IndexExpr = LHSExp;
  4132. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  4133. } else {
  4134. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4135. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4136. }
  4137. // C99 6.5.2.1p1
  4138. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4139. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4140. << IndexExpr->getSourceRange());
  4141. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4142. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4143. && !IndexExpr->isTypeDependent())
  4144. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4145. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4146. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4147. // type. Note that Functions are not objects, and that (in C99 parlance)
  4148. // incomplete types are not object types.
  4149. if (ResultType->isFunctionType()) {
  4150. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4151. << ResultType << BaseExpr->getSourceRange();
  4152. return ExprError();
  4153. }
  4154. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  4155. // GNU extension: subscripting on pointer to void
  4156. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4157. << BaseExpr->getSourceRange();
  4158. // C forbids expressions of unqualified void type from being l-values.
  4159. // See IsCForbiddenLValueType.
  4160. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4161. } else if (!ResultType->isDependentType() &&
  4162. RequireCompleteType(LLoc, ResultType,
  4163. diag::err_subscript_incomplete_type, BaseExpr))
  4164. return ExprError();
  4165. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4166. !ResultType.isCForbiddenLValueType());
  4167. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  4168. FunctionScopes.size() > 1) {
  4169. if (auto *TT =
  4170. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  4171. for (auto I = FunctionScopes.rbegin(),
  4172. E = std::prev(FunctionScopes.rend());
  4173. I != E; ++I) {
  4174. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  4175. if (CSI == nullptr)
  4176. break;
  4177. DeclContext *DC = nullptr;
  4178. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  4179. DC = LSI->CallOperator;
  4180. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  4181. DC = CRSI->TheCapturedDecl;
  4182. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  4183. DC = BSI->TheDecl;
  4184. if (DC) {
  4185. if (DC->containsDecl(TT->getDecl()))
  4186. break;
  4187. captureVariablyModifiedType(
  4188. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  4189. }
  4190. }
  4191. }
  4192. }
  4193. return new (Context)
  4194. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4195. }
  4196. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4197. ParmVarDecl *Param) {
  4198. if (Param->hasUnparsedDefaultArg()) {
  4199. Diag(CallLoc,
  4200. diag::err_use_of_default_argument_to_function_declared_later) <<
  4201. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4202. Diag(UnparsedDefaultArgLocs[Param],
  4203. diag::note_default_argument_declared_here);
  4204. return true;
  4205. }
  4206. if (Param->hasUninstantiatedDefaultArg()) {
  4207. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4208. EnterExpressionEvaluationContext EvalContext(
  4209. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4210. // Instantiate the expression.
  4211. //
  4212. // FIXME: Pass in a correct Pattern argument, otherwise
  4213. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4214. //
  4215. // template<typename T>
  4216. // struct A {
  4217. // static int FooImpl();
  4218. //
  4219. // template<typename Tp>
  4220. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4221. // // template argument list [[T], [Tp]], should be [[Tp]].
  4222. // friend A<Tp> Foo(int a);
  4223. // };
  4224. //
  4225. // template<typename T>
  4226. // A<T> Foo(int a = A<T>::FooImpl());
  4227. MultiLevelTemplateArgumentList MutiLevelArgList
  4228. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4229. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4230. MutiLevelArgList.getInnermost());
  4231. if (Inst.isInvalid())
  4232. return true;
  4233. if (Inst.isAlreadyInstantiating()) {
  4234. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4235. Param->setInvalidDecl();
  4236. return true;
  4237. }
  4238. ExprResult Result;
  4239. {
  4240. // C++ [dcl.fct.default]p5:
  4241. // The names in the [default argument] expression are bound, and
  4242. // the semantic constraints are checked, at the point where the
  4243. // default argument expression appears.
  4244. ContextRAII SavedContext(*this, FD);
  4245. LocalInstantiationScope Local(*this);
  4246. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4247. /*DirectInit*/false);
  4248. }
  4249. if (Result.isInvalid())
  4250. return true;
  4251. // Check the expression as an initializer for the parameter.
  4252. InitializedEntity Entity
  4253. = InitializedEntity::InitializeParameter(Context, Param);
  4254. InitializationKind Kind = InitializationKind::CreateCopy(
  4255. Param->getLocation(),
  4256. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4257. Expr *ResultE = Result.getAs<Expr>();
  4258. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4259. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4260. if (Result.isInvalid())
  4261. return true;
  4262. Result =
  4263. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  4264. /*DiscardedValue*/ false);
  4265. if (Result.isInvalid())
  4266. return true;
  4267. // Remember the instantiated default argument.
  4268. Param->setDefaultArg(Result.getAs<Expr>());
  4269. if (ASTMutationListener *L = getASTMutationListener()) {
  4270. L->DefaultArgumentInstantiated(Param);
  4271. }
  4272. }
  4273. // If the default argument expression is not set yet, we are building it now.
  4274. if (!Param->hasInit()) {
  4275. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4276. Param->setInvalidDecl();
  4277. return true;
  4278. }
  4279. // If the default expression creates temporaries, we need to
  4280. // push them to the current stack of expression temporaries so they'll
  4281. // be properly destroyed.
  4282. // FIXME: We should really be rebuilding the default argument with new
  4283. // bound temporaries; see the comment in PR5810.
  4284. // We don't need to do that with block decls, though, because
  4285. // blocks in default argument expression can never capture anything.
  4286. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4287. // Set the "needs cleanups" bit regardless of whether there are
  4288. // any explicit objects.
  4289. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4290. // Append all the objects to the cleanup list. Right now, this
  4291. // should always be a no-op, because blocks in default argument
  4292. // expressions should never be able to capture anything.
  4293. assert(!Init->getNumObjects() &&
  4294. "default argument expression has capturing blocks?");
  4295. }
  4296. // We already type-checked the argument, so we know it works.
  4297. // Just mark all of the declarations in this potentially-evaluated expression
  4298. // as being "referenced".
  4299. EnterExpressionEvaluationContext EvalContext(
  4300. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4301. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4302. /*SkipLocalVariables=*/true);
  4303. return false;
  4304. }
  4305. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4306. FunctionDecl *FD, ParmVarDecl *Param) {
  4307. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4308. return ExprError();
  4309. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  4310. }
  4311. Sema::VariadicCallType
  4312. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4313. Expr *Fn) {
  4314. if (Proto && Proto->isVariadic()) {
  4315. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4316. return VariadicConstructor;
  4317. else if (Fn && Fn->getType()->isBlockPointerType())
  4318. return VariadicBlock;
  4319. else if (FDecl) {
  4320. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4321. if (Method->isInstance())
  4322. return VariadicMethod;
  4323. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4324. return VariadicMethod;
  4325. return VariadicFunction;
  4326. }
  4327. return VariadicDoesNotApply;
  4328. }
  4329. namespace {
  4330. class FunctionCallCCC final : public FunctionCallFilterCCC {
  4331. public:
  4332. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4333. unsigned NumArgs, MemberExpr *ME)
  4334. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4335. FunctionName(FuncName) {}
  4336. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4337. if (!candidate.getCorrectionSpecifier() ||
  4338. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4339. return false;
  4340. }
  4341. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4342. }
  4343. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  4344. return llvm::make_unique<FunctionCallCCC>(*this);
  4345. }
  4346. private:
  4347. const IdentifierInfo *const FunctionName;
  4348. };
  4349. }
  4350. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4351. FunctionDecl *FDecl,
  4352. ArrayRef<Expr *> Args) {
  4353. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4354. DeclarationName FuncName = FDecl->getDeclName();
  4355. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4356. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  4357. if (TypoCorrection Corrected = S.CorrectTypo(
  4358. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4359. S.getScopeForContext(S.CurContext), nullptr, CCC,
  4360. Sema::CTK_ErrorRecovery)) {
  4361. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4362. if (Corrected.isOverloaded()) {
  4363. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4364. OverloadCandidateSet::iterator Best;
  4365. for (NamedDecl *CD : Corrected) {
  4366. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4367. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4368. OCS);
  4369. }
  4370. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4371. case OR_Success:
  4372. ND = Best->FoundDecl;
  4373. Corrected.setCorrectionDecl(ND);
  4374. break;
  4375. default:
  4376. break;
  4377. }
  4378. }
  4379. ND = ND->getUnderlyingDecl();
  4380. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4381. return Corrected;
  4382. }
  4383. }
  4384. return TypoCorrection();
  4385. }
  4386. /// ConvertArgumentsForCall - Converts the arguments specified in
  4387. /// Args/NumArgs to the parameter types of the function FDecl with
  4388. /// function prototype Proto. Call is the call expression itself, and
  4389. /// Fn is the function expression. For a C++ member function, this
  4390. /// routine does not attempt to convert the object argument. Returns
  4391. /// true if the call is ill-formed.
  4392. bool
  4393. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4394. FunctionDecl *FDecl,
  4395. const FunctionProtoType *Proto,
  4396. ArrayRef<Expr *> Args,
  4397. SourceLocation RParenLoc,
  4398. bool IsExecConfig) {
  4399. // Bail out early if calling a builtin with custom typechecking.
  4400. if (FDecl)
  4401. if (unsigned ID = FDecl->getBuiltinID())
  4402. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4403. return false;
  4404. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4405. // assignment, to the types of the corresponding parameter, ...
  4406. unsigned NumParams = Proto->getNumParams();
  4407. bool Invalid = false;
  4408. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4409. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4410. ? 1 /* block */
  4411. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4412. : 0 /* function */);
  4413. // If too few arguments are available (and we don't have default
  4414. // arguments for the remaining parameters), don't make the call.
  4415. if (Args.size() < NumParams) {
  4416. if (Args.size() < MinArgs) {
  4417. TypoCorrection TC;
  4418. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4419. unsigned diag_id =
  4420. MinArgs == NumParams && !Proto->isVariadic()
  4421. ? diag::err_typecheck_call_too_few_args_suggest
  4422. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4423. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4424. << static_cast<unsigned>(Args.size())
  4425. << TC.getCorrectionRange());
  4426. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4427. Diag(RParenLoc,
  4428. MinArgs == NumParams && !Proto->isVariadic()
  4429. ? diag::err_typecheck_call_too_few_args_one
  4430. : diag::err_typecheck_call_too_few_args_at_least_one)
  4431. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4432. else
  4433. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4434. ? diag::err_typecheck_call_too_few_args
  4435. : diag::err_typecheck_call_too_few_args_at_least)
  4436. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4437. << Fn->getSourceRange();
  4438. // Emit the location of the prototype.
  4439. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4440. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4441. return true;
  4442. }
  4443. // We reserve space for the default arguments when we create
  4444. // the call expression, before calling ConvertArgumentsForCall.
  4445. assert((Call->getNumArgs() == NumParams) &&
  4446. "We should have reserved space for the default arguments before!");
  4447. }
  4448. // If too many are passed and not variadic, error on the extras and drop
  4449. // them.
  4450. if (Args.size() > NumParams) {
  4451. if (!Proto->isVariadic()) {
  4452. TypoCorrection TC;
  4453. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4454. unsigned diag_id =
  4455. MinArgs == NumParams && !Proto->isVariadic()
  4456. ? diag::err_typecheck_call_too_many_args_suggest
  4457. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4458. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4459. << static_cast<unsigned>(Args.size())
  4460. << TC.getCorrectionRange());
  4461. } else if (NumParams == 1 && FDecl &&
  4462. FDecl->getParamDecl(0)->getDeclName())
  4463. Diag(Args[NumParams]->getBeginLoc(),
  4464. MinArgs == NumParams
  4465. ? diag::err_typecheck_call_too_many_args_one
  4466. : diag::err_typecheck_call_too_many_args_at_most_one)
  4467. << FnKind << FDecl->getParamDecl(0)
  4468. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4469. << SourceRange(Args[NumParams]->getBeginLoc(),
  4470. Args.back()->getEndLoc());
  4471. else
  4472. Diag(Args[NumParams]->getBeginLoc(),
  4473. MinArgs == NumParams
  4474. ? diag::err_typecheck_call_too_many_args
  4475. : diag::err_typecheck_call_too_many_args_at_most)
  4476. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4477. << Fn->getSourceRange()
  4478. << SourceRange(Args[NumParams]->getBeginLoc(),
  4479. Args.back()->getEndLoc());
  4480. // Emit the location of the prototype.
  4481. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4482. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4483. // This deletes the extra arguments.
  4484. Call->shrinkNumArgs(NumParams);
  4485. return true;
  4486. }
  4487. }
  4488. SmallVector<Expr *, 8> AllArgs;
  4489. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4490. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4491. AllArgs, CallType);
  4492. if (Invalid)
  4493. return true;
  4494. unsigned TotalNumArgs = AllArgs.size();
  4495. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4496. Call->setArg(i, AllArgs[i]);
  4497. return false;
  4498. }
  4499. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4500. const FunctionProtoType *Proto,
  4501. unsigned FirstParam, ArrayRef<Expr *> Args,
  4502. SmallVectorImpl<Expr *> &AllArgs,
  4503. VariadicCallType CallType, bool AllowExplicit,
  4504. bool IsListInitialization) {
  4505. unsigned NumParams = Proto->getNumParams();
  4506. bool Invalid = false;
  4507. size_t ArgIx = 0;
  4508. // Continue to check argument types (even if we have too few/many args).
  4509. for (unsigned i = FirstParam; i < NumParams; i++) {
  4510. QualType ProtoArgType = Proto->getParamType(i);
  4511. Expr *Arg;
  4512. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4513. if (ArgIx < Args.size()) {
  4514. Arg = Args[ArgIx++];
  4515. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4516. diag::err_call_incomplete_argument, Arg))
  4517. return true;
  4518. // Strip the unbridged-cast placeholder expression off, if applicable.
  4519. bool CFAudited = false;
  4520. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4521. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4522. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4523. Arg = stripARCUnbridgedCast(Arg);
  4524. else if (getLangOpts().ObjCAutoRefCount &&
  4525. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4526. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4527. CFAudited = true;
  4528. if (Proto->getExtParameterInfo(i).isNoEscape())
  4529. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4530. BE->getBlockDecl()->setDoesNotEscape();
  4531. InitializedEntity Entity =
  4532. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4533. ProtoArgType)
  4534. : InitializedEntity::InitializeParameter(
  4535. Context, ProtoArgType, Proto->isParamConsumed(i));
  4536. // Remember that parameter belongs to a CF audited API.
  4537. if (CFAudited)
  4538. Entity.setParameterCFAudited();
  4539. ExprResult ArgE = PerformCopyInitialization(
  4540. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4541. if (ArgE.isInvalid())
  4542. return true;
  4543. Arg = ArgE.getAs<Expr>();
  4544. } else {
  4545. assert(Param && "can't use default arguments without a known callee");
  4546. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4547. if (ArgExpr.isInvalid())
  4548. return true;
  4549. Arg = ArgExpr.getAs<Expr>();
  4550. }
  4551. // Check for array bounds violations for each argument to the call. This
  4552. // check only triggers warnings when the argument isn't a more complex Expr
  4553. // with its own checking, such as a BinaryOperator.
  4554. CheckArrayAccess(Arg);
  4555. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4556. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4557. AllArgs.push_back(Arg);
  4558. }
  4559. // If this is a variadic call, handle args passed through "...".
  4560. if (CallType != VariadicDoesNotApply) {
  4561. // Assume that extern "C" functions with variadic arguments that
  4562. // return __unknown_anytype aren't *really* variadic.
  4563. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4564. FDecl->isExternC()) {
  4565. for (Expr *A : Args.slice(ArgIx)) {
  4566. QualType paramType; // ignored
  4567. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4568. Invalid |= arg.isInvalid();
  4569. AllArgs.push_back(arg.get());
  4570. }
  4571. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4572. } else {
  4573. for (Expr *A : Args.slice(ArgIx)) {
  4574. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4575. Invalid |= Arg.isInvalid();
  4576. AllArgs.push_back(Arg.get());
  4577. }
  4578. }
  4579. // Check for array bounds violations.
  4580. for (Expr *A : Args.slice(ArgIx))
  4581. CheckArrayAccess(A);
  4582. }
  4583. return Invalid;
  4584. }
  4585. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4586. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4587. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4588. TL = DTL.getOriginalLoc();
  4589. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4590. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4591. << ATL.getLocalSourceRange();
  4592. }
  4593. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4594. /// array parameter, check that it is non-null, and that if it is formed by
  4595. /// array-to-pointer decay, the underlying array is sufficiently large.
  4596. ///
  4597. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4598. /// array type derivation, then for each call to the function, the value of the
  4599. /// corresponding actual argument shall provide access to the first element of
  4600. /// an array with at least as many elements as specified by the size expression.
  4601. void
  4602. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4603. ParmVarDecl *Param,
  4604. const Expr *ArgExpr) {
  4605. // Static array parameters are not supported in C++.
  4606. if (!Param || getLangOpts().CPlusPlus)
  4607. return;
  4608. QualType OrigTy = Param->getOriginalType();
  4609. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4610. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4611. return;
  4612. if (ArgExpr->isNullPointerConstant(Context,
  4613. Expr::NPC_NeverValueDependent)) {
  4614. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4615. DiagnoseCalleeStaticArrayParam(*this, Param);
  4616. return;
  4617. }
  4618. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4619. if (!CAT)
  4620. return;
  4621. const ConstantArrayType *ArgCAT =
  4622. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  4623. if (!ArgCAT)
  4624. return;
  4625. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  4626. ArgCAT->getElementType())) {
  4627. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4628. Diag(CallLoc, diag::warn_static_array_too_small)
  4629. << ArgExpr->getSourceRange()
  4630. << (unsigned)ArgCAT->getSize().getZExtValue()
  4631. << (unsigned)CAT->getSize().getZExtValue() << 0;
  4632. DiagnoseCalleeStaticArrayParam(*this, Param);
  4633. }
  4634. return;
  4635. }
  4636. Optional<CharUnits> ArgSize =
  4637. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  4638. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  4639. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  4640. Diag(CallLoc, diag::warn_static_array_too_small)
  4641. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  4642. << (unsigned)ParmSize->getQuantity() << 1;
  4643. DiagnoseCalleeStaticArrayParam(*this, Param);
  4644. }
  4645. }
  4646. /// Given a function expression of unknown-any type, try to rebuild it
  4647. /// to have a function type.
  4648. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4649. /// Is the given type a placeholder that we need to lower out
  4650. /// immediately during argument processing?
  4651. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4652. // Placeholders are never sugared.
  4653. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4654. if (!placeholder) return false;
  4655. switch (placeholder->getKind()) {
  4656. // Ignore all the non-placeholder types.
  4657. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4658. case BuiltinType::Id:
  4659. #include "clang/Basic/OpenCLImageTypes.def"
  4660. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4661. case BuiltinType::Id:
  4662. #include "clang/Basic/OpenCLExtensionTypes.def"
  4663. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4664. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4665. #include "clang/AST/BuiltinTypes.def"
  4666. return false;
  4667. // We cannot lower out overload sets; they might validly be resolved
  4668. // by the call machinery.
  4669. case BuiltinType::Overload:
  4670. return false;
  4671. // Unbridged casts in ARC can be handled in some call positions and
  4672. // should be left in place.
  4673. case BuiltinType::ARCUnbridgedCast:
  4674. return false;
  4675. // Pseudo-objects should be converted as soon as possible.
  4676. case BuiltinType::PseudoObject:
  4677. return true;
  4678. // The debugger mode could theoretically but currently does not try
  4679. // to resolve unknown-typed arguments based on known parameter types.
  4680. case BuiltinType::UnknownAny:
  4681. return true;
  4682. // These are always invalid as call arguments and should be reported.
  4683. case BuiltinType::BoundMember:
  4684. case BuiltinType::BuiltinFn:
  4685. case BuiltinType::OMPArraySection:
  4686. return true;
  4687. }
  4688. llvm_unreachable("bad builtin type kind");
  4689. }
  4690. /// Check an argument list for placeholders that we won't try to
  4691. /// handle later.
  4692. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4693. // Apply this processing to all the arguments at once instead of
  4694. // dying at the first failure.
  4695. bool hasInvalid = false;
  4696. for (size_t i = 0, e = args.size(); i != e; i++) {
  4697. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4698. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4699. if (result.isInvalid()) hasInvalid = true;
  4700. else args[i] = result.get();
  4701. } else if (hasInvalid) {
  4702. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4703. }
  4704. }
  4705. return hasInvalid;
  4706. }
  4707. /// If a builtin function has a pointer argument with no explicit address
  4708. /// space, then it should be able to accept a pointer to any address
  4709. /// space as input. In order to do this, we need to replace the
  4710. /// standard builtin declaration with one that uses the same address space
  4711. /// as the call.
  4712. ///
  4713. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4714. /// it does not contain any pointer arguments without
  4715. /// an address space qualifer. Otherwise the rewritten
  4716. /// FunctionDecl is returned.
  4717. /// TODO: Handle pointer return types.
  4718. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4719. FunctionDecl *FDecl,
  4720. MultiExprArg ArgExprs) {
  4721. QualType DeclType = FDecl->getType();
  4722. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4723. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4724. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4725. return nullptr;
  4726. bool NeedsNewDecl = false;
  4727. unsigned i = 0;
  4728. SmallVector<QualType, 8> OverloadParams;
  4729. for (QualType ParamType : FT->param_types()) {
  4730. // Convert array arguments to pointer to simplify type lookup.
  4731. ExprResult ArgRes =
  4732. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4733. if (ArgRes.isInvalid())
  4734. return nullptr;
  4735. Expr *Arg = ArgRes.get();
  4736. QualType ArgType = Arg->getType();
  4737. if (!ParamType->isPointerType() ||
  4738. ParamType.getQualifiers().hasAddressSpace() ||
  4739. !ArgType->isPointerType() ||
  4740. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4741. OverloadParams.push_back(ParamType);
  4742. continue;
  4743. }
  4744. QualType PointeeType = ParamType->getPointeeType();
  4745. if (PointeeType.getQualifiers().hasAddressSpace())
  4746. continue;
  4747. NeedsNewDecl = true;
  4748. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4749. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4750. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4751. }
  4752. if (!NeedsNewDecl)
  4753. return nullptr;
  4754. FunctionProtoType::ExtProtoInfo EPI;
  4755. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4756. OverloadParams, EPI);
  4757. DeclContext *Parent = FDecl->getParent();
  4758. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4759. FDecl->getLocation(),
  4760. FDecl->getLocation(),
  4761. FDecl->getIdentifier(),
  4762. OverloadTy,
  4763. /*TInfo=*/nullptr,
  4764. SC_Extern, false,
  4765. /*hasPrototype=*/true);
  4766. SmallVector<ParmVarDecl*, 16> Params;
  4767. FT = cast<FunctionProtoType>(OverloadTy);
  4768. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4769. QualType ParamType = FT->getParamType(i);
  4770. ParmVarDecl *Parm =
  4771. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4772. SourceLocation(), nullptr, ParamType,
  4773. /*TInfo=*/nullptr, SC_None, nullptr);
  4774. Parm->setScopeInfo(0, i);
  4775. Params.push_back(Parm);
  4776. }
  4777. OverloadDecl->setParams(Params);
  4778. return OverloadDecl;
  4779. }
  4780. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4781. FunctionDecl *Callee,
  4782. MultiExprArg ArgExprs) {
  4783. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4784. // similar attributes) really don't like it when functions are called with an
  4785. // invalid number of args.
  4786. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4787. /*PartialOverloading=*/false) &&
  4788. !Callee->isVariadic())
  4789. return;
  4790. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4791. return;
  4792. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4793. S.Diag(Fn->getBeginLoc(),
  4794. isa<CXXMethodDecl>(Callee)
  4795. ? diag::err_ovl_no_viable_member_function_in_call
  4796. : diag::err_ovl_no_viable_function_in_call)
  4797. << Callee << Callee->getSourceRange();
  4798. S.Diag(Callee->getLocation(),
  4799. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4800. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4801. return;
  4802. }
  4803. }
  4804. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4805. const UnresolvedMemberExpr *const UME, Sema &S) {
  4806. const auto GetFunctionLevelDCIfCXXClass =
  4807. [](Sema &S) -> const CXXRecordDecl * {
  4808. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4809. if (!DC || !DC->getParent())
  4810. return nullptr;
  4811. // If the call to some member function was made from within a member
  4812. // function body 'M' return return 'M's parent.
  4813. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4814. return MD->getParent()->getCanonicalDecl();
  4815. // else the call was made from within a default member initializer of a
  4816. // class, so return the class.
  4817. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4818. return RD->getCanonicalDecl();
  4819. return nullptr;
  4820. };
  4821. // If our DeclContext is neither a member function nor a class (in the
  4822. // case of a lambda in a default member initializer), we can't have an
  4823. // enclosing 'this'.
  4824. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4825. if (!CurParentClass)
  4826. return false;
  4827. // The naming class for implicit member functions call is the class in which
  4828. // name lookup starts.
  4829. const CXXRecordDecl *const NamingClass =
  4830. UME->getNamingClass()->getCanonicalDecl();
  4831. assert(NamingClass && "Must have naming class even for implicit access");
  4832. // If the unresolved member functions were found in a 'naming class' that is
  4833. // related (either the same or derived from) to the class that contains the
  4834. // member function that itself contained the implicit member access.
  4835. return CurParentClass == NamingClass ||
  4836. CurParentClass->isDerivedFrom(NamingClass);
  4837. }
  4838. static void
  4839. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4840. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4841. if (!UME)
  4842. return;
  4843. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4844. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4845. // already been captured, or if this is an implicit member function call (if
  4846. // it isn't, an attempt to capture 'this' should already have been made).
  4847. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4848. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4849. return;
  4850. // Check if the naming class in which the unresolved members were found is
  4851. // related (same as or is a base of) to the enclosing class.
  4852. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4853. return;
  4854. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4855. // If the enclosing function is not dependent, then this lambda is
  4856. // capture ready, so if we can capture this, do so.
  4857. if (!EnclosingFunctionCtx->isDependentContext()) {
  4858. // If the current lambda and all enclosing lambdas can capture 'this' -
  4859. // then go ahead and capture 'this' (since our unresolved overload set
  4860. // contains at least one non-static member function).
  4861. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4862. S.CheckCXXThisCapture(CallLoc);
  4863. } else if (S.CurContext->isDependentContext()) {
  4864. // ... since this is an implicit member reference, that might potentially
  4865. // involve a 'this' capture, mark 'this' for potential capture in
  4866. // enclosing lambdas.
  4867. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4868. CurLSI->addPotentialThisCapture(CallLoc);
  4869. }
  4870. }
  4871. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4872. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4873. Expr *ExecConfig) {
  4874. ExprResult Call =
  4875. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
  4876. if (Call.isInvalid())
  4877. return Call;
  4878. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  4879. // language modes.
  4880. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  4881. if (ULE->hasExplicitTemplateArgs() &&
  4882. ULE->decls_begin() == ULE->decls_end()) {
  4883. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
  4884. ? diag::warn_cxx17_compat_adl_only_template_id
  4885. : diag::ext_adl_only_template_id)
  4886. << ULE->getName();
  4887. }
  4888. }
  4889. return Call;
  4890. }
  4891. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  4892. /// This provides the location of the left/right parens and a list of comma
  4893. /// locations.
  4894. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4895. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4896. Expr *ExecConfig, bool IsExecConfig) {
  4897. // Since this might be a postfix expression, get rid of ParenListExprs.
  4898. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4899. if (Result.isInvalid()) return ExprError();
  4900. Fn = Result.get();
  4901. if (checkArgsForPlaceholders(*this, ArgExprs))
  4902. return ExprError();
  4903. if (getLangOpts().CPlusPlus) {
  4904. // If this is a pseudo-destructor expression, build the call immediately.
  4905. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4906. if (!ArgExprs.empty()) {
  4907. // Pseudo-destructor calls should not have any arguments.
  4908. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4909. << FixItHint::CreateRemoval(
  4910. SourceRange(ArgExprs.front()->getBeginLoc(),
  4911. ArgExprs.back()->getEndLoc()));
  4912. }
  4913. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  4914. VK_RValue, RParenLoc);
  4915. }
  4916. if (Fn->getType() == Context.PseudoObjectTy) {
  4917. ExprResult result = CheckPlaceholderExpr(Fn);
  4918. if (result.isInvalid()) return ExprError();
  4919. Fn = result.get();
  4920. }
  4921. // Determine whether this is a dependent call inside a C++ template,
  4922. // in which case we won't do any semantic analysis now.
  4923. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4924. if (ExecConfig) {
  4925. return CUDAKernelCallExpr::Create(
  4926. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4927. Context.DependentTy, VK_RValue, RParenLoc);
  4928. } else {
  4929. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4930. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4931. Fn->getBeginLoc());
  4932. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4933. VK_RValue, RParenLoc);
  4934. }
  4935. }
  4936. // Determine whether this is a call to an object (C++ [over.call.object]).
  4937. if (Fn->getType()->isRecordType())
  4938. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4939. RParenLoc);
  4940. if (Fn->getType() == Context.UnknownAnyTy) {
  4941. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4942. if (result.isInvalid()) return ExprError();
  4943. Fn = result.get();
  4944. }
  4945. if (Fn->getType() == Context.BoundMemberTy) {
  4946. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4947. RParenLoc);
  4948. }
  4949. }
  4950. // Check for overloaded calls. This can happen even in C due to extensions.
  4951. if (Fn->getType() == Context.OverloadTy) {
  4952. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4953. // We aren't supposed to apply this logic if there's an '&' involved.
  4954. if (!find.HasFormOfMemberPointer) {
  4955. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4956. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4957. VK_RValue, RParenLoc);
  4958. OverloadExpr *ovl = find.Expression;
  4959. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4960. return BuildOverloadedCallExpr(
  4961. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4962. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4963. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4964. RParenLoc);
  4965. }
  4966. }
  4967. // If we're directly calling a function, get the appropriate declaration.
  4968. if (Fn->getType() == Context.UnknownAnyTy) {
  4969. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4970. if (result.isInvalid()) return ExprError();
  4971. Fn = result.get();
  4972. }
  4973. Expr *NakedFn = Fn->IgnoreParens();
  4974. bool CallingNDeclIndirectly = false;
  4975. NamedDecl *NDecl = nullptr;
  4976. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4977. if (UnOp->getOpcode() == UO_AddrOf) {
  4978. CallingNDeclIndirectly = true;
  4979. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4980. }
  4981. }
  4982. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  4983. NDecl = DRE->getDecl();
  4984. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4985. if (FDecl && FDecl->getBuiltinID()) {
  4986. // Rewrite the function decl for this builtin by replacing parameters
  4987. // with no explicit address space with the address space of the arguments
  4988. // in ArgExprs.
  4989. if ((FDecl =
  4990. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4991. NDecl = FDecl;
  4992. Fn = DeclRefExpr::Create(
  4993. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  4994. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  4995. nullptr, DRE->isNonOdrUse());
  4996. }
  4997. }
  4998. } else if (isa<MemberExpr>(NakedFn))
  4999. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  5000. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  5001. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  5002. FD, /*Complain=*/true, Fn->getBeginLoc()))
  5003. return ExprError();
  5004. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  5005. return ExprError();
  5006. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  5007. }
  5008. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  5009. ExecConfig, IsExecConfig);
  5010. }
  5011. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  5012. ///
  5013. /// __builtin_astype( value, dst type )
  5014. ///
  5015. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  5016. SourceLocation BuiltinLoc,
  5017. SourceLocation RParenLoc) {
  5018. ExprValueKind VK = VK_RValue;
  5019. ExprObjectKind OK = OK_Ordinary;
  5020. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  5021. QualType SrcTy = E->getType();
  5022. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  5023. return ExprError(Diag(BuiltinLoc,
  5024. diag::err_invalid_astype_of_different_size)
  5025. << DstTy
  5026. << SrcTy
  5027. << E->getSourceRange());
  5028. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5029. }
  5030. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  5031. /// provided arguments.
  5032. ///
  5033. /// __builtin_convertvector( value, dst type )
  5034. ///
  5035. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  5036. SourceLocation BuiltinLoc,
  5037. SourceLocation RParenLoc) {
  5038. TypeSourceInfo *TInfo;
  5039. GetTypeFromParser(ParsedDestTy, &TInfo);
  5040. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  5041. }
  5042. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  5043. /// i.e. an expression not of \p OverloadTy. The expression should
  5044. /// unary-convert to an expression of function-pointer or
  5045. /// block-pointer type.
  5046. ///
  5047. /// \param NDecl the declaration being called, if available
  5048. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  5049. SourceLocation LParenLoc,
  5050. ArrayRef<Expr *> Args,
  5051. SourceLocation RParenLoc, Expr *Config,
  5052. bool IsExecConfig, ADLCallKind UsesADL) {
  5053. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5054. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5055. // Functions with 'interrupt' attribute cannot be called directly.
  5056. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5057. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5058. return ExprError();
  5059. }
  5060. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5061. // so there's some risk when calling out to non-interrupt handler functions
  5062. // that the callee might not preserve them. This is easy to diagnose here,
  5063. // but can be very challenging to debug.
  5064. if (auto *Caller = getCurFunctionDecl())
  5065. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5066. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5067. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  5068. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5069. }
  5070. // Promote the function operand.
  5071. // We special-case function promotion here because we only allow promoting
  5072. // builtin functions to function pointers in the callee of a call.
  5073. ExprResult Result;
  5074. QualType ResultTy;
  5075. if (BuiltinID &&
  5076. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5077. // Extract the return type from the (builtin) function pointer type.
  5078. // FIXME Several builtins still have setType in
  5079. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5080. // Builtins.def to ensure they are correct before removing setType calls.
  5081. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5082. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5083. ResultTy = FDecl->getCallResultType();
  5084. } else {
  5085. Result = CallExprUnaryConversions(Fn);
  5086. ResultTy = Context.BoolTy;
  5087. }
  5088. if (Result.isInvalid())
  5089. return ExprError();
  5090. Fn = Result.get();
  5091. // Check for a valid function type, but only if it is not a builtin which
  5092. // requires custom type checking. These will be handled by
  5093. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5094. const FunctionType *FuncT = nullptr;
  5095. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  5096. retry:
  5097. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  5098. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  5099. // have type pointer to function".
  5100. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  5101. if (!FuncT)
  5102. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5103. << Fn->getType() << Fn->getSourceRange());
  5104. } else if (const BlockPointerType *BPT =
  5105. Fn->getType()->getAs<BlockPointerType>()) {
  5106. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  5107. } else {
  5108. // Handle calls to expressions of unknown-any type.
  5109. if (Fn->getType() == Context.UnknownAnyTy) {
  5110. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  5111. if (rewrite.isInvalid())
  5112. return ExprError();
  5113. Fn = rewrite.get();
  5114. goto retry;
  5115. }
  5116. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5117. << Fn->getType() << Fn->getSourceRange());
  5118. }
  5119. }
  5120. // Get the number of parameters in the function prototype, if any.
  5121. // We will allocate space for max(Args.size(), NumParams) arguments
  5122. // in the call expression.
  5123. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  5124. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  5125. CallExpr *TheCall;
  5126. if (Config) {
  5127. assert(UsesADL == ADLCallKind::NotADL &&
  5128. "CUDAKernelCallExpr should not use ADL");
  5129. TheCall =
  5130. CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
  5131. ResultTy, VK_RValue, RParenLoc, NumParams);
  5132. } else {
  5133. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5134. RParenLoc, NumParams, UsesADL);
  5135. }
  5136. if (!getLangOpts().CPlusPlus) {
  5137. // Forget about the nulled arguments since typo correction
  5138. // do not handle them well.
  5139. TheCall->shrinkNumArgs(Args.size());
  5140. // C cannot always handle TypoExpr nodes in builtin calls and direct
  5141. // function calls as their argument checking don't necessarily handle
  5142. // dependent types properly, so make sure any TypoExprs have been
  5143. // dealt with.
  5144. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  5145. if (!Result.isUsable()) return ExprError();
  5146. CallExpr *TheOldCall = TheCall;
  5147. TheCall = dyn_cast<CallExpr>(Result.get());
  5148. bool CorrectedTypos = TheCall != TheOldCall;
  5149. if (!TheCall) return Result;
  5150. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  5151. // A new call expression node was created if some typos were corrected.
  5152. // However it may not have been constructed with enough storage. In this
  5153. // case, rebuild the node with enough storage. The waste of space is
  5154. // immaterial since this only happens when some typos were corrected.
  5155. if (CorrectedTypos && Args.size() < NumParams) {
  5156. if (Config)
  5157. TheCall = CUDAKernelCallExpr::Create(
  5158. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
  5159. RParenLoc, NumParams);
  5160. else
  5161. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5162. RParenLoc, NumParams, UsesADL);
  5163. }
  5164. // We can now handle the nulled arguments for the default arguments.
  5165. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  5166. }
  5167. // Bail out early if calling a builtin with custom type checking.
  5168. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  5169. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5170. if (getLangOpts().CUDA) {
  5171. if (Config) {
  5172. // CUDA: Kernel calls must be to global functions
  5173. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  5174. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  5175. << FDecl << Fn->getSourceRange());
  5176. // CUDA: Kernel function must have 'void' return type
  5177. if (!FuncT->getReturnType()->isVoidType())
  5178. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  5179. << Fn->getType() << Fn->getSourceRange());
  5180. } else {
  5181. // CUDA: Calls to global functions must be configured
  5182. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  5183. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  5184. << FDecl << Fn->getSourceRange());
  5185. }
  5186. }
  5187. // Check for a valid return type
  5188. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  5189. FDecl))
  5190. return ExprError();
  5191. // We know the result type of the call, set it.
  5192. TheCall->setType(FuncT->getCallResultType(Context));
  5193. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  5194. if (Proto) {
  5195. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  5196. IsExecConfig))
  5197. return ExprError();
  5198. } else {
  5199. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  5200. if (FDecl) {
  5201. // Check if we have too few/too many template arguments, based
  5202. // on our knowledge of the function definition.
  5203. const FunctionDecl *Def = nullptr;
  5204. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  5205. Proto = Def->getType()->getAs<FunctionProtoType>();
  5206. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  5207. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  5208. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  5209. }
  5210. // If the function we're calling isn't a function prototype, but we have
  5211. // a function prototype from a prior declaratiom, use that prototype.
  5212. if (!FDecl->hasPrototype())
  5213. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  5214. }
  5215. // Promote the arguments (C99 6.5.2.2p6).
  5216. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  5217. Expr *Arg = Args[i];
  5218. if (Proto && i < Proto->getNumParams()) {
  5219. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5220. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  5221. ExprResult ArgE =
  5222. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5223. if (ArgE.isInvalid())
  5224. return true;
  5225. Arg = ArgE.getAs<Expr>();
  5226. } else {
  5227. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  5228. if (ArgE.isInvalid())
  5229. return true;
  5230. Arg = ArgE.getAs<Expr>();
  5231. }
  5232. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  5233. diag::err_call_incomplete_argument, Arg))
  5234. return ExprError();
  5235. TheCall->setArg(i, Arg);
  5236. }
  5237. }
  5238. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5239. if (!Method->isStatic())
  5240. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  5241. << Fn->getSourceRange());
  5242. // Check for sentinels
  5243. if (NDecl)
  5244. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  5245. // Do special checking on direct calls to functions.
  5246. if (FDecl) {
  5247. if (CheckFunctionCall(FDecl, TheCall, Proto))
  5248. return ExprError();
  5249. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  5250. if (BuiltinID)
  5251. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5252. } else if (NDecl) {
  5253. if (CheckPointerCall(NDecl, TheCall, Proto))
  5254. return ExprError();
  5255. } else {
  5256. if (CheckOtherCall(TheCall, Proto))
  5257. return ExprError();
  5258. }
  5259. return MaybeBindToTemporary(TheCall);
  5260. }
  5261. ExprResult
  5262. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5263. SourceLocation RParenLoc, Expr *InitExpr) {
  5264. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5265. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5266. TypeSourceInfo *TInfo;
  5267. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5268. if (!TInfo)
  5269. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5270. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5271. }
  5272. ExprResult
  5273. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5274. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5275. QualType literalType = TInfo->getType();
  5276. if (literalType->isArrayType()) {
  5277. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5278. diag::err_illegal_decl_array_incomplete_type,
  5279. SourceRange(LParenLoc,
  5280. LiteralExpr->getSourceRange().getEnd())))
  5281. return ExprError();
  5282. if (literalType->isVariableArrayType())
  5283. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5284. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5285. } else if (!literalType->isDependentType() &&
  5286. RequireCompleteType(LParenLoc, literalType,
  5287. diag::err_typecheck_decl_incomplete_type,
  5288. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5289. return ExprError();
  5290. InitializedEntity Entity
  5291. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5292. InitializationKind Kind
  5293. = InitializationKind::CreateCStyleCast(LParenLoc,
  5294. SourceRange(LParenLoc, RParenLoc),
  5295. /*InitList=*/true);
  5296. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5297. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5298. &literalType);
  5299. if (Result.isInvalid())
  5300. return ExprError();
  5301. LiteralExpr = Result.get();
  5302. bool isFileScope = !CurContext->isFunctionOrMethod();
  5303. // In C, compound literals are l-values for some reason.
  5304. // For GCC compatibility, in C++, file-scope array compound literals with
  5305. // constant initializers are also l-values, and compound literals are
  5306. // otherwise prvalues.
  5307. //
  5308. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5309. // constant initializers as l-values, but that's non-conforming, so we don't
  5310. // follow it there.)
  5311. //
  5312. // FIXME: It would be better to handle the lvalue cases as materializing and
  5313. // lifetime-extending a temporary object, but our materialized temporaries
  5314. // representation only supports lifetime extension from a variable, not "out
  5315. // of thin air".
  5316. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5317. // is bound to the result of applying array-to-pointer decay to the compound
  5318. // literal.
  5319. // FIXME: GCC supports compound literals of reference type, which should
  5320. // obviously have a value kind derived from the kind of reference involved.
  5321. ExprValueKind VK =
  5322. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5323. ? VK_RValue
  5324. : VK_LValue;
  5325. if (isFileScope)
  5326. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  5327. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  5328. Expr *Init = ILE->getInit(i);
  5329. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  5330. }
  5331. auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5332. VK, LiteralExpr, isFileScope);
  5333. if (isFileScope) {
  5334. if (!LiteralExpr->isTypeDependent() &&
  5335. !LiteralExpr->isValueDependent() &&
  5336. !literalType->isDependentType()) // C99 6.5.2.5p3
  5337. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5338. return ExprError();
  5339. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5340. literalType.getAddressSpace() != LangAS::Default) {
  5341. // Embedded-C extensions to C99 6.5.2.5:
  5342. // "If the compound literal occurs inside the body of a function, the
  5343. // type name shall not be qualified by an address-space qualifier."
  5344. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5345. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5346. return ExprError();
  5347. }
  5348. // Compound literals that have automatic storage duration are destroyed at
  5349. // the end of the scope. Emit diagnostics if it is or contains a C union type
  5350. // that is non-trivial to destruct.
  5351. if (!isFileScope)
  5352. if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
  5353. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  5354. NTCUC_CompoundLiteral, NTCUK_Destruct);
  5355. if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  5356. E->getType().hasNonTrivialToPrimitiveCopyCUnion())
  5357. checkNonTrivialCUnionInInitializer(E->getInitializer(),
  5358. E->getInitializer()->getExprLoc());
  5359. return MaybeBindToTemporary(E);
  5360. }
  5361. ExprResult
  5362. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5363. SourceLocation RBraceLoc) {
  5364. // Immediately handle non-overload placeholders. Overloads can be
  5365. // resolved contextually, but everything else here can't.
  5366. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5367. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5368. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5369. // Ignore failures; dropping the entire initializer list because
  5370. // of one failure would be terrible for indexing/etc.
  5371. if (result.isInvalid()) continue;
  5372. InitArgList[I] = result.get();
  5373. }
  5374. }
  5375. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5376. // CheckInitializer() - it requires knowledge of the object being initialized.
  5377. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5378. RBraceLoc);
  5379. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5380. return E;
  5381. }
  5382. /// Do an explicit extend of the given block pointer if we're in ARC.
  5383. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5384. assert(E.get()->getType()->isBlockPointerType());
  5385. assert(E.get()->isRValue());
  5386. // Only do this in an r-value context.
  5387. if (!getLangOpts().ObjCAutoRefCount) return;
  5388. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5389. CK_ARCExtendBlockObject, E.get(),
  5390. /*base path*/ nullptr, VK_RValue);
  5391. Cleanup.setExprNeedsCleanups(true);
  5392. }
  5393. /// Prepare a conversion of the given expression to an ObjC object
  5394. /// pointer type.
  5395. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5396. QualType type = E.get()->getType();
  5397. if (type->isObjCObjectPointerType()) {
  5398. return CK_BitCast;
  5399. } else if (type->isBlockPointerType()) {
  5400. maybeExtendBlockObject(E);
  5401. return CK_BlockPointerToObjCPointerCast;
  5402. } else {
  5403. assert(type->isPointerType());
  5404. return CK_CPointerToObjCPointerCast;
  5405. }
  5406. }
  5407. /// Prepares for a scalar cast, performing all the necessary stages
  5408. /// except the final cast and returning the kind required.
  5409. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5410. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5411. // Also, callers should have filtered out the invalid cases with
  5412. // pointers. Everything else should be possible.
  5413. QualType SrcTy = Src.get()->getType();
  5414. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5415. return CK_NoOp;
  5416. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5417. case Type::STK_MemberPointer:
  5418. llvm_unreachable("member pointer type in C");
  5419. case Type::STK_CPointer:
  5420. case Type::STK_BlockPointer:
  5421. case Type::STK_ObjCObjectPointer:
  5422. switch (DestTy->getScalarTypeKind()) {
  5423. case Type::STK_CPointer: {
  5424. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5425. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5426. if (SrcAS != DestAS)
  5427. return CK_AddressSpaceConversion;
  5428. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5429. return CK_NoOp;
  5430. return CK_BitCast;
  5431. }
  5432. case Type::STK_BlockPointer:
  5433. return (SrcKind == Type::STK_BlockPointer
  5434. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5435. case Type::STK_ObjCObjectPointer:
  5436. if (SrcKind == Type::STK_ObjCObjectPointer)
  5437. return CK_BitCast;
  5438. if (SrcKind == Type::STK_CPointer)
  5439. return CK_CPointerToObjCPointerCast;
  5440. maybeExtendBlockObject(Src);
  5441. return CK_BlockPointerToObjCPointerCast;
  5442. case Type::STK_Bool:
  5443. return CK_PointerToBoolean;
  5444. case Type::STK_Integral:
  5445. return CK_PointerToIntegral;
  5446. case Type::STK_Floating:
  5447. case Type::STK_FloatingComplex:
  5448. case Type::STK_IntegralComplex:
  5449. case Type::STK_MemberPointer:
  5450. case Type::STK_FixedPoint:
  5451. llvm_unreachable("illegal cast from pointer");
  5452. }
  5453. llvm_unreachable("Should have returned before this");
  5454. case Type::STK_FixedPoint:
  5455. switch (DestTy->getScalarTypeKind()) {
  5456. case Type::STK_FixedPoint:
  5457. return CK_FixedPointCast;
  5458. case Type::STK_Bool:
  5459. return CK_FixedPointToBoolean;
  5460. case Type::STK_Integral:
  5461. return CK_FixedPointToIntegral;
  5462. case Type::STK_Floating:
  5463. case Type::STK_IntegralComplex:
  5464. case Type::STK_FloatingComplex:
  5465. Diag(Src.get()->getExprLoc(),
  5466. diag::err_unimplemented_conversion_with_fixed_point_type)
  5467. << DestTy;
  5468. return CK_IntegralCast;
  5469. case Type::STK_CPointer:
  5470. case Type::STK_ObjCObjectPointer:
  5471. case Type::STK_BlockPointer:
  5472. case Type::STK_MemberPointer:
  5473. llvm_unreachable("illegal cast to pointer type");
  5474. }
  5475. llvm_unreachable("Should have returned before this");
  5476. case Type::STK_Bool: // casting from bool is like casting from an integer
  5477. case Type::STK_Integral:
  5478. switch (DestTy->getScalarTypeKind()) {
  5479. case Type::STK_CPointer:
  5480. case Type::STK_ObjCObjectPointer:
  5481. case Type::STK_BlockPointer:
  5482. if (Src.get()->isNullPointerConstant(Context,
  5483. Expr::NPC_ValueDependentIsNull))
  5484. return CK_NullToPointer;
  5485. return CK_IntegralToPointer;
  5486. case Type::STK_Bool:
  5487. return CK_IntegralToBoolean;
  5488. case Type::STK_Integral:
  5489. return CK_IntegralCast;
  5490. case Type::STK_Floating:
  5491. return CK_IntegralToFloating;
  5492. case Type::STK_IntegralComplex:
  5493. Src = ImpCastExprToType(Src.get(),
  5494. DestTy->castAs<ComplexType>()->getElementType(),
  5495. CK_IntegralCast);
  5496. return CK_IntegralRealToComplex;
  5497. case Type::STK_FloatingComplex:
  5498. Src = ImpCastExprToType(Src.get(),
  5499. DestTy->castAs<ComplexType>()->getElementType(),
  5500. CK_IntegralToFloating);
  5501. return CK_FloatingRealToComplex;
  5502. case Type::STK_MemberPointer:
  5503. llvm_unreachable("member pointer type in C");
  5504. case Type::STK_FixedPoint:
  5505. return CK_IntegralToFixedPoint;
  5506. }
  5507. llvm_unreachable("Should have returned before this");
  5508. case Type::STK_Floating:
  5509. switch (DestTy->getScalarTypeKind()) {
  5510. case Type::STK_Floating:
  5511. return CK_FloatingCast;
  5512. case Type::STK_Bool:
  5513. return CK_FloatingToBoolean;
  5514. case Type::STK_Integral:
  5515. return CK_FloatingToIntegral;
  5516. case Type::STK_FloatingComplex:
  5517. Src = ImpCastExprToType(Src.get(),
  5518. DestTy->castAs<ComplexType>()->getElementType(),
  5519. CK_FloatingCast);
  5520. return CK_FloatingRealToComplex;
  5521. case Type::STK_IntegralComplex:
  5522. Src = ImpCastExprToType(Src.get(),
  5523. DestTy->castAs<ComplexType>()->getElementType(),
  5524. CK_FloatingToIntegral);
  5525. return CK_IntegralRealToComplex;
  5526. case Type::STK_CPointer:
  5527. case Type::STK_ObjCObjectPointer:
  5528. case Type::STK_BlockPointer:
  5529. llvm_unreachable("valid float->pointer cast?");
  5530. case Type::STK_MemberPointer:
  5531. llvm_unreachable("member pointer type in C");
  5532. case Type::STK_FixedPoint:
  5533. Diag(Src.get()->getExprLoc(),
  5534. diag::err_unimplemented_conversion_with_fixed_point_type)
  5535. << SrcTy;
  5536. return CK_IntegralCast;
  5537. }
  5538. llvm_unreachable("Should have returned before this");
  5539. case Type::STK_FloatingComplex:
  5540. switch (DestTy->getScalarTypeKind()) {
  5541. case Type::STK_FloatingComplex:
  5542. return CK_FloatingComplexCast;
  5543. case Type::STK_IntegralComplex:
  5544. return CK_FloatingComplexToIntegralComplex;
  5545. case Type::STK_Floating: {
  5546. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5547. if (Context.hasSameType(ET, DestTy))
  5548. return CK_FloatingComplexToReal;
  5549. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5550. return CK_FloatingCast;
  5551. }
  5552. case Type::STK_Bool:
  5553. return CK_FloatingComplexToBoolean;
  5554. case Type::STK_Integral:
  5555. Src = ImpCastExprToType(Src.get(),
  5556. SrcTy->castAs<ComplexType>()->getElementType(),
  5557. CK_FloatingComplexToReal);
  5558. return CK_FloatingToIntegral;
  5559. case Type::STK_CPointer:
  5560. case Type::STK_ObjCObjectPointer:
  5561. case Type::STK_BlockPointer:
  5562. llvm_unreachable("valid complex float->pointer cast?");
  5563. case Type::STK_MemberPointer:
  5564. llvm_unreachable("member pointer type in C");
  5565. case Type::STK_FixedPoint:
  5566. Diag(Src.get()->getExprLoc(),
  5567. diag::err_unimplemented_conversion_with_fixed_point_type)
  5568. << SrcTy;
  5569. return CK_IntegralCast;
  5570. }
  5571. llvm_unreachable("Should have returned before this");
  5572. case Type::STK_IntegralComplex:
  5573. switch (DestTy->getScalarTypeKind()) {
  5574. case Type::STK_FloatingComplex:
  5575. return CK_IntegralComplexToFloatingComplex;
  5576. case Type::STK_IntegralComplex:
  5577. return CK_IntegralComplexCast;
  5578. case Type::STK_Integral: {
  5579. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5580. if (Context.hasSameType(ET, DestTy))
  5581. return CK_IntegralComplexToReal;
  5582. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5583. return CK_IntegralCast;
  5584. }
  5585. case Type::STK_Bool:
  5586. return CK_IntegralComplexToBoolean;
  5587. case Type::STK_Floating:
  5588. Src = ImpCastExprToType(Src.get(),
  5589. SrcTy->castAs<ComplexType>()->getElementType(),
  5590. CK_IntegralComplexToReal);
  5591. return CK_IntegralToFloating;
  5592. case Type::STK_CPointer:
  5593. case Type::STK_ObjCObjectPointer:
  5594. case Type::STK_BlockPointer:
  5595. llvm_unreachable("valid complex int->pointer cast?");
  5596. case Type::STK_MemberPointer:
  5597. llvm_unreachable("member pointer type in C");
  5598. case Type::STK_FixedPoint:
  5599. Diag(Src.get()->getExprLoc(),
  5600. diag::err_unimplemented_conversion_with_fixed_point_type)
  5601. << SrcTy;
  5602. return CK_IntegralCast;
  5603. }
  5604. llvm_unreachable("Should have returned before this");
  5605. }
  5606. llvm_unreachable("Unhandled scalar cast");
  5607. }
  5608. static bool breakDownVectorType(QualType type, uint64_t &len,
  5609. QualType &eltType) {
  5610. // Vectors are simple.
  5611. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5612. len = vecType->getNumElements();
  5613. eltType = vecType->getElementType();
  5614. assert(eltType->isScalarType());
  5615. return true;
  5616. }
  5617. // We allow lax conversion to and from non-vector types, but only if
  5618. // they're real types (i.e. non-complex, non-pointer scalar types).
  5619. if (!type->isRealType()) return false;
  5620. len = 1;
  5621. eltType = type;
  5622. return true;
  5623. }
  5624. /// Are the two types lax-compatible vector types? That is, given
  5625. /// that one of them is a vector, do they have equal storage sizes,
  5626. /// where the storage size is the number of elements times the element
  5627. /// size?
  5628. ///
  5629. /// This will also return false if either of the types is neither a
  5630. /// vector nor a real type.
  5631. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5632. assert(destTy->isVectorType() || srcTy->isVectorType());
  5633. // Disallow lax conversions between scalars and ExtVectors (these
  5634. // conversions are allowed for other vector types because common headers
  5635. // depend on them). Most scalar OP ExtVector cases are handled by the
  5636. // splat path anyway, which does what we want (convert, not bitcast).
  5637. // What this rules out for ExtVectors is crazy things like char4*float.
  5638. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5639. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5640. uint64_t srcLen, destLen;
  5641. QualType srcEltTy, destEltTy;
  5642. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5643. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5644. // ASTContext::getTypeSize will return the size rounded up to a
  5645. // power of 2, so instead of using that, we need to use the raw
  5646. // element size multiplied by the element count.
  5647. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5648. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5649. return (srcLen * srcEltSize == destLen * destEltSize);
  5650. }
  5651. /// Is this a legal conversion between two types, one of which is
  5652. /// known to be a vector type?
  5653. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5654. assert(destTy->isVectorType() || srcTy->isVectorType());
  5655. if (!Context.getLangOpts().LaxVectorConversions)
  5656. return false;
  5657. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5658. }
  5659. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5660. CastKind &Kind) {
  5661. assert(VectorTy->isVectorType() && "Not a vector type!");
  5662. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5663. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5664. return Diag(R.getBegin(),
  5665. Ty->isVectorType() ?
  5666. diag::err_invalid_conversion_between_vectors :
  5667. diag::err_invalid_conversion_between_vector_and_integer)
  5668. << VectorTy << Ty << R;
  5669. } else
  5670. return Diag(R.getBegin(),
  5671. diag::err_invalid_conversion_between_vector_and_scalar)
  5672. << VectorTy << Ty << R;
  5673. Kind = CK_BitCast;
  5674. return false;
  5675. }
  5676. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5677. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5678. if (DestElemTy == SplattedExpr->getType())
  5679. return SplattedExpr;
  5680. assert(DestElemTy->isFloatingType() ||
  5681. DestElemTy->isIntegralOrEnumerationType());
  5682. CastKind CK;
  5683. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5684. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5685. // only when splatting vectors.
  5686. if (DestElemTy->isFloatingType()) {
  5687. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5688. // in two steps: boolean to signed integral, then to floating.
  5689. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5690. CK_BooleanToSignedIntegral);
  5691. SplattedExpr = CastExprRes.get();
  5692. CK = CK_IntegralToFloating;
  5693. } else {
  5694. CK = CK_BooleanToSignedIntegral;
  5695. }
  5696. } else {
  5697. ExprResult CastExprRes = SplattedExpr;
  5698. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5699. if (CastExprRes.isInvalid())
  5700. return ExprError();
  5701. SplattedExpr = CastExprRes.get();
  5702. }
  5703. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5704. }
  5705. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5706. Expr *CastExpr, CastKind &Kind) {
  5707. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5708. QualType SrcTy = CastExpr->getType();
  5709. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5710. // an ExtVectorType.
  5711. // In OpenCL, casts between vectors of different types are not allowed.
  5712. // (See OpenCL 6.2).
  5713. if (SrcTy->isVectorType()) {
  5714. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5715. (getLangOpts().OpenCL &&
  5716. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5717. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5718. << DestTy << SrcTy << R;
  5719. return ExprError();
  5720. }
  5721. Kind = CK_BitCast;
  5722. return CastExpr;
  5723. }
  5724. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5725. // conversion will take place first from scalar to elt type, and then
  5726. // splat from elt type to vector.
  5727. if (SrcTy->isPointerType())
  5728. return Diag(R.getBegin(),
  5729. diag::err_invalid_conversion_between_vector_and_scalar)
  5730. << DestTy << SrcTy << R;
  5731. Kind = CK_VectorSplat;
  5732. return prepareVectorSplat(DestTy, CastExpr);
  5733. }
  5734. ExprResult
  5735. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5736. Declarator &D, ParsedType &Ty,
  5737. SourceLocation RParenLoc, Expr *CastExpr) {
  5738. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5739. "ActOnCastExpr(): missing type or expr");
  5740. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5741. if (D.isInvalidType())
  5742. return ExprError();
  5743. if (getLangOpts().CPlusPlus) {
  5744. // Check that there are no default arguments (C++ only).
  5745. CheckExtraCXXDefaultArguments(D);
  5746. } else {
  5747. // Make sure any TypoExprs have been dealt with.
  5748. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5749. if (!Res.isUsable())
  5750. return ExprError();
  5751. CastExpr = Res.get();
  5752. }
  5753. checkUnusedDeclAttributes(D);
  5754. QualType castType = castTInfo->getType();
  5755. Ty = CreateParsedType(castType, castTInfo);
  5756. bool isVectorLiteral = false;
  5757. // Check for an altivec or OpenCL literal,
  5758. // i.e. all the elements are integer constants.
  5759. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5760. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5761. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5762. && castType->isVectorType() && (PE || PLE)) {
  5763. if (PLE && PLE->getNumExprs() == 0) {
  5764. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5765. return ExprError();
  5766. }
  5767. if (PE || PLE->getNumExprs() == 1) {
  5768. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5769. if (!E->getType()->isVectorType())
  5770. isVectorLiteral = true;
  5771. }
  5772. else
  5773. isVectorLiteral = true;
  5774. }
  5775. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5776. // then handle it as such.
  5777. if (isVectorLiteral)
  5778. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5779. // If the Expr being casted is a ParenListExpr, handle it specially.
  5780. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5781. // sequence of BinOp comma operators.
  5782. if (isa<ParenListExpr>(CastExpr)) {
  5783. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5784. if (Result.isInvalid()) return ExprError();
  5785. CastExpr = Result.get();
  5786. }
  5787. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5788. !getSourceManager().isInSystemMacro(LParenLoc))
  5789. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5790. CheckTollFreeBridgeCast(castType, CastExpr);
  5791. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5792. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5793. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5794. }
  5795. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5796. SourceLocation RParenLoc, Expr *E,
  5797. TypeSourceInfo *TInfo) {
  5798. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5799. "Expected paren or paren list expression");
  5800. Expr **exprs;
  5801. unsigned numExprs;
  5802. Expr *subExpr;
  5803. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5804. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5805. LiteralLParenLoc = PE->getLParenLoc();
  5806. LiteralRParenLoc = PE->getRParenLoc();
  5807. exprs = PE->getExprs();
  5808. numExprs = PE->getNumExprs();
  5809. } else { // isa<ParenExpr> by assertion at function entrance
  5810. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5811. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5812. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5813. exprs = &subExpr;
  5814. numExprs = 1;
  5815. }
  5816. QualType Ty = TInfo->getType();
  5817. assert(Ty->isVectorType() && "Expected vector type");
  5818. SmallVector<Expr *, 8> initExprs;
  5819. const VectorType *VTy = Ty->getAs<VectorType>();
  5820. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5821. // '(...)' form of vector initialization in AltiVec: the number of
  5822. // initializers must be one or must match the size of the vector.
  5823. // If a single value is specified in the initializer then it will be
  5824. // replicated to all the components of the vector
  5825. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5826. // The number of initializers must be one or must match the size of the
  5827. // vector. If a single value is specified in the initializer then it will
  5828. // be replicated to all the components of the vector
  5829. if (numExprs == 1) {
  5830. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5831. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5832. if (Literal.isInvalid())
  5833. return ExprError();
  5834. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5835. PrepareScalarCast(Literal, ElemTy));
  5836. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5837. }
  5838. else if (numExprs < numElems) {
  5839. Diag(E->getExprLoc(),
  5840. diag::err_incorrect_number_of_vector_initializers);
  5841. return ExprError();
  5842. }
  5843. else
  5844. initExprs.append(exprs, exprs + numExprs);
  5845. }
  5846. else {
  5847. // For OpenCL, when the number of initializers is a single value,
  5848. // it will be replicated to all components of the vector.
  5849. if (getLangOpts().OpenCL &&
  5850. VTy->getVectorKind() == VectorType::GenericVector &&
  5851. numExprs == 1) {
  5852. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5853. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5854. if (Literal.isInvalid())
  5855. return ExprError();
  5856. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5857. PrepareScalarCast(Literal, ElemTy));
  5858. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5859. }
  5860. initExprs.append(exprs, exprs + numExprs);
  5861. }
  5862. // FIXME: This means that pretty-printing the final AST will produce curly
  5863. // braces instead of the original commas.
  5864. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5865. initExprs, LiteralRParenLoc);
  5866. initE->setType(Ty);
  5867. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5868. }
  5869. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5870. /// the ParenListExpr into a sequence of comma binary operators.
  5871. ExprResult
  5872. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5873. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5874. if (!E)
  5875. return OrigExpr;
  5876. ExprResult Result(E->getExpr(0));
  5877. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5878. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5879. E->getExpr(i));
  5880. if (Result.isInvalid()) return ExprError();
  5881. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5882. }
  5883. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5884. SourceLocation R,
  5885. MultiExprArg Val) {
  5886. return ParenListExpr::Create(Context, L, Val, R);
  5887. }
  5888. /// Emit a specialized diagnostic when one expression is a null pointer
  5889. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5890. /// emitted.
  5891. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5892. SourceLocation QuestionLoc) {
  5893. Expr *NullExpr = LHSExpr;
  5894. Expr *NonPointerExpr = RHSExpr;
  5895. Expr::NullPointerConstantKind NullKind =
  5896. NullExpr->isNullPointerConstant(Context,
  5897. Expr::NPC_ValueDependentIsNotNull);
  5898. if (NullKind == Expr::NPCK_NotNull) {
  5899. NullExpr = RHSExpr;
  5900. NonPointerExpr = LHSExpr;
  5901. NullKind =
  5902. NullExpr->isNullPointerConstant(Context,
  5903. Expr::NPC_ValueDependentIsNotNull);
  5904. }
  5905. if (NullKind == Expr::NPCK_NotNull)
  5906. return false;
  5907. if (NullKind == Expr::NPCK_ZeroExpression)
  5908. return false;
  5909. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5910. // In this case, check to make sure that we got here from a "NULL"
  5911. // string in the source code.
  5912. NullExpr = NullExpr->IgnoreParenImpCasts();
  5913. SourceLocation loc = NullExpr->getExprLoc();
  5914. if (!findMacroSpelling(loc, "NULL"))
  5915. return false;
  5916. }
  5917. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5918. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5919. << NonPointerExpr->getType() << DiagType
  5920. << NonPointerExpr->getSourceRange();
  5921. return true;
  5922. }
  5923. /// Return false if the condition expression is valid, true otherwise.
  5924. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5925. QualType CondTy = Cond->getType();
  5926. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5927. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5928. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5929. << CondTy << Cond->getSourceRange();
  5930. return true;
  5931. }
  5932. // C99 6.5.15p2
  5933. if (CondTy->isScalarType()) return false;
  5934. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5935. << CondTy << Cond->getSourceRange();
  5936. return true;
  5937. }
  5938. /// Handle when one or both operands are void type.
  5939. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5940. ExprResult &RHS) {
  5941. Expr *LHSExpr = LHS.get();
  5942. Expr *RHSExpr = RHS.get();
  5943. if (!LHSExpr->getType()->isVoidType())
  5944. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5945. << RHSExpr->getSourceRange();
  5946. if (!RHSExpr->getType()->isVoidType())
  5947. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5948. << LHSExpr->getSourceRange();
  5949. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5950. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5951. return S.Context.VoidTy;
  5952. }
  5953. /// Return false if the NullExpr can be promoted to PointerTy,
  5954. /// true otherwise.
  5955. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5956. QualType PointerTy) {
  5957. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5958. !NullExpr.get()->isNullPointerConstant(S.Context,
  5959. Expr::NPC_ValueDependentIsNull))
  5960. return true;
  5961. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5962. return false;
  5963. }
  5964. /// Checks compatibility between two pointers and return the resulting
  5965. /// type.
  5966. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5967. ExprResult &RHS,
  5968. SourceLocation Loc) {
  5969. QualType LHSTy = LHS.get()->getType();
  5970. QualType RHSTy = RHS.get()->getType();
  5971. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5972. // Two identical pointers types are always compatible.
  5973. return LHSTy;
  5974. }
  5975. QualType lhptee, rhptee;
  5976. // Get the pointee types.
  5977. bool IsBlockPointer = false;
  5978. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5979. lhptee = LHSBTy->getPointeeType();
  5980. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5981. IsBlockPointer = true;
  5982. } else {
  5983. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5984. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5985. }
  5986. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5987. // differently qualified versions of compatible types, the result type is
  5988. // a pointer to an appropriately qualified version of the composite
  5989. // type.
  5990. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5991. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5992. // be incompatible with address space 3: they may live on different devices or
  5993. // anything.
  5994. Qualifiers lhQual = lhptee.getQualifiers();
  5995. Qualifiers rhQual = rhptee.getQualifiers();
  5996. LangAS ResultAddrSpace = LangAS::Default;
  5997. LangAS LAddrSpace = lhQual.getAddressSpace();
  5998. LangAS RAddrSpace = rhQual.getAddressSpace();
  5999. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  6000. // spaces is disallowed.
  6001. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  6002. ResultAddrSpace = LAddrSpace;
  6003. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  6004. ResultAddrSpace = RAddrSpace;
  6005. else {
  6006. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6007. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  6008. << RHS.get()->getSourceRange();
  6009. return QualType();
  6010. }
  6011. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  6012. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  6013. lhQual.removeCVRQualifiers();
  6014. rhQual.removeCVRQualifiers();
  6015. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  6016. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  6017. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  6018. // qual types are compatible iff
  6019. // * corresponded types are compatible
  6020. // * CVR qualifiers are equal
  6021. // * address spaces are equal
  6022. // Thus for conditional operator we merge CVR and address space unqualified
  6023. // pointees and if there is a composite type we return a pointer to it with
  6024. // merged qualifiers.
  6025. LHSCastKind =
  6026. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6027. RHSCastKind =
  6028. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6029. lhQual.removeAddressSpace();
  6030. rhQual.removeAddressSpace();
  6031. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  6032. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  6033. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  6034. if (CompositeTy.isNull()) {
  6035. // In this situation, we assume void* type. No especially good
  6036. // reason, but this is what gcc does, and we do have to pick
  6037. // to get a consistent AST.
  6038. QualType incompatTy;
  6039. incompatTy = S.Context.getPointerType(
  6040. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  6041. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  6042. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  6043. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  6044. // for casts between types with incompatible address space qualifiers.
  6045. // For the following code the compiler produces casts between global and
  6046. // local address spaces of the corresponded innermost pointees:
  6047. // local int *global *a;
  6048. // global int *global *b;
  6049. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  6050. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  6051. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6052. << RHS.get()->getSourceRange();
  6053. return incompatTy;
  6054. }
  6055. // The pointer types are compatible.
  6056. // In case of OpenCL ResultTy should have the address space qualifier
  6057. // which is a superset of address spaces of both the 2nd and the 3rd
  6058. // operands of the conditional operator.
  6059. QualType ResultTy = [&, ResultAddrSpace]() {
  6060. if (S.getLangOpts().OpenCL) {
  6061. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  6062. CompositeQuals.setAddressSpace(ResultAddrSpace);
  6063. return S.Context
  6064. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  6065. .withCVRQualifiers(MergedCVRQual);
  6066. }
  6067. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  6068. }();
  6069. if (IsBlockPointer)
  6070. ResultTy = S.Context.getBlockPointerType(ResultTy);
  6071. else
  6072. ResultTy = S.Context.getPointerType(ResultTy);
  6073. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  6074. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  6075. return ResultTy;
  6076. }
  6077. /// Return the resulting type when the operands are both block pointers.
  6078. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  6079. ExprResult &LHS,
  6080. ExprResult &RHS,
  6081. SourceLocation Loc) {
  6082. QualType LHSTy = LHS.get()->getType();
  6083. QualType RHSTy = RHS.get()->getType();
  6084. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  6085. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  6086. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  6087. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6088. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6089. return destType;
  6090. }
  6091. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  6092. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6093. << RHS.get()->getSourceRange();
  6094. return QualType();
  6095. }
  6096. // We have 2 block pointer types.
  6097. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6098. }
  6099. /// Return the resulting type when the operands are both pointers.
  6100. static QualType
  6101. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  6102. ExprResult &RHS,
  6103. SourceLocation Loc) {
  6104. // get the pointer types
  6105. QualType LHSTy = LHS.get()->getType();
  6106. QualType RHSTy = RHS.get()->getType();
  6107. // get the "pointed to" types
  6108. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6109. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6110. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  6111. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  6112. // Figure out necessary qualifiers (C99 6.5.15p6)
  6113. QualType destPointee
  6114. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6115. QualType destType = S.Context.getPointerType(destPointee);
  6116. // Add qualifiers if necessary.
  6117. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6118. // Promote to void*.
  6119. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6120. return destType;
  6121. }
  6122. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  6123. QualType destPointee
  6124. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6125. QualType destType = S.Context.getPointerType(destPointee);
  6126. // Add qualifiers if necessary.
  6127. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6128. // Promote to void*.
  6129. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6130. return destType;
  6131. }
  6132. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6133. }
  6134. /// Return false if the first expression is not an integer and the second
  6135. /// expression is not a pointer, true otherwise.
  6136. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  6137. Expr* PointerExpr, SourceLocation Loc,
  6138. bool IsIntFirstExpr) {
  6139. if (!PointerExpr->getType()->isPointerType() ||
  6140. !Int.get()->getType()->isIntegerType())
  6141. return false;
  6142. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  6143. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  6144. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  6145. << Expr1->getType() << Expr2->getType()
  6146. << Expr1->getSourceRange() << Expr2->getSourceRange();
  6147. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  6148. CK_IntegralToPointer);
  6149. return true;
  6150. }
  6151. /// Simple conversion between integer and floating point types.
  6152. ///
  6153. /// Used when handling the OpenCL conditional operator where the
  6154. /// condition is a vector while the other operands are scalar.
  6155. ///
  6156. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  6157. /// types are either integer or floating type. Between the two
  6158. /// operands, the type with the higher rank is defined as the "result
  6159. /// type". The other operand needs to be promoted to the same type. No
  6160. /// other type promotion is allowed. We cannot use
  6161. /// UsualArithmeticConversions() for this purpose, since it always
  6162. /// promotes promotable types.
  6163. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  6164. ExprResult &RHS,
  6165. SourceLocation QuestionLoc) {
  6166. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  6167. if (LHS.isInvalid())
  6168. return QualType();
  6169. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  6170. if (RHS.isInvalid())
  6171. return QualType();
  6172. // For conversion purposes, we ignore any qualifiers.
  6173. // For example, "const float" and "float" are equivalent.
  6174. QualType LHSType =
  6175. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  6176. QualType RHSType =
  6177. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  6178. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  6179. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6180. << LHSType << LHS.get()->getSourceRange();
  6181. return QualType();
  6182. }
  6183. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  6184. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6185. << RHSType << RHS.get()->getSourceRange();
  6186. return QualType();
  6187. }
  6188. // If both types are identical, no conversion is needed.
  6189. if (LHSType == RHSType)
  6190. return LHSType;
  6191. // Now handle "real" floating types (i.e. float, double, long double).
  6192. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  6193. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  6194. /*IsCompAssign = */ false);
  6195. // Finally, we have two differing integer types.
  6196. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  6197. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  6198. }
  6199. /// Convert scalar operands to a vector that matches the
  6200. /// condition in length.
  6201. ///
  6202. /// Used when handling the OpenCL conditional operator where the
  6203. /// condition is a vector while the other operands are scalar.
  6204. ///
  6205. /// We first compute the "result type" for the scalar operands
  6206. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  6207. /// into a vector of that type where the length matches the condition
  6208. /// vector type. s6.11.6 requires that the element types of the result
  6209. /// and the condition must have the same number of bits.
  6210. static QualType
  6211. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6212. QualType CondTy, SourceLocation QuestionLoc) {
  6213. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  6214. if (ResTy.isNull()) return QualType();
  6215. const VectorType *CV = CondTy->getAs<VectorType>();
  6216. assert(CV);
  6217. // Determine the vector result type
  6218. unsigned NumElements = CV->getNumElements();
  6219. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  6220. // Ensure that all types have the same number of bits
  6221. if (S.Context.getTypeSize(CV->getElementType())
  6222. != S.Context.getTypeSize(ResTy)) {
  6223. // Since VectorTy is created internally, it does not pretty print
  6224. // with an OpenCL name. Instead, we just print a description.
  6225. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  6226. SmallString<64> Str;
  6227. llvm::raw_svector_ostream OS(Str);
  6228. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  6229. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6230. << CondTy << OS.str();
  6231. return QualType();
  6232. }
  6233. // Convert operands to the vector result type
  6234. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  6235. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  6236. return VectorTy;
  6237. }
  6238. /// Return false if this is a valid OpenCL condition vector
  6239. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  6240. SourceLocation QuestionLoc) {
  6241. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  6242. // integral type.
  6243. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  6244. assert(CondTy);
  6245. QualType EleTy = CondTy->getElementType();
  6246. if (EleTy->isIntegerType()) return false;
  6247. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6248. << Cond->getType() << Cond->getSourceRange();
  6249. return true;
  6250. }
  6251. /// Return false if the vector condition type and the vector
  6252. /// result type are compatible.
  6253. ///
  6254. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  6255. /// number of elements, and their element types have the same number
  6256. /// of bits.
  6257. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  6258. SourceLocation QuestionLoc) {
  6259. const VectorType *CV = CondTy->getAs<VectorType>();
  6260. const VectorType *RV = VecResTy->getAs<VectorType>();
  6261. assert(CV && RV);
  6262. if (CV->getNumElements() != RV->getNumElements()) {
  6263. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  6264. << CondTy << VecResTy;
  6265. return true;
  6266. }
  6267. QualType CVE = CV->getElementType();
  6268. QualType RVE = RV->getElementType();
  6269. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  6270. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6271. << CondTy << VecResTy;
  6272. return true;
  6273. }
  6274. return false;
  6275. }
  6276. /// Return the resulting type for the conditional operator in
  6277. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6278. /// s6.3.i) when the condition is a vector type.
  6279. static QualType
  6280. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6281. ExprResult &LHS, ExprResult &RHS,
  6282. SourceLocation QuestionLoc) {
  6283. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6284. if (Cond.isInvalid())
  6285. return QualType();
  6286. QualType CondTy = Cond.get()->getType();
  6287. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6288. return QualType();
  6289. // If either operand is a vector then find the vector type of the
  6290. // result as specified in OpenCL v1.1 s6.3.i.
  6291. if (LHS.get()->getType()->isVectorType() ||
  6292. RHS.get()->getType()->isVectorType()) {
  6293. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6294. /*isCompAssign*/false,
  6295. /*AllowBothBool*/true,
  6296. /*AllowBoolConversions*/false);
  6297. if (VecResTy.isNull()) return QualType();
  6298. // The result type must match the condition type as specified in
  6299. // OpenCL v1.1 s6.11.6.
  6300. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6301. return QualType();
  6302. return VecResTy;
  6303. }
  6304. // Both operands are scalar.
  6305. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6306. }
  6307. /// Return true if the Expr is block type
  6308. static bool checkBlockType(Sema &S, const Expr *E) {
  6309. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6310. QualType Ty = CE->getCallee()->getType();
  6311. if (Ty->isBlockPointerType()) {
  6312. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6313. return true;
  6314. }
  6315. }
  6316. return false;
  6317. }
  6318. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6319. /// In that case, LHS = cond.
  6320. /// C99 6.5.15
  6321. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6322. ExprResult &RHS, ExprValueKind &VK,
  6323. ExprObjectKind &OK,
  6324. SourceLocation QuestionLoc) {
  6325. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6326. if (!LHSResult.isUsable()) return QualType();
  6327. LHS = LHSResult;
  6328. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6329. if (!RHSResult.isUsable()) return QualType();
  6330. RHS = RHSResult;
  6331. // C++ is sufficiently different to merit its own checker.
  6332. if (getLangOpts().CPlusPlus)
  6333. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6334. VK = VK_RValue;
  6335. OK = OK_Ordinary;
  6336. // The OpenCL operator with a vector condition is sufficiently
  6337. // different to merit its own checker.
  6338. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6339. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6340. // First, check the condition.
  6341. Cond = UsualUnaryConversions(Cond.get());
  6342. if (Cond.isInvalid())
  6343. return QualType();
  6344. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6345. return QualType();
  6346. // Now check the two expressions.
  6347. if (LHS.get()->getType()->isVectorType() ||
  6348. RHS.get()->getType()->isVectorType())
  6349. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6350. /*AllowBothBool*/true,
  6351. /*AllowBoolConversions*/false);
  6352. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6353. if (LHS.isInvalid() || RHS.isInvalid())
  6354. return QualType();
  6355. QualType LHSTy = LHS.get()->getType();
  6356. QualType RHSTy = RHS.get()->getType();
  6357. // Diagnose attempts to convert between __float128 and long double where
  6358. // such conversions currently can't be handled.
  6359. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6360. Diag(QuestionLoc,
  6361. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6362. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6363. return QualType();
  6364. }
  6365. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6366. // selection operator (?:).
  6367. if (getLangOpts().OpenCL &&
  6368. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6369. return QualType();
  6370. }
  6371. // If both operands have arithmetic type, do the usual arithmetic conversions
  6372. // to find a common type: C99 6.5.15p3,5.
  6373. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6374. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6375. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6376. return ResTy;
  6377. }
  6378. // If both operands are the same structure or union type, the result is that
  6379. // type.
  6380. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6381. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6382. if (LHSRT->getDecl() == RHSRT->getDecl())
  6383. // "If both the operands have structure or union type, the result has
  6384. // that type." This implies that CV qualifiers are dropped.
  6385. return LHSTy.getUnqualifiedType();
  6386. // FIXME: Type of conditional expression must be complete in C mode.
  6387. }
  6388. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6389. // The following || allows only one side to be void (a GCC-ism).
  6390. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6391. return checkConditionalVoidType(*this, LHS, RHS);
  6392. }
  6393. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6394. // the type of the other operand."
  6395. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6396. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6397. // All objective-c pointer type analysis is done here.
  6398. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6399. QuestionLoc);
  6400. if (LHS.isInvalid() || RHS.isInvalid())
  6401. return QualType();
  6402. if (!compositeType.isNull())
  6403. return compositeType;
  6404. // Handle block pointer types.
  6405. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6406. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6407. QuestionLoc);
  6408. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6409. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6410. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6411. QuestionLoc);
  6412. // GCC compatibility: soften pointer/integer mismatch. Note that
  6413. // null pointers have been filtered out by this point.
  6414. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6415. /*IsIntFirstExpr=*/true))
  6416. return RHSTy;
  6417. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6418. /*IsIntFirstExpr=*/false))
  6419. return LHSTy;
  6420. // Emit a better diagnostic if one of the expressions is a null pointer
  6421. // constant and the other is not a pointer type. In this case, the user most
  6422. // likely forgot to take the address of the other expression.
  6423. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6424. return QualType();
  6425. // Otherwise, the operands are not compatible.
  6426. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6427. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6428. << RHS.get()->getSourceRange();
  6429. return QualType();
  6430. }
  6431. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6432. /// two objective-c pointer types of the two input expressions.
  6433. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6434. SourceLocation QuestionLoc) {
  6435. QualType LHSTy = LHS.get()->getType();
  6436. QualType RHSTy = RHS.get()->getType();
  6437. // Handle things like Class and struct objc_class*. Here we case the result
  6438. // to the pseudo-builtin, because that will be implicitly cast back to the
  6439. // redefinition type if an attempt is made to access its fields.
  6440. if (LHSTy->isObjCClassType() &&
  6441. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6442. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6443. return LHSTy;
  6444. }
  6445. if (RHSTy->isObjCClassType() &&
  6446. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6447. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6448. return RHSTy;
  6449. }
  6450. // And the same for struct objc_object* / id
  6451. if (LHSTy->isObjCIdType() &&
  6452. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6453. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6454. return LHSTy;
  6455. }
  6456. if (RHSTy->isObjCIdType() &&
  6457. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6458. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6459. return RHSTy;
  6460. }
  6461. // And the same for struct objc_selector* / SEL
  6462. if (Context.isObjCSelType(LHSTy) &&
  6463. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6464. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6465. return LHSTy;
  6466. }
  6467. if (Context.isObjCSelType(RHSTy) &&
  6468. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6469. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6470. return RHSTy;
  6471. }
  6472. // Check constraints for Objective-C object pointers types.
  6473. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6474. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6475. // Two identical object pointer types are always compatible.
  6476. return LHSTy;
  6477. }
  6478. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6479. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6480. QualType compositeType = LHSTy;
  6481. // If both operands are interfaces and either operand can be
  6482. // assigned to the other, use that type as the composite
  6483. // type. This allows
  6484. // xxx ? (A*) a : (B*) b
  6485. // where B is a subclass of A.
  6486. //
  6487. // Additionally, as for assignment, if either type is 'id'
  6488. // allow silent coercion. Finally, if the types are
  6489. // incompatible then make sure to use 'id' as the composite
  6490. // type so the result is acceptable for sending messages to.
  6491. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6492. // It could return the composite type.
  6493. if (!(compositeType =
  6494. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6495. // Nothing more to do.
  6496. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6497. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6498. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6499. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6500. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6501. RHSTy->isObjCQualifiedIdType()) &&
  6502. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6503. // Need to handle "id<xx>" explicitly.
  6504. // GCC allows qualified id and any Objective-C type to devolve to
  6505. // id. Currently localizing to here until clear this should be
  6506. // part of ObjCQualifiedIdTypesAreCompatible.
  6507. compositeType = Context.getObjCIdType();
  6508. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6509. compositeType = Context.getObjCIdType();
  6510. } else {
  6511. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6512. << LHSTy << RHSTy
  6513. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6514. QualType incompatTy = Context.getObjCIdType();
  6515. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6516. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6517. return incompatTy;
  6518. }
  6519. // The object pointer types are compatible.
  6520. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6521. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6522. return compositeType;
  6523. }
  6524. // Check Objective-C object pointer types and 'void *'
  6525. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6526. if (getLangOpts().ObjCAutoRefCount) {
  6527. // ARC forbids the implicit conversion of object pointers to 'void *',
  6528. // so these types are not compatible.
  6529. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6530. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6531. LHS = RHS = true;
  6532. return QualType();
  6533. }
  6534. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6535. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6536. QualType destPointee
  6537. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6538. QualType destType = Context.getPointerType(destPointee);
  6539. // Add qualifiers if necessary.
  6540. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6541. // Promote to void*.
  6542. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6543. return destType;
  6544. }
  6545. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6546. if (getLangOpts().ObjCAutoRefCount) {
  6547. // ARC forbids the implicit conversion of object pointers to 'void *',
  6548. // so these types are not compatible.
  6549. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6550. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6551. LHS = RHS = true;
  6552. return QualType();
  6553. }
  6554. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6555. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6556. QualType destPointee
  6557. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6558. QualType destType = Context.getPointerType(destPointee);
  6559. // Add qualifiers if necessary.
  6560. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6561. // Promote to void*.
  6562. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6563. return destType;
  6564. }
  6565. return QualType();
  6566. }
  6567. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6568. /// ParenRange in parentheses.
  6569. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6570. const PartialDiagnostic &Note,
  6571. SourceRange ParenRange) {
  6572. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6573. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6574. EndLoc.isValid()) {
  6575. Self.Diag(Loc, Note)
  6576. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6577. << FixItHint::CreateInsertion(EndLoc, ")");
  6578. } else {
  6579. // We can't display the parentheses, so just show the bare note.
  6580. Self.Diag(Loc, Note) << ParenRange;
  6581. }
  6582. }
  6583. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6584. return BinaryOperator::isAdditiveOp(Opc) ||
  6585. BinaryOperator::isMultiplicativeOp(Opc) ||
  6586. BinaryOperator::isShiftOp(Opc);
  6587. }
  6588. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6589. /// expression, either using a built-in or overloaded operator,
  6590. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6591. /// expression.
  6592. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6593. Expr **RHSExprs) {
  6594. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6595. E = E->IgnoreImpCasts();
  6596. E = E->IgnoreConversionOperator();
  6597. E = E->IgnoreImpCasts();
  6598. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6599. E = MTE->GetTemporaryExpr();
  6600. E = E->IgnoreImpCasts();
  6601. }
  6602. // Built-in binary operator.
  6603. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6604. if (IsArithmeticOp(OP->getOpcode())) {
  6605. *Opcode = OP->getOpcode();
  6606. *RHSExprs = OP->getRHS();
  6607. return true;
  6608. }
  6609. }
  6610. // Overloaded operator.
  6611. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6612. if (Call->getNumArgs() != 2)
  6613. return false;
  6614. // Make sure this is really a binary operator that is safe to pass into
  6615. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6616. OverloadedOperatorKind OO = Call->getOperator();
  6617. if (OO < OO_Plus || OO > OO_Arrow ||
  6618. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6619. return false;
  6620. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6621. if (IsArithmeticOp(OpKind)) {
  6622. *Opcode = OpKind;
  6623. *RHSExprs = Call->getArg(1);
  6624. return true;
  6625. }
  6626. }
  6627. return false;
  6628. }
  6629. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6630. /// or is a logical expression such as (x==y) which has int type, but is
  6631. /// commonly interpreted as boolean.
  6632. static bool ExprLooksBoolean(Expr *E) {
  6633. E = E->IgnoreParenImpCasts();
  6634. if (E->getType()->isBooleanType())
  6635. return true;
  6636. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6637. return OP->isComparisonOp() || OP->isLogicalOp();
  6638. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6639. return OP->getOpcode() == UO_LNot;
  6640. if (E->getType()->isPointerType())
  6641. return true;
  6642. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6643. // type"s (commonly pointer-to-members)?
  6644. return false;
  6645. }
  6646. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6647. /// and binary operator are mixed in a way that suggests the programmer assumed
  6648. /// the conditional operator has higher precedence, for example:
  6649. /// "int x = a + someBinaryCondition ? 1 : 2".
  6650. static void DiagnoseConditionalPrecedence(Sema &Self,
  6651. SourceLocation OpLoc,
  6652. Expr *Condition,
  6653. Expr *LHSExpr,
  6654. Expr *RHSExpr) {
  6655. BinaryOperatorKind CondOpcode;
  6656. Expr *CondRHS;
  6657. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6658. return;
  6659. if (!ExprLooksBoolean(CondRHS))
  6660. return;
  6661. // The condition is an arithmetic binary expression, with a right-
  6662. // hand side that looks boolean, so warn.
  6663. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6664. << Condition->getSourceRange()
  6665. << BinaryOperator::getOpcodeStr(CondOpcode);
  6666. SuggestParentheses(
  6667. Self, OpLoc,
  6668. Self.PDiag(diag::note_precedence_silence)
  6669. << BinaryOperator::getOpcodeStr(CondOpcode),
  6670. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6671. SuggestParentheses(Self, OpLoc,
  6672. Self.PDiag(diag::note_precedence_conditional_first),
  6673. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6674. }
  6675. /// Compute the nullability of a conditional expression.
  6676. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6677. QualType LHSTy, QualType RHSTy,
  6678. ASTContext &Ctx) {
  6679. if (!ResTy->isAnyPointerType())
  6680. return ResTy;
  6681. auto GetNullability = [&Ctx](QualType Ty) {
  6682. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6683. if (Kind)
  6684. return *Kind;
  6685. return NullabilityKind::Unspecified;
  6686. };
  6687. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6688. NullabilityKind MergedKind;
  6689. // Compute nullability of a binary conditional expression.
  6690. if (IsBin) {
  6691. if (LHSKind == NullabilityKind::NonNull)
  6692. MergedKind = NullabilityKind::NonNull;
  6693. else
  6694. MergedKind = RHSKind;
  6695. // Compute nullability of a normal conditional expression.
  6696. } else {
  6697. if (LHSKind == NullabilityKind::Nullable ||
  6698. RHSKind == NullabilityKind::Nullable)
  6699. MergedKind = NullabilityKind::Nullable;
  6700. else if (LHSKind == NullabilityKind::NonNull)
  6701. MergedKind = RHSKind;
  6702. else if (RHSKind == NullabilityKind::NonNull)
  6703. MergedKind = LHSKind;
  6704. else
  6705. MergedKind = NullabilityKind::Unspecified;
  6706. }
  6707. // Return if ResTy already has the correct nullability.
  6708. if (GetNullability(ResTy) == MergedKind)
  6709. return ResTy;
  6710. // Strip all nullability from ResTy.
  6711. while (ResTy->getNullability(Ctx))
  6712. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6713. // Create a new AttributedType with the new nullability kind.
  6714. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6715. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6716. }
  6717. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6718. /// in the case of a the GNU conditional expr extension.
  6719. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6720. SourceLocation ColonLoc,
  6721. Expr *CondExpr, Expr *LHSExpr,
  6722. Expr *RHSExpr) {
  6723. if (!getLangOpts().CPlusPlus) {
  6724. // C cannot handle TypoExpr nodes in the condition because it
  6725. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6726. // been dealt with before checking the operands.
  6727. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6728. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6729. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6730. if (!CondResult.isUsable())
  6731. return ExprError();
  6732. if (LHSExpr) {
  6733. if (!LHSResult.isUsable())
  6734. return ExprError();
  6735. }
  6736. if (!RHSResult.isUsable())
  6737. return ExprError();
  6738. CondExpr = CondResult.get();
  6739. LHSExpr = LHSResult.get();
  6740. RHSExpr = RHSResult.get();
  6741. }
  6742. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6743. // was the condition.
  6744. OpaqueValueExpr *opaqueValue = nullptr;
  6745. Expr *commonExpr = nullptr;
  6746. if (!LHSExpr) {
  6747. commonExpr = CondExpr;
  6748. // Lower out placeholder types first. This is important so that we don't
  6749. // try to capture a placeholder. This happens in few cases in C++; such
  6750. // as Objective-C++'s dictionary subscripting syntax.
  6751. if (commonExpr->hasPlaceholderType()) {
  6752. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6753. if (!result.isUsable()) return ExprError();
  6754. commonExpr = result.get();
  6755. }
  6756. // We usually want to apply unary conversions *before* saving, except
  6757. // in the special case of a C++ l-value conditional.
  6758. if (!(getLangOpts().CPlusPlus
  6759. && !commonExpr->isTypeDependent()
  6760. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6761. && commonExpr->isGLValue()
  6762. && commonExpr->isOrdinaryOrBitFieldObject()
  6763. && RHSExpr->isOrdinaryOrBitFieldObject()
  6764. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6765. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6766. if (commonRes.isInvalid())
  6767. return ExprError();
  6768. commonExpr = commonRes.get();
  6769. }
  6770. // If the common expression is a class or array prvalue, materialize it
  6771. // so that we can safely refer to it multiple times.
  6772. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6773. commonExpr->getType()->isArrayType())) {
  6774. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6775. if (MatExpr.isInvalid())
  6776. return ExprError();
  6777. commonExpr = MatExpr.get();
  6778. }
  6779. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6780. commonExpr->getType(),
  6781. commonExpr->getValueKind(),
  6782. commonExpr->getObjectKind(),
  6783. commonExpr);
  6784. LHSExpr = CondExpr = opaqueValue;
  6785. }
  6786. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6787. ExprValueKind VK = VK_RValue;
  6788. ExprObjectKind OK = OK_Ordinary;
  6789. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6790. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6791. VK, OK, QuestionLoc);
  6792. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6793. RHS.isInvalid())
  6794. return ExprError();
  6795. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6796. RHS.get());
  6797. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6798. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6799. Context);
  6800. if (!commonExpr)
  6801. return new (Context)
  6802. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6803. RHS.get(), result, VK, OK);
  6804. return new (Context) BinaryConditionalOperator(
  6805. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6806. ColonLoc, result, VK, OK);
  6807. }
  6808. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6809. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6810. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6811. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6812. // FIXME: add a couple examples in this comment.
  6813. static Sema::AssignConvertType
  6814. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6815. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6816. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6817. // get the "pointed to" type (ignoring qualifiers at the top level)
  6818. const Type *lhptee, *rhptee;
  6819. Qualifiers lhq, rhq;
  6820. std::tie(lhptee, lhq) =
  6821. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6822. std::tie(rhptee, rhq) =
  6823. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6824. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6825. // C99 6.5.16.1p1: This following citation is common to constraints
  6826. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6827. // qualifiers of the type *pointed to* by the right;
  6828. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6829. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6830. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6831. // Ignore lifetime for further calculation.
  6832. lhq.removeObjCLifetime();
  6833. rhq.removeObjCLifetime();
  6834. }
  6835. if (!lhq.compatiblyIncludes(rhq)) {
  6836. // Treat address-space mismatches as fatal.
  6837. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6838. return Sema::IncompatiblePointerDiscardsQualifiers;
  6839. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6840. // and from void*.
  6841. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6842. .compatiblyIncludes(
  6843. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6844. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6845. ; // keep old
  6846. // Treat lifetime mismatches as fatal.
  6847. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6848. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6849. // For GCC/MS compatibility, other qualifier mismatches are treated
  6850. // as still compatible in C.
  6851. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6852. }
  6853. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6854. // incomplete type and the other is a pointer to a qualified or unqualified
  6855. // version of void...
  6856. if (lhptee->isVoidType()) {
  6857. if (rhptee->isIncompleteOrObjectType())
  6858. return ConvTy;
  6859. // As an extension, we allow cast to/from void* to function pointer.
  6860. assert(rhptee->isFunctionType());
  6861. return Sema::FunctionVoidPointer;
  6862. }
  6863. if (rhptee->isVoidType()) {
  6864. if (lhptee->isIncompleteOrObjectType())
  6865. return ConvTy;
  6866. // As an extension, we allow cast to/from void* to function pointer.
  6867. assert(lhptee->isFunctionType());
  6868. return Sema::FunctionVoidPointer;
  6869. }
  6870. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6871. // unqualified versions of compatible types, ...
  6872. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6873. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6874. // Check if the pointee types are compatible ignoring the sign.
  6875. // We explicitly check for char so that we catch "char" vs
  6876. // "unsigned char" on systems where "char" is unsigned.
  6877. if (lhptee->isCharType())
  6878. ltrans = S.Context.UnsignedCharTy;
  6879. else if (lhptee->hasSignedIntegerRepresentation())
  6880. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6881. if (rhptee->isCharType())
  6882. rtrans = S.Context.UnsignedCharTy;
  6883. else if (rhptee->hasSignedIntegerRepresentation())
  6884. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6885. if (ltrans == rtrans) {
  6886. // Types are compatible ignoring the sign. Qualifier incompatibility
  6887. // takes priority over sign incompatibility because the sign
  6888. // warning can be disabled.
  6889. if (ConvTy != Sema::Compatible)
  6890. return ConvTy;
  6891. return Sema::IncompatiblePointerSign;
  6892. }
  6893. // If we are a multi-level pointer, it's possible that our issue is simply
  6894. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6895. // the eventual target type is the same and the pointers have the same
  6896. // level of indirection, this must be the issue.
  6897. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6898. do {
  6899. std::tie(lhptee, lhq) =
  6900. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  6901. std::tie(rhptee, rhq) =
  6902. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  6903. // Inconsistent address spaces at this point is invalid, even if the
  6904. // address spaces would be compatible.
  6905. // FIXME: This doesn't catch address space mismatches for pointers of
  6906. // different nesting levels, like:
  6907. // __local int *** a;
  6908. // int ** b = a;
  6909. // It's not clear how to actually determine when such pointers are
  6910. // invalidly incompatible.
  6911. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  6912. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  6913. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6914. if (lhptee == rhptee)
  6915. return Sema::IncompatibleNestedPointerQualifiers;
  6916. }
  6917. // General pointer incompatibility takes priority over qualifiers.
  6918. return Sema::IncompatiblePointer;
  6919. }
  6920. if (!S.getLangOpts().CPlusPlus &&
  6921. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6922. return Sema::IncompatiblePointer;
  6923. return ConvTy;
  6924. }
  6925. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6926. /// block pointer types are compatible or whether a block and normal pointer
  6927. /// are compatible. It is more restrict than comparing two function pointer
  6928. // types.
  6929. static Sema::AssignConvertType
  6930. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6931. QualType RHSType) {
  6932. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6933. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6934. QualType lhptee, rhptee;
  6935. // get the "pointed to" type (ignoring qualifiers at the top level)
  6936. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6937. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6938. // In C++, the types have to match exactly.
  6939. if (S.getLangOpts().CPlusPlus)
  6940. return Sema::IncompatibleBlockPointer;
  6941. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6942. // For blocks we enforce that qualifiers are identical.
  6943. Qualifiers LQuals = lhptee.getLocalQualifiers();
  6944. Qualifiers RQuals = rhptee.getLocalQualifiers();
  6945. if (S.getLangOpts().OpenCL) {
  6946. LQuals.removeAddressSpace();
  6947. RQuals.removeAddressSpace();
  6948. }
  6949. if (LQuals != RQuals)
  6950. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6951. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  6952. // assignment.
  6953. // The current behavior is similar to C++ lambdas. A block might be
  6954. // assigned to a variable iff its return type and parameters are compatible
  6955. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  6956. // an assignment. Presumably it should behave in way that a function pointer
  6957. // assignment does in C, so for each parameter and return type:
  6958. // * CVR and address space of LHS should be a superset of CVR and address
  6959. // space of RHS.
  6960. // * unqualified types should be compatible.
  6961. if (S.getLangOpts().OpenCL) {
  6962. if (!S.Context.typesAreBlockPointerCompatible(
  6963. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  6964. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  6965. return Sema::IncompatibleBlockPointer;
  6966. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6967. return Sema::IncompatibleBlockPointer;
  6968. return ConvTy;
  6969. }
  6970. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6971. /// for assignment compatibility.
  6972. static Sema::AssignConvertType
  6973. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6974. QualType RHSType) {
  6975. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6976. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6977. if (LHSType->isObjCBuiltinType()) {
  6978. // Class is not compatible with ObjC object pointers.
  6979. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6980. !RHSType->isObjCQualifiedClassType())
  6981. return Sema::IncompatiblePointer;
  6982. return Sema::Compatible;
  6983. }
  6984. if (RHSType->isObjCBuiltinType()) {
  6985. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6986. !LHSType->isObjCQualifiedClassType())
  6987. return Sema::IncompatiblePointer;
  6988. return Sema::Compatible;
  6989. }
  6990. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6991. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6992. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6993. // make an exception for id<P>
  6994. !LHSType->isObjCQualifiedIdType())
  6995. return Sema::CompatiblePointerDiscardsQualifiers;
  6996. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6997. return Sema::Compatible;
  6998. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6999. return Sema::IncompatibleObjCQualifiedId;
  7000. return Sema::IncompatiblePointer;
  7001. }
  7002. Sema::AssignConvertType
  7003. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  7004. QualType LHSType, QualType RHSType) {
  7005. // Fake up an opaque expression. We don't actually care about what
  7006. // cast operations are required, so if CheckAssignmentConstraints
  7007. // adds casts to this they'll be wasted, but fortunately that doesn't
  7008. // usually happen on valid code.
  7009. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  7010. ExprResult RHSPtr = &RHSExpr;
  7011. CastKind K;
  7012. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  7013. }
  7014. /// This helper function returns true if QT is a vector type that has element
  7015. /// type ElementType.
  7016. static bool isVector(QualType QT, QualType ElementType) {
  7017. if (const VectorType *VT = QT->getAs<VectorType>())
  7018. return VT->getElementType() == ElementType;
  7019. return false;
  7020. }
  7021. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  7022. /// has code to accommodate several GCC extensions when type checking
  7023. /// pointers. Here are some objectionable examples that GCC considers warnings:
  7024. ///
  7025. /// int a, *pint;
  7026. /// short *pshort;
  7027. /// struct foo *pfoo;
  7028. ///
  7029. /// pint = pshort; // warning: assignment from incompatible pointer type
  7030. /// a = pint; // warning: assignment makes integer from pointer without a cast
  7031. /// pint = a; // warning: assignment makes pointer from integer without a cast
  7032. /// pint = pfoo; // warning: assignment from incompatible pointer type
  7033. ///
  7034. /// As a result, the code for dealing with pointers is more complex than the
  7035. /// C99 spec dictates.
  7036. ///
  7037. /// Sets 'Kind' for any result kind except Incompatible.
  7038. Sema::AssignConvertType
  7039. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  7040. CastKind &Kind, bool ConvertRHS) {
  7041. QualType RHSType = RHS.get()->getType();
  7042. QualType OrigLHSType = LHSType;
  7043. // Get canonical types. We're not formatting these types, just comparing
  7044. // them.
  7045. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  7046. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  7047. // Common case: no conversion required.
  7048. if (LHSType == RHSType) {
  7049. Kind = CK_NoOp;
  7050. return Compatible;
  7051. }
  7052. // If we have an atomic type, try a non-atomic assignment, then just add an
  7053. // atomic qualification step.
  7054. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  7055. Sema::AssignConvertType result =
  7056. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  7057. if (result != Compatible)
  7058. return result;
  7059. if (Kind != CK_NoOp && ConvertRHS)
  7060. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  7061. Kind = CK_NonAtomicToAtomic;
  7062. return Compatible;
  7063. }
  7064. // If the left-hand side is a reference type, then we are in a
  7065. // (rare!) case where we've allowed the use of references in C,
  7066. // e.g., as a parameter type in a built-in function. In this case,
  7067. // just make sure that the type referenced is compatible with the
  7068. // right-hand side type. The caller is responsible for adjusting
  7069. // LHSType so that the resulting expression does not have reference
  7070. // type.
  7071. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7072. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7073. Kind = CK_LValueBitCast;
  7074. return Compatible;
  7075. }
  7076. return Incompatible;
  7077. }
  7078. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7079. // to the same ExtVector type.
  7080. if (LHSType->isExtVectorType()) {
  7081. if (RHSType->isExtVectorType())
  7082. return Incompatible;
  7083. if (RHSType->isArithmeticType()) {
  7084. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7085. if (ConvertRHS)
  7086. RHS = prepareVectorSplat(LHSType, RHS.get());
  7087. Kind = CK_VectorSplat;
  7088. return Compatible;
  7089. }
  7090. }
  7091. // Conversions to or from vector type.
  7092. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7093. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7094. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7095. // vector type and vice versa
  7096. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7097. Kind = CK_BitCast;
  7098. return Compatible;
  7099. }
  7100. // If we are allowing lax vector conversions, and LHS and RHS are both
  7101. // vectors, the total size only needs to be the same. This is a bitcast;
  7102. // no bits are changed but the result type is different.
  7103. if (isLaxVectorConversion(RHSType, LHSType)) {
  7104. Kind = CK_BitCast;
  7105. return IncompatibleVectors;
  7106. }
  7107. }
  7108. // When the RHS comes from another lax conversion (e.g. binops between
  7109. // scalars and vectors) the result is canonicalized as a vector. When the
  7110. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7111. // the case where LHS is a scalar.
  7112. if (LHSType->isScalarType()) {
  7113. const VectorType *VecType = RHSType->getAs<VectorType>();
  7114. if (VecType && VecType->getNumElements() == 1 &&
  7115. isLaxVectorConversion(RHSType, LHSType)) {
  7116. ExprResult *VecExpr = &RHS;
  7117. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7118. Kind = CK_BitCast;
  7119. return Compatible;
  7120. }
  7121. }
  7122. return Incompatible;
  7123. }
  7124. // Diagnose attempts to convert between __float128 and long double where
  7125. // such conversions currently can't be handled.
  7126. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7127. return Incompatible;
  7128. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7129. // discards the imaginary part.
  7130. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7131. !LHSType->getAs<ComplexType>())
  7132. return Incompatible;
  7133. // Arithmetic conversions.
  7134. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7135. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7136. if (ConvertRHS)
  7137. Kind = PrepareScalarCast(RHS, LHSType);
  7138. return Compatible;
  7139. }
  7140. // Conversions to normal pointers.
  7141. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7142. // U* -> T*
  7143. if (isa<PointerType>(RHSType)) {
  7144. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7145. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7146. if (AddrSpaceL != AddrSpaceR)
  7147. Kind = CK_AddressSpaceConversion;
  7148. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7149. Kind = CK_NoOp;
  7150. else
  7151. Kind = CK_BitCast;
  7152. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7153. }
  7154. // int -> T*
  7155. if (RHSType->isIntegerType()) {
  7156. Kind = CK_IntegralToPointer; // FIXME: null?
  7157. return IntToPointer;
  7158. }
  7159. // C pointers are not compatible with ObjC object pointers,
  7160. // with two exceptions:
  7161. if (isa<ObjCObjectPointerType>(RHSType)) {
  7162. // - conversions to void*
  7163. if (LHSPointer->getPointeeType()->isVoidType()) {
  7164. Kind = CK_BitCast;
  7165. return Compatible;
  7166. }
  7167. // - conversions from 'Class' to the redefinition type
  7168. if (RHSType->isObjCClassType() &&
  7169. Context.hasSameType(LHSType,
  7170. Context.getObjCClassRedefinitionType())) {
  7171. Kind = CK_BitCast;
  7172. return Compatible;
  7173. }
  7174. Kind = CK_BitCast;
  7175. return IncompatiblePointer;
  7176. }
  7177. // U^ -> void*
  7178. if (RHSType->getAs<BlockPointerType>()) {
  7179. if (LHSPointer->getPointeeType()->isVoidType()) {
  7180. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7181. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7182. ->getPointeeType()
  7183. .getAddressSpace();
  7184. Kind =
  7185. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7186. return Compatible;
  7187. }
  7188. }
  7189. return Incompatible;
  7190. }
  7191. // Conversions to block pointers.
  7192. if (isa<BlockPointerType>(LHSType)) {
  7193. // U^ -> T^
  7194. if (RHSType->isBlockPointerType()) {
  7195. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7196. ->getPointeeType()
  7197. .getAddressSpace();
  7198. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7199. ->getPointeeType()
  7200. .getAddressSpace();
  7201. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7202. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7203. }
  7204. // int or null -> T^
  7205. if (RHSType->isIntegerType()) {
  7206. Kind = CK_IntegralToPointer; // FIXME: null
  7207. return IntToBlockPointer;
  7208. }
  7209. // id -> T^
  7210. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7211. Kind = CK_AnyPointerToBlockPointerCast;
  7212. return Compatible;
  7213. }
  7214. // void* -> T^
  7215. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7216. if (RHSPT->getPointeeType()->isVoidType()) {
  7217. Kind = CK_AnyPointerToBlockPointerCast;
  7218. return Compatible;
  7219. }
  7220. return Incompatible;
  7221. }
  7222. // Conversions to Objective-C pointers.
  7223. if (isa<ObjCObjectPointerType>(LHSType)) {
  7224. // A* -> B*
  7225. if (RHSType->isObjCObjectPointerType()) {
  7226. Kind = CK_BitCast;
  7227. Sema::AssignConvertType result =
  7228. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7229. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7230. result == Compatible &&
  7231. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7232. result = IncompatibleObjCWeakRef;
  7233. return result;
  7234. }
  7235. // int or null -> A*
  7236. if (RHSType->isIntegerType()) {
  7237. Kind = CK_IntegralToPointer; // FIXME: null
  7238. return IntToPointer;
  7239. }
  7240. // In general, C pointers are not compatible with ObjC object pointers,
  7241. // with two exceptions:
  7242. if (isa<PointerType>(RHSType)) {
  7243. Kind = CK_CPointerToObjCPointerCast;
  7244. // - conversions from 'void*'
  7245. if (RHSType->isVoidPointerType()) {
  7246. return Compatible;
  7247. }
  7248. // - conversions to 'Class' from its redefinition type
  7249. if (LHSType->isObjCClassType() &&
  7250. Context.hasSameType(RHSType,
  7251. Context.getObjCClassRedefinitionType())) {
  7252. return Compatible;
  7253. }
  7254. return IncompatiblePointer;
  7255. }
  7256. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7257. if (RHSType->isBlockPointerType() &&
  7258. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7259. if (ConvertRHS)
  7260. maybeExtendBlockObject(RHS);
  7261. Kind = CK_BlockPointerToObjCPointerCast;
  7262. return Compatible;
  7263. }
  7264. return Incompatible;
  7265. }
  7266. // Conversions from pointers that are not covered by the above.
  7267. if (isa<PointerType>(RHSType)) {
  7268. // T* -> _Bool
  7269. if (LHSType == Context.BoolTy) {
  7270. Kind = CK_PointerToBoolean;
  7271. return Compatible;
  7272. }
  7273. // T* -> int
  7274. if (LHSType->isIntegerType()) {
  7275. Kind = CK_PointerToIntegral;
  7276. return PointerToInt;
  7277. }
  7278. return Incompatible;
  7279. }
  7280. // Conversions from Objective-C pointers that are not covered by the above.
  7281. if (isa<ObjCObjectPointerType>(RHSType)) {
  7282. // T* -> _Bool
  7283. if (LHSType == Context.BoolTy) {
  7284. Kind = CK_PointerToBoolean;
  7285. return Compatible;
  7286. }
  7287. // T* -> int
  7288. if (LHSType->isIntegerType()) {
  7289. Kind = CK_PointerToIntegral;
  7290. return PointerToInt;
  7291. }
  7292. return Incompatible;
  7293. }
  7294. // struct A -> struct B
  7295. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7296. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7297. Kind = CK_NoOp;
  7298. return Compatible;
  7299. }
  7300. }
  7301. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7302. Kind = CK_IntToOCLSampler;
  7303. return Compatible;
  7304. }
  7305. return Incompatible;
  7306. }
  7307. /// Constructs a transparent union from an expression that is
  7308. /// used to initialize the transparent union.
  7309. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7310. ExprResult &EResult, QualType UnionType,
  7311. FieldDecl *Field) {
  7312. // Build an initializer list that designates the appropriate member
  7313. // of the transparent union.
  7314. Expr *E = EResult.get();
  7315. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7316. E, SourceLocation());
  7317. Initializer->setType(UnionType);
  7318. Initializer->setInitializedFieldInUnion(Field);
  7319. // Build a compound literal constructing a value of the transparent
  7320. // union type from this initializer list.
  7321. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7322. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7323. VK_RValue, Initializer, false);
  7324. }
  7325. Sema::AssignConvertType
  7326. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7327. ExprResult &RHS) {
  7328. QualType RHSType = RHS.get()->getType();
  7329. // If the ArgType is a Union type, we want to handle a potential
  7330. // transparent_union GCC extension.
  7331. const RecordType *UT = ArgType->getAsUnionType();
  7332. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7333. return Incompatible;
  7334. // The field to initialize within the transparent union.
  7335. RecordDecl *UD = UT->getDecl();
  7336. FieldDecl *InitField = nullptr;
  7337. // It's compatible if the expression matches any of the fields.
  7338. for (auto *it : UD->fields()) {
  7339. if (it->getType()->isPointerType()) {
  7340. // If the transparent union contains a pointer type, we allow:
  7341. // 1) void pointer
  7342. // 2) null pointer constant
  7343. if (RHSType->isPointerType())
  7344. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7345. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7346. InitField = it;
  7347. break;
  7348. }
  7349. if (RHS.get()->isNullPointerConstant(Context,
  7350. Expr::NPC_ValueDependentIsNull)) {
  7351. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7352. CK_NullToPointer);
  7353. InitField = it;
  7354. break;
  7355. }
  7356. }
  7357. CastKind Kind;
  7358. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7359. == Compatible) {
  7360. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7361. InitField = it;
  7362. break;
  7363. }
  7364. }
  7365. if (!InitField)
  7366. return Incompatible;
  7367. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7368. return Compatible;
  7369. }
  7370. Sema::AssignConvertType
  7371. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7372. bool Diagnose,
  7373. bool DiagnoseCFAudited,
  7374. bool ConvertRHS) {
  7375. // We need to be able to tell the caller whether we diagnosed a problem, if
  7376. // they ask us to issue diagnostics.
  7377. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7378. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7379. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7380. // to put the updated value.
  7381. ExprResult LocalRHS = CallerRHS;
  7382. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7383. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7384. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7385. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7386. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7387. Diag(RHS.get()->getExprLoc(),
  7388. diag::warn_noderef_to_dereferenceable_pointer)
  7389. << RHS.get()->getSourceRange();
  7390. }
  7391. }
  7392. }
  7393. if (getLangOpts().CPlusPlus) {
  7394. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7395. // C++ 5.17p3: If the left operand is not of class type, the
  7396. // expression is implicitly converted (C++ 4) to the
  7397. // cv-unqualified type of the left operand.
  7398. QualType RHSType = RHS.get()->getType();
  7399. if (Diagnose) {
  7400. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7401. AA_Assigning);
  7402. } else {
  7403. ImplicitConversionSequence ICS =
  7404. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7405. /*SuppressUserConversions=*/false,
  7406. /*AllowExplicit=*/false,
  7407. /*InOverloadResolution=*/false,
  7408. /*CStyle=*/false,
  7409. /*AllowObjCWritebackConversion=*/false);
  7410. if (ICS.isFailure())
  7411. return Incompatible;
  7412. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7413. ICS, AA_Assigning);
  7414. }
  7415. if (RHS.isInvalid())
  7416. return Incompatible;
  7417. Sema::AssignConvertType result = Compatible;
  7418. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7419. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7420. result = IncompatibleObjCWeakRef;
  7421. return result;
  7422. }
  7423. // FIXME: Currently, we fall through and treat C++ classes like C
  7424. // structures.
  7425. // FIXME: We also fall through for atomics; not sure what should
  7426. // happen there, though.
  7427. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7428. // As a set of extensions to C, we support overloading on functions. These
  7429. // functions need to be resolved here.
  7430. DeclAccessPair DAP;
  7431. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7432. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7433. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7434. else
  7435. return Incompatible;
  7436. }
  7437. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7438. // a null pointer constant.
  7439. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7440. LHSType->isBlockPointerType()) &&
  7441. RHS.get()->isNullPointerConstant(Context,
  7442. Expr::NPC_ValueDependentIsNull)) {
  7443. if (Diagnose || ConvertRHS) {
  7444. CastKind Kind;
  7445. CXXCastPath Path;
  7446. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7447. /*IgnoreBaseAccess=*/false, Diagnose);
  7448. if (ConvertRHS)
  7449. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7450. }
  7451. return Compatible;
  7452. }
  7453. // OpenCL queue_t type assignment.
  7454. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7455. Context, Expr::NPC_ValueDependentIsNull)) {
  7456. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7457. return Compatible;
  7458. }
  7459. // This check seems unnatural, however it is necessary to ensure the proper
  7460. // conversion of functions/arrays. If the conversion were done for all
  7461. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7462. // expressions that suppress this implicit conversion (&, sizeof).
  7463. //
  7464. // Suppress this for references: C++ 8.5.3p5.
  7465. if (!LHSType->isReferenceType()) {
  7466. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7467. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7468. if (RHS.isInvalid())
  7469. return Incompatible;
  7470. }
  7471. CastKind Kind;
  7472. Sema::AssignConvertType result =
  7473. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7474. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7475. // type of the assignment expression.
  7476. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7477. // so that we can use references in built-in functions even in C.
  7478. // The getNonReferenceType() call makes sure that the resulting expression
  7479. // does not have reference type.
  7480. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7481. QualType Ty = LHSType.getNonLValueExprType(Context);
  7482. Expr *E = RHS.get();
  7483. // Check for various Objective-C errors. If we are not reporting
  7484. // diagnostics and just checking for errors, e.g., during overload
  7485. // resolution, return Incompatible to indicate the failure.
  7486. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7487. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7488. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7489. if (!Diagnose)
  7490. return Incompatible;
  7491. }
  7492. if (getLangOpts().ObjC &&
  7493. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7494. E->getType(), E, Diagnose) ||
  7495. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7496. if (!Diagnose)
  7497. return Incompatible;
  7498. // Replace the expression with a corrected version and continue so we
  7499. // can find further errors.
  7500. RHS = E;
  7501. return Compatible;
  7502. }
  7503. if (ConvertRHS)
  7504. RHS = ImpCastExprToType(E, Ty, Kind);
  7505. }
  7506. return result;
  7507. }
  7508. namespace {
  7509. /// The original operand to an operator, prior to the application of the usual
  7510. /// arithmetic conversions and converting the arguments of a builtin operator
  7511. /// candidate.
  7512. struct OriginalOperand {
  7513. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7514. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7515. Op = MTE->GetTemporaryExpr();
  7516. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7517. Op = BTE->getSubExpr();
  7518. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7519. Orig = ICE->getSubExprAsWritten();
  7520. Conversion = ICE->getConversionFunction();
  7521. }
  7522. }
  7523. QualType getType() const { return Orig->getType(); }
  7524. Expr *Orig;
  7525. NamedDecl *Conversion;
  7526. };
  7527. }
  7528. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7529. ExprResult &RHS) {
  7530. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7531. Diag(Loc, diag::err_typecheck_invalid_operands)
  7532. << OrigLHS.getType() << OrigRHS.getType()
  7533. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7534. // If a user-defined conversion was applied to either of the operands prior
  7535. // to applying the built-in operator rules, tell the user about it.
  7536. if (OrigLHS.Conversion) {
  7537. Diag(OrigLHS.Conversion->getLocation(),
  7538. diag::note_typecheck_invalid_operands_converted)
  7539. << 0 << LHS.get()->getType();
  7540. }
  7541. if (OrigRHS.Conversion) {
  7542. Diag(OrigRHS.Conversion->getLocation(),
  7543. diag::note_typecheck_invalid_operands_converted)
  7544. << 1 << RHS.get()->getType();
  7545. }
  7546. return QualType();
  7547. }
  7548. // Diagnose cases where a scalar was implicitly converted to a vector and
  7549. // diagnose the underlying types. Otherwise, diagnose the error
  7550. // as invalid vector logical operands for non-C++ cases.
  7551. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7552. ExprResult &RHS) {
  7553. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7554. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7555. bool LHSNatVec = LHSType->isVectorType();
  7556. bool RHSNatVec = RHSType->isVectorType();
  7557. if (!(LHSNatVec && RHSNatVec)) {
  7558. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7559. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7560. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7561. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7562. << Vector->getSourceRange();
  7563. return QualType();
  7564. }
  7565. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7566. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7567. << RHS.get()->getSourceRange();
  7568. return QualType();
  7569. }
  7570. /// Try to convert a value of non-vector type to a vector type by converting
  7571. /// the type to the element type of the vector and then performing a splat.
  7572. /// If the language is OpenCL, we only use conversions that promote scalar
  7573. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7574. /// for float->int.
  7575. ///
  7576. /// OpenCL V2.0 6.2.6.p2:
  7577. /// An error shall occur if any scalar operand type has greater rank
  7578. /// than the type of the vector element.
  7579. ///
  7580. /// \param scalar - if non-null, actually perform the conversions
  7581. /// \return true if the operation fails (but without diagnosing the failure)
  7582. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7583. QualType scalarTy,
  7584. QualType vectorEltTy,
  7585. QualType vectorTy,
  7586. unsigned &DiagID) {
  7587. // The conversion to apply to the scalar before splatting it,
  7588. // if necessary.
  7589. CastKind scalarCast = CK_NoOp;
  7590. if (vectorEltTy->isIntegralType(S.Context)) {
  7591. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7592. (scalarTy->isIntegerType() &&
  7593. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7594. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7595. return true;
  7596. }
  7597. if (!scalarTy->isIntegralType(S.Context))
  7598. return true;
  7599. scalarCast = CK_IntegralCast;
  7600. } else if (vectorEltTy->isRealFloatingType()) {
  7601. if (scalarTy->isRealFloatingType()) {
  7602. if (S.getLangOpts().OpenCL &&
  7603. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7604. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7605. return true;
  7606. }
  7607. scalarCast = CK_FloatingCast;
  7608. }
  7609. else if (scalarTy->isIntegralType(S.Context))
  7610. scalarCast = CK_IntegralToFloating;
  7611. else
  7612. return true;
  7613. } else {
  7614. return true;
  7615. }
  7616. // Adjust scalar if desired.
  7617. if (scalar) {
  7618. if (scalarCast != CK_NoOp)
  7619. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7620. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7621. }
  7622. return false;
  7623. }
  7624. /// Convert vector E to a vector with the same number of elements but different
  7625. /// element type.
  7626. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7627. const auto *VecTy = E->getType()->getAs<VectorType>();
  7628. assert(VecTy && "Expression E must be a vector");
  7629. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7630. VecTy->getNumElements(),
  7631. VecTy->getVectorKind());
  7632. // Look through the implicit cast. Return the subexpression if its type is
  7633. // NewVecTy.
  7634. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7635. if (ICE->getSubExpr()->getType() == NewVecTy)
  7636. return ICE->getSubExpr();
  7637. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7638. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7639. }
  7640. /// Test if a (constant) integer Int can be casted to another integer type
  7641. /// IntTy without losing precision.
  7642. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7643. QualType OtherIntTy) {
  7644. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7645. // Reject cases where the value of the Int is unknown as that would
  7646. // possibly cause truncation, but accept cases where the scalar can be
  7647. // demoted without loss of precision.
  7648. Expr::EvalResult EVResult;
  7649. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7650. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7651. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7652. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7653. if (CstInt) {
  7654. // If the scalar is constant and is of a higher order and has more active
  7655. // bits that the vector element type, reject it.
  7656. llvm::APSInt Result = EVResult.Val.getInt();
  7657. unsigned NumBits = IntSigned
  7658. ? (Result.isNegative() ? Result.getMinSignedBits()
  7659. : Result.getActiveBits())
  7660. : Result.getActiveBits();
  7661. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7662. return true;
  7663. // If the signedness of the scalar type and the vector element type
  7664. // differs and the number of bits is greater than that of the vector
  7665. // element reject it.
  7666. return (IntSigned != OtherIntSigned &&
  7667. NumBits > S.Context.getIntWidth(OtherIntTy));
  7668. }
  7669. // Reject cases where the value of the scalar is not constant and it's
  7670. // order is greater than that of the vector element type.
  7671. return (Order < 0);
  7672. }
  7673. /// Test if a (constant) integer Int can be casted to floating point type
  7674. /// FloatTy without losing precision.
  7675. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7676. QualType FloatTy) {
  7677. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7678. // Determine if the integer constant can be expressed as a floating point
  7679. // number of the appropriate type.
  7680. Expr::EvalResult EVResult;
  7681. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7682. uint64_t Bits = 0;
  7683. if (CstInt) {
  7684. // Reject constants that would be truncated if they were converted to
  7685. // the floating point type. Test by simple to/from conversion.
  7686. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7687. // could be avoided if there was a convertFromAPInt method
  7688. // which could signal back if implicit truncation occurred.
  7689. llvm::APSInt Result = EVResult.Val.getInt();
  7690. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7691. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7692. llvm::APFloat::rmTowardZero);
  7693. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7694. !IntTy->hasSignedIntegerRepresentation());
  7695. bool Ignored = false;
  7696. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7697. &Ignored);
  7698. if (Result != ConvertBack)
  7699. return true;
  7700. } else {
  7701. // Reject types that cannot be fully encoded into the mantissa of
  7702. // the float.
  7703. Bits = S.Context.getTypeSize(IntTy);
  7704. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7705. S.Context.getFloatTypeSemantics(FloatTy));
  7706. if (Bits > FloatPrec)
  7707. return true;
  7708. }
  7709. return false;
  7710. }
  7711. /// Attempt to convert and splat Scalar into a vector whose types matches
  7712. /// Vector following GCC conversion rules. The rule is that implicit
  7713. /// conversion can occur when Scalar can be casted to match Vector's element
  7714. /// type without causing truncation of Scalar.
  7715. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7716. ExprResult *Vector) {
  7717. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7718. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7719. const VectorType *VT = VectorTy->getAs<VectorType>();
  7720. assert(!isa<ExtVectorType>(VT) &&
  7721. "ExtVectorTypes should not be handled here!");
  7722. QualType VectorEltTy = VT->getElementType();
  7723. // Reject cases where the vector element type or the scalar element type are
  7724. // not integral or floating point types.
  7725. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7726. return true;
  7727. // The conversion to apply to the scalar before splatting it,
  7728. // if necessary.
  7729. CastKind ScalarCast = CK_NoOp;
  7730. // Accept cases where the vector elements are integers and the scalar is
  7731. // an integer.
  7732. // FIXME: Notionally if the scalar was a floating point value with a precise
  7733. // integral representation, we could cast it to an appropriate integer
  7734. // type and then perform the rest of the checks here. GCC will perform
  7735. // this conversion in some cases as determined by the input language.
  7736. // We should accept it on a language independent basis.
  7737. if (VectorEltTy->isIntegralType(S.Context) &&
  7738. ScalarTy->isIntegralType(S.Context) &&
  7739. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7740. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7741. return true;
  7742. ScalarCast = CK_IntegralCast;
  7743. } else if (VectorEltTy->isRealFloatingType()) {
  7744. if (ScalarTy->isRealFloatingType()) {
  7745. // Reject cases where the scalar type is not a constant and has a higher
  7746. // Order than the vector element type.
  7747. llvm::APFloat Result(0.0);
  7748. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7749. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7750. if (!CstScalar && Order < 0)
  7751. return true;
  7752. // If the scalar cannot be safely casted to the vector element type,
  7753. // reject it.
  7754. if (CstScalar) {
  7755. bool Truncated = false;
  7756. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7757. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7758. if (Truncated)
  7759. return true;
  7760. }
  7761. ScalarCast = CK_FloatingCast;
  7762. } else if (ScalarTy->isIntegralType(S.Context)) {
  7763. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7764. return true;
  7765. ScalarCast = CK_IntegralToFloating;
  7766. } else
  7767. return true;
  7768. }
  7769. // Adjust scalar if desired.
  7770. if (Scalar) {
  7771. if (ScalarCast != CK_NoOp)
  7772. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7773. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7774. }
  7775. return false;
  7776. }
  7777. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7778. SourceLocation Loc, bool IsCompAssign,
  7779. bool AllowBothBool,
  7780. bool AllowBoolConversions) {
  7781. if (!IsCompAssign) {
  7782. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7783. if (LHS.isInvalid())
  7784. return QualType();
  7785. }
  7786. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7787. if (RHS.isInvalid())
  7788. return QualType();
  7789. // For conversion purposes, we ignore any qualifiers.
  7790. // For example, "const float" and "float" are equivalent.
  7791. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7792. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7793. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7794. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7795. assert(LHSVecType || RHSVecType);
  7796. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7797. // for some operators but not others.
  7798. if (!AllowBothBool &&
  7799. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7800. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7801. return InvalidOperands(Loc, LHS, RHS);
  7802. // If the vector types are identical, return.
  7803. if (Context.hasSameType(LHSType, RHSType))
  7804. return LHSType;
  7805. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7806. if (LHSVecType && RHSVecType &&
  7807. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7808. if (isa<ExtVectorType>(LHSVecType)) {
  7809. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7810. return LHSType;
  7811. }
  7812. if (!IsCompAssign)
  7813. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7814. return RHSType;
  7815. }
  7816. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7817. // can be mixed, with the result being the non-bool type. The non-bool
  7818. // operand must have integer element type.
  7819. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7820. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7821. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7822. Context.getTypeSize(RHSVecType->getElementType()))) {
  7823. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7824. LHSVecType->getElementType()->isIntegerType() &&
  7825. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7826. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7827. return LHSType;
  7828. }
  7829. if (!IsCompAssign &&
  7830. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7831. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7832. RHSVecType->getElementType()->isIntegerType()) {
  7833. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7834. return RHSType;
  7835. }
  7836. }
  7837. // If there's a vector type and a scalar, try to convert the scalar to
  7838. // the vector element type and splat.
  7839. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7840. if (!RHSVecType) {
  7841. if (isa<ExtVectorType>(LHSVecType)) {
  7842. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7843. LHSVecType->getElementType(), LHSType,
  7844. DiagID))
  7845. return LHSType;
  7846. } else {
  7847. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7848. return LHSType;
  7849. }
  7850. }
  7851. if (!LHSVecType) {
  7852. if (isa<ExtVectorType>(RHSVecType)) {
  7853. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7854. LHSType, RHSVecType->getElementType(),
  7855. RHSType, DiagID))
  7856. return RHSType;
  7857. } else {
  7858. if (LHS.get()->getValueKind() == VK_LValue ||
  7859. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7860. return RHSType;
  7861. }
  7862. }
  7863. // FIXME: The code below also handles conversion between vectors and
  7864. // non-scalars, we should break this down into fine grained specific checks
  7865. // and emit proper diagnostics.
  7866. QualType VecType = LHSVecType ? LHSType : RHSType;
  7867. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7868. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7869. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7870. if (isLaxVectorConversion(OtherType, VecType)) {
  7871. // If we're allowing lax vector conversions, only the total (data) size
  7872. // needs to be the same. For non compound assignment, if one of the types is
  7873. // scalar, the result is always the vector type.
  7874. if (!IsCompAssign) {
  7875. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7876. return VecType;
  7877. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7878. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7879. // type. Note that this is already done by non-compound assignments in
  7880. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7881. // <1 x T> -> T. The result is also a vector type.
  7882. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7883. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7884. ExprResult *RHSExpr = &RHS;
  7885. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7886. return VecType;
  7887. }
  7888. }
  7889. // Okay, the expression is invalid.
  7890. // If there's a non-vector, non-real operand, diagnose that.
  7891. if ((!RHSVecType && !RHSType->isRealType()) ||
  7892. (!LHSVecType && !LHSType->isRealType())) {
  7893. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7894. << LHSType << RHSType
  7895. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7896. return QualType();
  7897. }
  7898. // OpenCL V1.1 6.2.6.p1:
  7899. // If the operands are of more than one vector type, then an error shall
  7900. // occur. Implicit conversions between vector types are not permitted, per
  7901. // section 6.2.1.
  7902. if (getLangOpts().OpenCL &&
  7903. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7904. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7905. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7906. << RHSType;
  7907. return QualType();
  7908. }
  7909. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7910. // this point if scalar could not be converted to the vector's element type
  7911. // without truncation.
  7912. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7913. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7914. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7915. QualType Vector = LHSVecType ? LHSType : RHSType;
  7916. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7917. Diag(Loc,
  7918. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7919. << ScalarOrVector << Scalar << Vector;
  7920. return QualType();
  7921. }
  7922. // Otherwise, use the generic diagnostic.
  7923. Diag(Loc, DiagID)
  7924. << LHSType << RHSType
  7925. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7926. return QualType();
  7927. }
  7928. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7929. // expression. These are mainly cases where the null pointer is used as an
  7930. // integer instead of a pointer.
  7931. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7932. SourceLocation Loc, bool IsCompare) {
  7933. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7934. // but we use a bit of a hack here for speed; this is a relatively
  7935. // hot path, and isNullPointerConstant is slow.
  7936. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  7937. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  7938. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  7939. // Avoid analyzing cases where the result will either be invalid (and
  7940. // diagnosed as such) or entirely valid and not something to warn about.
  7941. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  7942. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  7943. return;
  7944. // Comparison operations would not make sense with a null pointer no matter
  7945. // what the other expression is.
  7946. if (!IsCompare) {
  7947. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  7948. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  7949. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  7950. return;
  7951. }
  7952. // The rest of the operations only make sense with a null pointer
  7953. // if the other expression is a pointer.
  7954. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  7955. NonNullType->canDecayToPointerType())
  7956. return;
  7957. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  7958. << LHSNull /* LHS is NULL */ << NonNullType
  7959. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7960. }
  7961. static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
  7962. SourceLocation Loc) {
  7963. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  7964. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  7965. if (!LUE || !RUE)
  7966. return;
  7967. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  7968. RUE->getKind() != UETT_SizeOf)
  7969. return;
  7970. QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
  7971. QualType RHSTy;
  7972. if (RUE->isArgumentType())
  7973. RHSTy = RUE->getArgumentType();
  7974. else
  7975. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  7976. if (!LHSTy->isPointerType() || RHSTy->isPointerType())
  7977. return;
  7978. if (LHSTy->getPointeeType() != RHSTy)
  7979. return;
  7980. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  7981. }
  7982. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  7983. ExprResult &RHS,
  7984. SourceLocation Loc, bool IsDiv) {
  7985. // Check for division/remainder by zero.
  7986. Expr::EvalResult RHSValue;
  7987. if (!RHS.get()->isValueDependent() &&
  7988. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  7989. RHSValue.Val.getInt() == 0)
  7990. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7991. S.PDiag(diag::warn_remainder_division_by_zero)
  7992. << IsDiv << RHS.get()->getSourceRange());
  7993. }
  7994. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  7995. SourceLocation Loc,
  7996. bool IsCompAssign, bool IsDiv) {
  7997. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  7998. if (LHS.get()->getType()->isVectorType() ||
  7999. RHS.get()->getType()->isVectorType())
  8000. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8001. /*AllowBothBool*/getLangOpts().AltiVec,
  8002. /*AllowBoolConversions*/false);
  8003. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8004. if (LHS.isInvalid() || RHS.isInvalid())
  8005. return QualType();
  8006. if (compType.isNull() || !compType->isArithmeticType())
  8007. return InvalidOperands(Loc, LHS, RHS);
  8008. if (IsDiv) {
  8009. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  8010. DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
  8011. }
  8012. return compType;
  8013. }
  8014. QualType Sema::CheckRemainderOperands(
  8015. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  8016. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8017. if (LHS.get()->getType()->isVectorType() ||
  8018. RHS.get()->getType()->isVectorType()) {
  8019. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8020. RHS.get()->getType()->hasIntegerRepresentation())
  8021. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8022. /*AllowBothBool*/getLangOpts().AltiVec,
  8023. /*AllowBoolConversions*/false);
  8024. return InvalidOperands(Loc, LHS, RHS);
  8025. }
  8026. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8027. if (LHS.isInvalid() || RHS.isInvalid())
  8028. return QualType();
  8029. if (compType.isNull() || !compType->isIntegerType())
  8030. return InvalidOperands(Loc, LHS, RHS);
  8031. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  8032. return compType;
  8033. }
  8034. /// Diagnose invalid arithmetic on two void pointers.
  8035. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  8036. Expr *LHSExpr, Expr *RHSExpr) {
  8037. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8038. ? diag::err_typecheck_pointer_arith_void_type
  8039. : diag::ext_gnu_void_ptr)
  8040. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  8041. << RHSExpr->getSourceRange();
  8042. }
  8043. /// Diagnose invalid arithmetic on a void pointer.
  8044. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  8045. Expr *Pointer) {
  8046. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8047. ? diag::err_typecheck_pointer_arith_void_type
  8048. : diag::ext_gnu_void_ptr)
  8049. << 0 /* one pointer */ << Pointer->getSourceRange();
  8050. }
  8051. /// Diagnose invalid arithmetic on a null pointer.
  8052. ///
  8053. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  8054. /// idiom, which we recognize as a GNU extension.
  8055. ///
  8056. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  8057. Expr *Pointer, bool IsGNUIdiom) {
  8058. if (IsGNUIdiom)
  8059. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  8060. << Pointer->getSourceRange();
  8061. else
  8062. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8063. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8064. }
  8065. /// Diagnose invalid arithmetic on two function pointers.
  8066. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8067. Expr *LHS, Expr *RHS) {
  8068. assert(LHS->getType()->isAnyPointerType());
  8069. assert(RHS->getType()->isAnyPointerType());
  8070. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8071. ? diag::err_typecheck_pointer_arith_function_type
  8072. : diag::ext_gnu_ptr_func_arith)
  8073. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8074. // We only show the second type if it differs from the first.
  8075. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8076. RHS->getType())
  8077. << RHS->getType()->getPointeeType()
  8078. << LHS->getSourceRange() << RHS->getSourceRange();
  8079. }
  8080. /// Diagnose invalid arithmetic on a function pointer.
  8081. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8082. Expr *Pointer) {
  8083. assert(Pointer->getType()->isAnyPointerType());
  8084. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8085. ? diag::err_typecheck_pointer_arith_function_type
  8086. : diag::ext_gnu_ptr_func_arith)
  8087. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8088. << 0 /* one pointer, so only one type */
  8089. << Pointer->getSourceRange();
  8090. }
  8091. /// Emit error if Operand is incomplete pointer type
  8092. ///
  8093. /// \returns True if pointer has incomplete type
  8094. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8095. Expr *Operand) {
  8096. QualType ResType = Operand->getType();
  8097. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8098. ResType = ResAtomicType->getValueType();
  8099. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8100. QualType PointeeTy = ResType->getPointeeType();
  8101. return S.RequireCompleteType(Loc, PointeeTy,
  8102. diag::err_typecheck_arithmetic_incomplete_type,
  8103. PointeeTy, Operand->getSourceRange());
  8104. }
  8105. /// Check the validity of an arithmetic pointer operand.
  8106. ///
  8107. /// If the operand has pointer type, this code will check for pointer types
  8108. /// which are invalid in arithmetic operations. These will be diagnosed
  8109. /// appropriately, including whether or not the use is supported as an
  8110. /// extension.
  8111. ///
  8112. /// \returns True when the operand is valid to use (even if as an extension).
  8113. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8114. Expr *Operand) {
  8115. QualType ResType = Operand->getType();
  8116. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8117. ResType = ResAtomicType->getValueType();
  8118. if (!ResType->isAnyPointerType()) return true;
  8119. QualType PointeeTy = ResType->getPointeeType();
  8120. if (PointeeTy->isVoidType()) {
  8121. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8122. return !S.getLangOpts().CPlusPlus;
  8123. }
  8124. if (PointeeTy->isFunctionType()) {
  8125. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8126. return !S.getLangOpts().CPlusPlus;
  8127. }
  8128. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8129. return true;
  8130. }
  8131. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8132. /// operands.
  8133. ///
  8134. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8135. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8136. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8137. /// are (potentially problematic) pointers.
  8138. ///
  8139. /// \returns True when the operand is valid to use (even if as an extension).
  8140. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8141. Expr *LHSExpr, Expr *RHSExpr) {
  8142. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8143. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8144. if (!isLHSPointer && !isRHSPointer) return true;
  8145. QualType LHSPointeeTy, RHSPointeeTy;
  8146. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8147. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8148. // if both are pointers check if operation is valid wrt address spaces
  8149. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8150. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  8151. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  8152. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8153. S.Diag(Loc,
  8154. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8155. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8156. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8157. return false;
  8158. }
  8159. }
  8160. // Check for arithmetic on pointers to incomplete types.
  8161. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8162. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8163. if (isLHSVoidPtr || isRHSVoidPtr) {
  8164. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8165. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8166. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8167. return !S.getLangOpts().CPlusPlus;
  8168. }
  8169. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8170. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8171. if (isLHSFuncPtr || isRHSFuncPtr) {
  8172. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8173. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8174. RHSExpr);
  8175. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8176. return !S.getLangOpts().CPlusPlus;
  8177. }
  8178. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8179. return false;
  8180. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8181. return false;
  8182. return true;
  8183. }
  8184. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8185. /// literal.
  8186. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8187. Expr *LHSExpr, Expr *RHSExpr) {
  8188. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8189. Expr* IndexExpr = RHSExpr;
  8190. if (!StrExpr) {
  8191. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8192. IndexExpr = LHSExpr;
  8193. }
  8194. bool IsStringPlusInt = StrExpr &&
  8195. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8196. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8197. return;
  8198. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8199. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8200. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8201. // Only print a fixit for "str" + int, not for int + "str".
  8202. if (IndexExpr == RHSExpr) {
  8203. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8204. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8205. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8206. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8207. << FixItHint::CreateInsertion(EndLoc, "]");
  8208. } else
  8209. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8210. }
  8211. /// Emit a warning when adding a char literal to a string.
  8212. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8213. Expr *LHSExpr, Expr *RHSExpr) {
  8214. const Expr *StringRefExpr = LHSExpr;
  8215. const CharacterLiteral *CharExpr =
  8216. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8217. if (!CharExpr) {
  8218. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8219. StringRefExpr = RHSExpr;
  8220. }
  8221. if (!CharExpr || !StringRefExpr)
  8222. return;
  8223. const QualType StringType = StringRefExpr->getType();
  8224. // Return if not a PointerType.
  8225. if (!StringType->isAnyPointerType())
  8226. return;
  8227. // Return if not a CharacterType.
  8228. if (!StringType->getPointeeType()->isAnyCharacterType())
  8229. return;
  8230. ASTContext &Ctx = Self.getASTContext();
  8231. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8232. const QualType CharType = CharExpr->getType();
  8233. if (!CharType->isAnyCharacterType() &&
  8234. CharType->isIntegerType() &&
  8235. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8236. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8237. << DiagRange << Ctx.CharTy;
  8238. } else {
  8239. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8240. << DiagRange << CharExpr->getType();
  8241. }
  8242. // Only print a fixit for str + char, not for char + str.
  8243. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8244. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8245. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8246. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8247. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8248. << FixItHint::CreateInsertion(EndLoc, "]");
  8249. } else {
  8250. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8251. }
  8252. }
  8253. /// Emit error when two pointers are incompatible.
  8254. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8255. Expr *LHSExpr, Expr *RHSExpr) {
  8256. assert(LHSExpr->getType()->isAnyPointerType());
  8257. assert(RHSExpr->getType()->isAnyPointerType());
  8258. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8259. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8260. << RHSExpr->getSourceRange();
  8261. }
  8262. // C99 6.5.6
  8263. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8264. SourceLocation Loc, BinaryOperatorKind Opc,
  8265. QualType* CompLHSTy) {
  8266. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8267. if (LHS.get()->getType()->isVectorType() ||
  8268. RHS.get()->getType()->isVectorType()) {
  8269. QualType compType = CheckVectorOperands(
  8270. LHS, RHS, Loc, CompLHSTy,
  8271. /*AllowBothBool*/getLangOpts().AltiVec,
  8272. /*AllowBoolConversions*/getLangOpts().ZVector);
  8273. if (CompLHSTy) *CompLHSTy = compType;
  8274. return compType;
  8275. }
  8276. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8277. if (LHS.isInvalid() || RHS.isInvalid())
  8278. return QualType();
  8279. // Diagnose "string literal" '+' int and string '+' "char literal".
  8280. if (Opc == BO_Add) {
  8281. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8282. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8283. }
  8284. // handle the common case first (both operands are arithmetic).
  8285. if (!compType.isNull() && compType->isArithmeticType()) {
  8286. if (CompLHSTy) *CompLHSTy = compType;
  8287. return compType;
  8288. }
  8289. // Type-checking. Ultimately the pointer's going to be in PExp;
  8290. // note that we bias towards the LHS being the pointer.
  8291. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8292. bool isObjCPointer;
  8293. if (PExp->getType()->isPointerType()) {
  8294. isObjCPointer = false;
  8295. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8296. isObjCPointer = true;
  8297. } else {
  8298. std::swap(PExp, IExp);
  8299. if (PExp->getType()->isPointerType()) {
  8300. isObjCPointer = false;
  8301. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8302. isObjCPointer = true;
  8303. } else {
  8304. return InvalidOperands(Loc, LHS, RHS);
  8305. }
  8306. }
  8307. assert(PExp->getType()->isAnyPointerType());
  8308. if (!IExp->getType()->isIntegerType())
  8309. return InvalidOperands(Loc, LHS, RHS);
  8310. // Adding to a null pointer results in undefined behavior.
  8311. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8312. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8313. // In C++ adding zero to a null pointer is defined.
  8314. Expr::EvalResult KnownVal;
  8315. if (!getLangOpts().CPlusPlus ||
  8316. (!IExp->isValueDependent() &&
  8317. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8318. KnownVal.Val.getInt() != 0))) {
  8319. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8320. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8321. Context, BO_Add, PExp, IExp);
  8322. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8323. }
  8324. }
  8325. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8326. return QualType();
  8327. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8328. return QualType();
  8329. // Check array bounds for pointer arithemtic
  8330. CheckArrayAccess(PExp, IExp);
  8331. if (CompLHSTy) {
  8332. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8333. if (LHSTy.isNull()) {
  8334. LHSTy = LHS.get()->getType();
  8335. if (LHSTy->isPromotableIntegerType())
  8336. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8337. }
  8338. *CompLHSTy = LHSTy;
  8339. }
  8340. return PExp->getType();
  8341. }
  8342. // C99 6.5.6
  8343. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8344. SourceLocation Loc,
  8345. QualType* CompLHSTy) {
  8346. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8347. if (LHS.get()->getType()->isVectorType() ||
  8348. RHS.get()->getType()->isVectorType()) {
  8349. QualType compType = CheckVectorOperands(
  8350. LHS, RHS, Loc, CompLHSTy,
  8351. /*AllowBothBool*/getLangOpts().AltiVec,
  8352. /*AllowBoolConversions*/getLangOpts().ZVector);
  8353. if (CompLHSTy) *CompLHSTy = compType;
  8354. return compType;
  8355. }
  8356. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8357. if (LHS.isInvalid() || RHS.isInvalid())
  8358. return QualType();
  8359. // Enforce type constraints: C99 6.5.6p3.
  8360. // Handle the common case first (both operands are arithmetic).
  8361. if (!compType.isNull() && compType->isArithmeticType()) {
  8362. if (CompLHSTy) *CompLHSTy = compType;
  8363. return compType;
  8364. }
  8365. // Either ptr - int or ptr - ptr.
  8366. if (LHS.get()->getType()->isAnyPointerType()) {
  8367. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8368. // Diagnose bad cases where we step over interface counts.
  8369. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8370. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8371. return QualType();
  8372. // The result type of a pointer-int computation is the pointer type.
  8373. if (RHS.get()->getType()->isIntegerType()) {
  8374. // Subtracting from a null pointer should produce a warning.
  8375. // The last argument to the diagnose call says this doesn't match the
  8376. // GNU int-to-pointer idiom.
  8377. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8378. Expr::NPC_ValueDependentIsNotNull)) {
  8379. // In C++ adding zero to a null pointer is defined.
  8380. Expr::EvalResult KnownVal;
  8381. if (!getLangOpts().CPlusPlus ||
  8382. (!RHS.get()->isValueDependent() &&
  8383. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8384. KnownVal.Val.getInt() != 0))) {
  8385. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8386. }
  8387. }
  8388. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8389. return QualType();
  8390. // Check array bounds for pointer arithemtic
  8391. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8392. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8393. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8394. return LHS.get()->getType();
  8395. }
  8396. // Handle pointer-pointer subtractions.
  8397. if (const PointerType *RHSPTy
  8398. = RHS.get()->getType()->getAs<PointerType>()) {
  8399. QualType rpointee = RHSPTy->getPointeeType();
  8400. if (getLangOpts().CPlusPlus) {
  8401. // Pointee types must be the same: C++ [expr.add]
  8402. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8403. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8404. }
  8405. } else {
  8406. // Pointee types must be compatible C99 6.5.6p3
  8407. if (!Context.typesAreCompatible(
  8408. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8409. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8410. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8411. return QualType();
  8412. }
  8413. }
  8414. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8415. LHS.get(), RHS.get()))
  8416. return QualType();
  8417. // FIXME: Add warnings for nullptr - ptr.
  8418. // The pointee type may have zero size. As an extension, a structure or
  8419. // union may have zero size or an array may have zero length. In this
  8420. // case subtraction does not make sense.
  8421. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8422. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8423. if (ElementSize.isZero()) {
  8424. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8425. << rpointee.getUnqualifiedType()
  8426. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8427. }
  8428. }
  8429. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8430. return Context.getPointerDiffType();
  8431. }
  8432. }
  8433. return InvalidOperands(Loc, LHS, RHS);
  8434. }
  8435. static bool isScopedEnumerationType(QualType T) {
  8436. if (const EnumType *ET = T->getAs<EnumType>())
  8437. return ET->getDecl()->isScoped();
  8438. return false;
  8439. }
  8440. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8441. SourceLocation Loc, BinaryOperatorKind Opc,
  8442. QualType LHSType) {
  8443. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8444. // so skip remaining warnings as we don't want to modify values within Sema.
  8445. if (S.getLangOpts().OpenCL)
  8446. return;
  8447. // Check right/shifter operand
  8448. Expr::EvalResult RHSResult;
  8449. if (RHS.get()->isValueDependent() ||
  8450. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8451. return;
  8452. llvm::APSInt Right = RHSResult.Val.getInt();
  8453. if (Right.isNegative()) {
  8454. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8455. S.PDiag(diag::warn_shift_negative)
  8456. << RHS.get()->getSourceRange());
  8457. return;
  8458. }
  8459. llvm::APInt LeftBits(Right.getBitWidth(),
  8460. S.Context.getTypeSize(LHS.get()->getType()));
  8461. if (Right.uge(LeftBits)) {
  8462. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8463. S.PDiag(diag::warn_shift_gt_typewidth)
  8464. << RHS.get()->getSourceRange());
  8465. return;
  8466. }
  8467. if (Opc != BO_Shl)
  8468. return;
  8469. // When left shifting an ICE which is signed, we can check for overflow which
  8470. // according to C++ standards prior to C++2a has undefined behavior
  8471. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  8472. // more than the maximum value representable in the result type, so never
  8473. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  8474. // expression is still probably a bug.)
  8475. Expr::EvalResult LHSResult;
  8476. if (LHS.get()->isValueDependent() ||
  8477. LHSType->hasUnsignedIntegerRepresentation() ||
  8478. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8479. return;
  8480. llvm::APSInt Left = LHSResult.Val.getInt();
  8481. // If LHS does not have a signed type and non-negative value
  8482. // then, the behavior is undefined before C++2a. Warn about it.
  8483. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  8484. !S.getLangOpts().CPlusPlus2a) {
  8485. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8486. S.PDiag(diag::warn_shift_lhs_negative)
  8487. << LHS.get()->getSourceRange());
  8488. return;
  8489. }
  8490. llvm::APInt ResultBits =
  8491. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8492. if (LeftBits.uge(ResultBits))
  8493. return;
  8494. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8495. Result = Result.shl(Right);
  8496. // Print the bit representation of the signed integer as an unsigned
  8497. // hexadecimal number.
  8498. SmallString<40> HexResult;
  8499. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8500. // If we are only missing a sign bit, this is less likely to result in actual
  8501. // bugs -- if the result is cast back to an unsigned type, it will have the
  8502. // expected value. Thus we place this behind a different warning that can be
  8503. // turned off separately if needed.
  8504. if (LeftBits == ResultBits - 1) {
  8505. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8506. << HexResult << LHSType
  8507. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8508. return;
  8509. }
  8510. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8511. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8512. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8513. << RHS.get()->getSourceRange();
  8514. }
  8515. /// Return the resulting type when a vector is shifted
  8516. /// by a scalar or vector shift amount.
  8517. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8518. SourceLocation Loc, bool IsCompAssign) {
  8519. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8520. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8521. !LHS.get()->getType()->isVectorType()) {
  8522. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8523. << RHS.get()->getType() << LHS.get()->getType()
  8524. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8525. return QualType();
  8526. }
  8527. if (!IsCompAssign) {
  8528. LHS = S.UsualUnaryConversions(LHS.get());
  8529. if (LHS.isInvalid()) return QualType();
  8530. }
  8531. RHS = S.UsualUnaryConversions(RHS.get());
  8532. if (RHS.isInvalid()) return QualType();
  8533. QualType LHSType = LHS.get()->getType();
  8534. // Note that LHS might be a scalar because the routine calls not only in
  8535. // OpenCL case.
  8536. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8537. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8538. // Note that RHS might not be a vector.
  8539. QualType RHSType = RHS.get()->getType();
  8540. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8541. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8542. // The operands need to be integers.
  8543. if (!LHSEleType->isIntegerType()) {
  8544. S.Diag(Loc, diag::err_typecheck_expect_int)
  8545. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8546. return QualType();
  8547. }
  8548. if (!RHSEleType->isIntegerType()) {
  8549. S.Diag(Loc, diag::err_typecheck_expect_int)
  8550. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8551. return QualType();
  8552. }
  8553. if (!LHSVecTy) {
  8554. assert(RHSVecTy);
  8555. if (IsCompAssign)
  8556. return RHSType;
  8557. if (LHSEleType != RHSEleType) {
  8558. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8559. LHSEleType = RHSEleType;
  8560. }
  8561. QualType VecTy =
  8562. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8563. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8564. LHSType = VecTy;
  8565. } else if (RHSVecTy) {
  8566. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8567. // are applied component-wise. So if RHS is a vector, then ensure
  8568. // that the number of elements is the same as LHS...
  8569. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8570. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8571. << LHS.get()->getType() << RHS.get()->getType()
  8572. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8573. return QualType();
  8574. }
  8575. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8576. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8577. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8578. if (LHSBT != RHSBT &&
  8579. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8580. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8581. << LHS.get()->getType() << RHS.get()->getType()
  8582. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8583. }
  8584. }
  8585. } else {
  8586. // ...else expand RHS to match the number of elements in LHS.
  8587. QualType VecTy =
  8588. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8589. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8590. }
  8591. return LHSType;
  8592. }
  8593. // C99 6.5.7
  8594. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8595. SourceLocation Loc, BinaryOperatorKind Opc,
  8596. bool IsCompAssign) {
  8597. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8598. // Vector shifts promote their scalar inputs to vector type.
  8599. if (LHS.get()->getType()->isVectorType() ||
  8600. RHS.get()->getType()->isVectorType()) {
  8601. if (LangOpts.ZVector) {
  8602. // The shift operators for the z vector extensions work basically
  8603. // like general shifts, except that neither the LHS nor the RHS is
  8604. // allowed to be a "vector bool".
  8605. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8606. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8607. return InvalidOperands(Loc, LHS, RHS);
  8608. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8609. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8610. return InvalidOperands(Loc, LHS, RHS);
  8611. }
  8612. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8613. }
  8614. // Shifts don't perform usual arithmetic conversions, they just do integer
  8615. // promotions on each operand. C99 6.5.7p3
  8616. // For the LHS, do usual unary conversions, but then reset them away
  8617. // if this is a compound assignment.
  8618. ExprResult OldLHS = LHS;
  8619. LHS = UsualUnaryConversions(LHS.get());
  8620. if (LHS.isInvalid())
  8621. return QualType();
  8622. QualType LHSType = LHS.get()->getType();
  8623. if (IsCompAssign) LHS = OldLHS;
  8624. // The RHS is simpler.
  8625. RHS = UsualUnaryConversions(RHS.get());
  8626. if (RHS.isInvalid())
  8627. return QualType();
  8628. QualType RHSType = RHS.get()->getType();
  8629. // C99 6.5.7p2: Each of the operands shall have integer type.
  8630. if (!LHSType->hasIntegerRepresentation() ||
  8631. !RHSType->hasIntegerRepresentation())
  8632. return InvalidOperands(Loc, LHS, RHS);
  8633. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8634. // hasIntegerRepresentation() above instead of this.
  8635. if (isScopedEnumerationType(LHSType) ||
  8636. isScopedEnumerationType(RHSType)) {
  8637. return InvalidOperands(Loc, LHS, RHS);
  8638. }
  8639. // Sanity-check shift operands
  8640. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8641. // "The type of the result is that of the promoted left operand."
  8642. return LHSType;
  8643. }
  8644. /// If two different enums are compared, raise a warning.
  8645. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8646. Expr *RHS) {
  8647. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8648. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8649. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8650. if (!LHSEnumType)
  8651. return;
  8652. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8653. if (!RHSEnumType)
  8654. return;
  8655. // Ignore anonymous enums.
  8656. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8657. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8658. return;
  8659. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8660. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8661. return;
  8662. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8663. return;
  8664. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8665. << LHSStrippedType << RHSStrippedType
  8666. << LHS->getSourceRange() << RHS->getSourceRange();
  8667. }
  8668. /// Diagnose bad pointer comparisons.
  8669. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8670. ExprResult &LHS, ExprResult &RHS,
  8671. bool IsError) {
  8672. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8673. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8674. << LHS.get()->getType() << RHS.get()->getType()
  8675. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8676. }
  8677. /// Returns false if the pointers are converted to a composite type,
  8678. /// true otherwise.
  8679. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8680. ExprResult &LHS, ExprResult &RHS) {
  8681. // C++ [expr.rel]p2:
  8682. // [...] Pointer conversions (4.10) and qualification
  8683. // conversions (4.4) are performed on pointer operands (or on
  8684. // a pointer operand and a null pointer constant) to bring
  8685. // them to their composite pointer type. [...]
  8686. //
  8687. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8688. // comparisons of pointers.
  8689. QualType LHSType = LHS.get()->getType();
  8690. QualType RHSType = RHS.get()->getType();
  8691. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8692. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8693. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8694. if (T.isNull()) {
  8695. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8696. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8697. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8698. else
  8699. S.InvalidOperands(Loc, LHS, RHS);
  8700. return true;
  8701. }
  8702. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8703. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8704. return false;
  8705. }
  8706. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8707. ExprResult &LHS,
  8708. ExprResult &RHS,
  8709. bool IsError) {
  8710. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8711. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8712. << LHS.get()->getType() << RHS.get()->getType()
  8713. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8714. }
  8715. static bool isObjCObjectLiteral(ExprResult &E) {
  8716. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8717. case Stmt::ObjCArrayLiteralClass:
  8718. case Stmt::ObjCDictionaryLiteralClass:
  8719. case Stmt::ObjCStringLiteralClass:
  8720. case Stmt::ObjCBoxedExprClass:
  8721. return true;
  8722. default:
  8723. // Note that ObjCBoolLiteral is NOT an object literal!
  8724. return false;
  8725. }
  8726. }
  8727. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8728. const ObjCObjectPointerType *Type =
  8729. LHS->getType()->getAs<ObjCObjectPointerType>();
  8730. // If this is not actually an Objective-C object, bail out.
  8731. if (!Type)
  8732. return false;
  8733. // Get the LHS object's interface type.
  8734. QualType InterfaceType = Type->getPointeeType();
  8735. // If the RHS isn't an Objective-C object, bail out.
  8736. if (!RHS->getType()->isObjCObjectPointerType())
  8737. return false;
  8738. // Try to find the -isEqual: method.
  8739. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8740. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8741. InterfaceType,
  8742. /*IsInstance=*/true);
  8743. if (!Method) {
  8744. if (Type->isObjCIdType()) {
  8745. // For 'id', just check the global pool.
  8746. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8747. /*receiverId=*/true);
  8748. } else {
  8749. // Check protocols.
  8750. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8751. /*IsInstance=*/true);
  8752. }
  8753. }
  8754. if (!Method)
  8755. return false;
  8756. QualType T = Method->parameters()[0]->getType();
  8757. if (!T->isObjCObjectPointerType())
  8758. return false;
  8759. QualType R = Method->getReturnType();
  8760. if (!R->isScalarType())
  8761. return false;
  8762. return true;
  8763. }
  8764. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8765. FromE = FromE->IgnoreParenImpCasts();
  8766. switch (FromE->getStmtClass()) {
  8767. default:
  8768. break;
  8769. case Stmt::ObjCStringLiteralClass:
  8770. // "string literal"
  8771. return LK_String;
  8772. case Stmt::ObjCArrayLiteralClass:
  8773. // "array literal"
  8774. return LK_Array;
  8775. case Stmt::ObjCDictionaryLiteralClass:
  8776. // "dictionary literal"
  8777. return LK_Dictionary;
  8778. case Stmt::BlockExprClass:
  8779. return LK_Block;
  8780. case Stmt::ObjCBoxedExprClass: {
  8781. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8782. switch (Inner->getStmtClass()) {
  8783. case Stmt::IntegerLiteralClass:
  8784. case Stmt::FloatingLiteralClass:
  8785. case Stmt::CharacterLiteralClass:
  8786. case Stmt::ObjCBoolLiteralExprClass:
  8787. case Stmt::CXXBoolLiteralExprClass:
  8788. // "numeric literal"
  8789. return LK_Numeric;
  8790. case Stmt::ImplicitCastExprClass: {
  8791. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8792. // Boolean literals can be represented by implicit casts.
  8793. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8794. return LK_Numeric;
  8795. break;
  8796. }
  8797. default:
  8798. break;
  8799. }
  8800. return LK_Boxed;
  8801. }
  8802. }
  8803. return LK_None;
  8804. }
  8805. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8806. ExprResult &LHS, ExprResult &RHS,
  8807. BinaryOperator::Opcode Opc){
  8808. Expr *Literal;
  8809. Expr *Other;
  8810. if (isObjCObjectLiteral(LHS)) {
  8811. Literal = LHS.get();
  8812. Other = RHS.get();
  8813. } else {
  8814. Literal = RHS.get();
  8815. Other = LHS.get();
  8816. }
  8817. // Don't warn on comparisons against nil.
  8818. Other = Other->IgnoreParenCasts();
  8819. if (Other->isNullPointerConstant(S.getASTContext(),
  8820. Expr::NPC_ValueDependentIsNotNull))
  8821. return;
  8822. // This should be kept in sync with warn_objc_literal_comparison.
  8823. // LK_String should always be after the other literals, since it has its own
  8824. // warning flag.
  8825. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8826. assert(LiteralKind != Sema::LK_Block);
  8827. if (LiteralKind == Sema::LK_None) {
  8828. llvm_unreachable("Unknown Objective-C object literal kind");
  8829. }
  8830. if (LiteralKind == Sema::LK_String)
  8831. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8832. << Literal->getSourceRange();
  8833. else
  8834. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8835. << LiteralKind << Literal->getSourceRange();
  8836. if (BinaryOperator::isEqualityOp(Opc) &&
  8837. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8838. SourceLocation Start = LHS.get()->getBeginLoc();
  8839. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8840. CharSourceRange OpRange =
  8841. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8842. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8843. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8844. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8845. << FixItHint::CreateInsertion(End, "]");
  8846. }
  8847. }
  8848. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8849. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8850. ExprResult &RHS, SourceLocation Loc,
  8851. BinaryOperatorKind Opc) {
  8852. // Check that left hand side is !something.
  8853. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8854. if (!UO || UO->getOpcode() != UO_LNot) return;
  8855. // Only check if the right hand side is non-bool arithmetic type.
  8856. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8857. // Make sure that the something in !something is not bool.
  8858. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8859. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8860. // Emit warning.
  8861. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8862. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8863. << Loc << IsBitwiseOp;
  8864. // First note suggest !(x < y)
  8865. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  8866. SourceLocation FirstClose = RHS.get()->getEndLoc();
  8867. FirstClose = S.getLocForEndOfToken(FirstClose);
  8868. if (FirstClose.isInvalid())
  8869. FirstOpen = SourceLocation();
  8870. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8871. << IsBitwiseOp
  8872. << FixItHint::CreateInsertion(FirstOpen, "(")
  8873. << FixItHint::CreateInsertion(FirstClose, ")");
  8874. // Second note suggests (!x) < y
  8875. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  8876. SourceLocation SecondClose = LHS.get()->getEndLoc();
  8877. SecondClose = S.getLocForEndOfToken(SecondClose);
  8878. if (SecondClose.isInvalid())
  8879. SecondOpen = SourceLocation();
  8880. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8881. << FixItHint::CreateInsertion(SecondOpen, "(")
  8882. << FixItHint::CreateInsertion(SecondClose, ")");
  8883. }
  8884. // Get the decl for a simple expression: a reference to a variable,
  8885. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8886. static ValueDecl *getCompareDecl(Expr *E) {
  8887. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
  8888. return DR->getDecl();
  8889. if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8890. if (Ivar->isFreeIvar())
  8891. return Ivar->getDecl();
  8892. }
  8893. if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8894. if (Mem->isImplicitAccess())
  8895. return Mem->getMemberDecl();
  8896. }
  8897. return nullptr;
  8898. }
  8899. /// Diagnose some forms of syntactically-obvious tautological comparison.
  8900. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  8901. Expr *LHS, Expr *RHS,
  8902. BinaryOperatorKind Opc) {
  8903. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  8904. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  8905. QualType LHSType = LHS->getType();
  8906. QualType RHSType = RHS->getType();
  8907. if (LHSType->hasFloatingRepresentation() ||
  8908. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  8909. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  8910. S.inTemplateInstantiation())
  8911. return;
  8912. // Comparisons between two array types are ill-formed for operator<=>, so
  8913. // we shouldn't emit any additional warnings about it.
  8914. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  8915. return;
  8916. // For non-floating point types, check for self-comparisons of the form
  8917. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8918. // often indicate logic errors in the program.
  8919. //
  8920. // NOTE: Don't warn about comparison expressions resulting from macro
  8921. // expansion. Also don't warn about comparisons which are only self
  8922. // comparisons within a template instantiation. The warnings should catch
  8923. // obvious cases in the definition of the template anyways. The idea is to
  8924. // warn when the typed comparison operator will always evaluate to the same
  8925. // result.
  8926. ValueDecl *DL = getCompareDecl(LHSStripped);
  8927. ValueDecl *DR = getCompareDecl(RHSStripped);
  8928. if (DL && DR && declaresSameEntity(DL, DR)) {
  8929. StringRef Result;
  8930. switch (Opc) {
  8931. case BO_EQ: case BO_LE: case BO_GE:
  8932. Result = "true";
  8933. break;
  8934. case BO_NE: case BO_LT: case BO_GT:
  8935. Result = "false";
  8936. break;
  8937. case BO_Cmp:
  8938. Result = "'std::strong_ordering::equal'";
  8939. break;
  8940. default:
  8941. break;
  8942. }
  8943. S.DiagRuntimeBehavior(Loc, nullptr,
  8944. S.PDiag(diag::warn_comparison_always)
  8945. << 0 /*self-comparison*/ << !Result.empty()
  8946. << Result);
  8947. } else if (DL && DR &&
  8948. DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
  8949. !DL->isWeak() && !DR->isWeak()) {
  8950. // What is it always going to evaluate to?
  8951. StringRef Result;
  8952. switch(Opc) {
  8953. case BO_EQ: // e.g. array1 == array2
  8954. Result = "false";
  8955. break;
  8956. case BO_NE: // e.g. array1 != array2
  8957. Result = "true";
  8958. break;
  8959. default: // e.g. array1 <= array2
  8960. // The best we can say is 'a constant'
  8961. break;
  8962. }
  8963. S.DiagRuntimeBehavior(Loc, nullptr,
  8964. S.PDiag(diag::warn_comparison_always)
  8965. << 1 /*array comparison*/
  8966. << !Result.empty() << Result);
  8967. }
  8968. if (isa<CastExpr>(LHSStripped))
  8969. LHSStripped = LHSStripped->IgnoreParenCasts();
  8970. if (isa<CastExpr>(RHSStripped))
  8971. RHSStripped = RHSStripped->IgnoreParenCasts();
  8972. // Warn about comparisons against a string constant (unless the other
  8973. // operand is null); the user probably wants strcmp.
  8974. Expr *LiteralString = nullptr;
  8975. Expr *LiteralStringStripped = nullptr;
  8976. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  8977. !RHSStripped->isNullPointerConstant(S.Context,
  8978. Expr::NPC_ValueDependentIsNull)) {
  8979. LiteralString = LHS;
  8980. LiteralStringStripped = LHSStripped;
  8981. } else if ((isa<StringLiteral>(RHSStripped) ||
  8982. isa<ObjCEncodeExpr>(RHSStripped)) &&
  8983. !LHSStripped->isNullPointerConstant(S.Context,
  8984. Expr::NPC_ValueDependentIsNull)) {
  8985. LiteralString = RHS;
  8986. LiteralStringStripped = RHSStripped;
  8987. }
  8988. if (LiteralString) {
  8989. S.DiagRuntimeBehavior(Loc, nullptr,
  8990. S.PDiag(diag::warn_stringcompare)
  8991. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  8992. << LiteralString->getSourceRange());
  8993. }
  8994. }
  8995. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  8996. switch (CK) {
  8997. default: {
  8998. #ifndef NDEBUG
  8999. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  9000. << "\n";
  9001. #endif
  9002. llvm_unreachable("unhandled cast kind");
  9003. }
  9004. case CK_UserDefinedConversion:
  9005. return ICK_Identity;
  9006. case CK_LValueToRValue:
  9007. return ICK_Lvalue_To_Rvalue;
  9008. case CK_ArrayToPointerDecay:
  9009. return ICK_Array_To_Pointer;
  9010. case CK_FunctionToPointerDecay:
  9011. return ICK_Function_To_Pointer;
  9012. case CK_IntegralCast:
  9013. return ICK_Integral_Conversion;
  9014. case CK_FloatingCast:
  9015. return ICK_Floating_Conversion;
  9016. case CK_IntegralToFloating:
  9017. case CK_FloatingToIntegral:
  9018. return ICK_Floating_Integral;
  9019. case CK_IntegralComplexCast:
  9020. case CK_FloatingComplexCast:
  9021. case CK_FloatingComplexToIntegralComplex:
  9022. case CK_IntegralComplexToFloatingComplex:
  9023. return ICK_Complex_Conversion;
  9024. case CK_FloatingComplexToReal:
  9025. case CK_FloatingRealToComplex:
  9026. case CK_IntegralComplexToReal:
  9027. case CK_IntegralRealToComplex:
  9028. return ICK_Complex_Real;
  9029. }
  9030. }
  9031. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  9032. QualType FromType,
  9033. SourceLocation Loc) {
  9034. // Check for a narrowing implicit conversion.
  9035. StandardConversionSequence SCS;
  9036. SCS.setAsIdentityConversion();
  9037. SCS.setToType(0, FromType);
  9038. SCS.setToType(1, ToType);
  9039. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9040. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  9041. APValue PreNarrowingValue;
  9042. QualType PreNarrowingType;
  9043. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  9044. PreNarrowingType,
  9045. /*IgnoreFloatToIntegralConversion*/ true)) {
  9046. case NK_Dependent_Narrowing:
  9047. // Implicit conversion to a narrower type, but the expression is
  9048. // value-dependent so we can't tell whether it's actually narrowing.
  9049. case NK_Not_Narrowing:
  9050. return false;
  9051. case NK_Constant_Narrowing:
  9052. // Implicit conversion to a narrower type, and the value is not a constant
  9053. // expression.
  9054. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9055. << /*Constant*/ 1
  9056. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  9057. return true;
  9058. case NK_Variable_Narrowing:
  9059. // Implicit conversion to a narrower type, and the value is not a constant
  9060. // expression.
  9061. case NK_Type_Narrowing:
  9062. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9063. << /*Constant*/ 0 << FromType << ToType;
  9064. // TODO: It's not a constant expression, but what if the user intended it
  9065. // to be? Can we produce notes to help them figure out why it isn't?
  9066. return true;
  9067. }
  9068. llvm_unreachable("unhandled case in switch");
  9069. }
  9070. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9071. ExprResult &LHS,
  9072. ExprResult &RHS,
  9073. SourceLocation Loc) {
  9074. using CCT = ComparisonCategoryType;
  9075. QualType LHSType = LHS.get()->getType();
  9076. QualType RHSType = RHS.get()->getType();
  9077. // Dig out the original argument type and expression before implicit casts
  9078. // were applied. These are the types/expressions we need to check the
  9079. // [expr.spaceship] requirements against.
  9080. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9081. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9082. QualType LHSStrippedType = LHSStripped.get()->getType();
  9083. QualType RHSStrippedType = RHSStripped.get()->getType();
  9084. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9085. // other is not, the program is ill-formed.
  9086. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9087. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9088. return QualType();
  9089. }
  9090. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9091. RHSStrippedType->isEnumeralType();
  9092. if (NumEnumArgs == 1) {
  9093. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9094. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9095. if (OtherTy->hasFloatingRepresentation()) {
  9096. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9097. return QualType();
  9098. }
  9099. }
  9100. if (NumEnumArgs == 2) {
  9101. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9102. // type E, the operator yields the result of converting the operands
  9103. // to the underlying type of E and applying <=> to the converted operands.
  9104. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9105. S.InvalidOperands(Loc, LHS, RHS);
  9106. return QualType();
  9107. }
  9108. QualType IntType =
  9109. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  9110. assert(IntType->isArithmeticType());
  9111. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9112. // promote the boolean type, and all other promotable integer types, to
  9113. // avoid this.
  9114. if (IntType->isPromotableIntegerType())
  9115. IntType = S.Context.getPromotedIntegerType(IntType);
  9116. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9117. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9118. LHSType = RHSType = IntType;
  9119. }
  9120. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9121. // usual arithmetic conversions are applied to the operands.
  9122. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9123. if (LHS.isInvalid() || RHS.isInvalid())
  9124. return QualType();
  9125. if (Type.isNull())
  9126. return S.InvalidOperands(Loc, LHS, RHS);
  9127. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9128. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9129. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9130. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9131. RHS.get()->getBeginLoc());
  9132. if (HasNarrowing)
  9133. return QualType();
  9134. assert(!Type.isNull() && "composite type for <=> has not been set");
  9135. auto TypeKind = [&]() {
  9136. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9137. if (CT->getElementType()->hasFloatingRepresentation())
  9138. return CCT::WeakEquality;
  9139. return CCT::StrongEquality;
  9140. }
  9141. if (Type->isIntegralOrEnumerationType())
  9142. return CCT::StrongOrdering;
  9143. if (Type->hasFloatingRepresentation())
  9144. return CCT::PartialOrdering;
  9145. llvm_unreachable("other types are unimplemented");
  9146. }();
  9147. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9148. }
  9149. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9150. ExprResult &RHS,
  9151. SourceLocation Loc,
  9152. BinaryOperatorKind Opc) {
  9153. if (Opc == BO_Cmp)
  9154. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9155. // C99 6.5.8p3 / C99 6.5.9p4
  9156. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9157. if (LHS.isInvalid() || RHS.isInvalid())
  9158. return QualType();
  9159. if (Type.isNull())
  9160. return S.InvalidOperands(Loc, LHS, RHS);
  9161. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9162. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9163. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9164. return S.InvalidOperands(Loc, LHS, RHS);
  9165. // Check for comparisons of floating point operands using != and ==.
  9166. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9167. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9168. // The result of comparisons is 'bool' in C++, 'int' in C.
  9169. return S.Context.getLogicalOperationType();
  9170. }
  9171. // C99 6.5.8, C++ [expr.rel]
  9172. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9173. SourceLocation Loc,
  9174. BinaryOperatorKind Opc) {
  9175. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9176. bool IsThreeWay = Opc == BO_Cmp;
  9177. auto IsAnyPointerType = [](ExprResult E) {
  9178. QualType Ty = E.get()->getType();
  9179. return Ty->isPointerType() || Ty->isMemberPointerType();
  9180. };
  9181. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9182. // type, array-to-pointer, ..., conversions are performed on both operands to
  9183. // bring them to their composite type.
  9184. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9185. // any type-related checks.
  9186. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9187. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9188. if (LHS.isInvalid())
  9189. return QualType();
  9190. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9191. if (RHS.isInvalid())
  9192. return QualType();
  9193. } else {
  9194. LHS = DefaultLvalueConversion(LHS.get());
  9195. if (LHS.isInvalid())
  9196. return QualType();
  9197. RHS = DefaultLvalueConversion(RHS.get());
  9198. if (RHS.isInvalid())
  9199. return QualType();
  9200. }
  9201. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  9202. // Handle vector comparisons separately.
  9203. if (LHS.get()->getType()->isVectorType() ||
  9204. RHS.get()->getType()->isVectorType())
  9205. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9206. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9207. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9208. QualType LHSType = LHS.get()->getType();
  9209. QualType RHSType = RHS.get()->getType();
  9210. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9211. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9212. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9213. const Expr::NullPointerConstantKind LHSNullKind =
  9214. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9215. const Expr::NullPointerConstantKind RHSNullKind =
  9216. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9217. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9218. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9219. auto computeResultTy = [&]() {
  9220. if (Opc != BO_Cmp)
  9221. return Context.getLogicalOperationType();
  9222. assert(getLangOpts().CPlusPlus);
  9223. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9224. QualType CompositeTy = LHS.get()->getType();
  9225. assert(!CompositeTy->isReferenceType());
  9226. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9227. return CheckComparisonCategoryType(Kind, Loc);
  9228. };
  9229. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9230. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9231. // result is of type std::strong_equality
  9232. if (CompositeTy->isFunctionPointerType() ||
  9233. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9234. // FIXME: consider making the function pointer case produce
  9235. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9236. // and direction polls
  9237. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9238. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9239. // pointer type, p <=> q is of type std::strong_ordering.
  9240. if (CompositeTy->isPointerType()) {
  9241. // P0946R0: Comparisons between a null pointer constant and an object
  9242. // pointer result in std::strong_equality
  9243. if (LHSIsNull != RHSIsNull)
  9244. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9245. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9246. }
  9247. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9248. // TODO: Extend support for operator<=> to ObjC types.
  9249. return InvalidOperands(Loc, LHS, RHS);
  9250. };
  9251. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9252. bool IsEquality = Opc == BO_EQ;
  9253. if (RHSIsNull)
  9254. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9255. RHS.get()->getSourceRange());
  9256. else
  9257. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9258. LHS.get()->getSourceRange());
  9259. }
  9260. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9261. (RHSType->isIntegerType() && !RHSIsNull)) {
  9262. // Skip normal pointer conversion checks in this case; we have better
  9263. // diagnostics for this below.
  9264. } else if (getLangOpts().CPlusPlus) {
  9265. // Equality comparison of a function pointer to a void pointer is invalid,
  9266. // but we allow it as an extension.
  9267. // FIXME: If we really want to allow this, should it be part of composite
  9268. // pointer type computation so it works in conditionals too?
  9269. if (!IsRelational &&
  9270. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9271. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9272. // This is a gcc extension compatibility comparison.
  9273. // In a SFINAE context, we treat this as a hard error to maintain
  9274. // conformance with the C++ standard.
  9275. diagnoseFunctionPointerToVoidComparison(
  9276. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9277. if (isSFINAEContext())
  9278. return QualType();
  9279. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9280. return computeResultTy();
  9281. }
  9282. // C++ [expr.eq]p2:
  9283. // If at least one operand is a pointer [...] bring them to their
  9284. // composite pointer type.
  9285. // C++ [expr.spaceship]p6
  9286. // If at least one of the operands is of pointer type, [...] bring them
  9287. // to their composite pointer type.
  9288. // C++ [expr.rel]p2:
  9289. // If both operands are pointers, [...] bring them to their composite
  9290. // pointer type.
  9291. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9292. (IsRelational ? 2 : 1) &&
  9293. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9294. RHSType->isObjCObjectPointerType()))) {
  9295. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9296. return QualType();
  9297. return computeResultTy();
  9298. }
  9299. } else if (LHSType->isPointerType() &&
  9300. RHSType->isPointerType()) { // C99 6.5.8p2
  9301. // All of the following pointer-related warnings are GCC extensions, except
  9302. // when handling null pointer constants.
  9303. QualType LCanPointeeTy =
  9304. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9305. QualType RCanPointeeTy =
  9306. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9307. // C99 6.5.9p2 and C99 6.5.8p2
  9308. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9309. RCanPointeeTy.getUnqualifiedType())) {
  9310. // Valid unless a relational comparison of function pointers
  9311. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9312. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9313. << LHSType << RHSType << LHS.get()->getSourceRange()
  9314. << RHS.get()->getSourceRange();
  9315. }
  9316. } else if (!IsRelational &&
  9317. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9318. // Valid unless comparison between non-null pointer and function pointer
  9319. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9320. && !LHSIsNull && !RHSIsNull)
  9321. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9322. /*isError*/false);
  9323. } else {
  9324. // Invalid
  9325. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9326. }
  9327. if (LCanPointeeTy != RCanPointeeTy) {
  9328. // Treat NULL constant as a special case in OpenCL.
  9329. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9330. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  9331. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  9332. Diag(Loc,
  9333. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9334. << LHSType << RHSType << 0 /* comparison */
  9335. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9336. }
  9337. }
  9338. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9339. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9340. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9341. : CK_BitCast;
  9342. if (LHSIsNull && !RHSIsNull)
  9343. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9344. else
  9345. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9346. }
  9347. return computeResultTy();
  9348. }
  9349. if (getLangOpts().CPlusPlus) {
  9350. // C++ [expr.eq]p4:
  9351. // Two operands of type std::nullptr_t or one operand of type
  9352. // std::nullptr_t and the other a null pointer constant compare equal.
  9353. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9354. if (LHSType->isNullPtrType()) {
  9355. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9356. return computeResultTy();
  9357. }
  9358. if (RHSType->isNullPtrType()) {
  9359. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9360. return computeResultTy();
  9361. }
  9362. }
  9363. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9364. // These aren't covered by the composite pointer type rules.
  9365. if (!IsRelational && RHSType->isNullPtrType() &&
  9366. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9367. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9368. return computeResultTy();
  9369. }
  9370. if (!IsRelational && LHSType->isNullPtrType() &&
  9371. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9372. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9373. return computeResultTy();
  9374. }
  9375. if (IsRelational &&
  9376. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9377. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9378. // HACK: Relational comparison of nullptr_t against a pointer type is
  9379. // invalid per DR583, but we allow it within std::less<> and friends,
  9380. // since otherwise common uses of it break.
  9381. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9382. // friends to have std::nullptr_t overload candidates.
  9383. DeclContext *DC = CurContext;
  9384. if (isa<FunctionDecl>(DC))
  9385. DC = DC->getParent();
  9386. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9387. if (CTSD->isInStdNamespace() &&
  9388. llvm::StringSwitch<bool>(CTSD->getName())
  9389. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9390. .Default(false)) {
  9391. if (RHSType->isNullPtrType())
  9392. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9393. else
  9394. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9395. return computeResultTy();
  9396. }
  9397. }
  9398. }
  9399. // C++ [expr.eq]p2:
  9400. // If at least one operand is a pointer to member, [...] bring them to
  9401. // their composite pointer type.
  9402. if (!IsRelational &&
  9403. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9404. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9405. return QualType();
  9406. else
  9407. return computeResultTy();
  9408. }
  9409. }
  9410. // Handle block pointer types.
  9411. if (!IsRelational && LHSType->isBlockPointerType() &&
  9412. RHSType->isBlockPointerType()) {
  9413. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9414. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9415. if (!LHSIsNull && !RHSIsNull &&
  9416. !Context.typesAreCompatible(lpointee, rpointee)) {
  9417. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9418. << LHSType << RHSType << LHS.get()->getSourceRange()
  9419. << RHS.get()->getSourceRange();
  9420. }
  9421. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9422. return computeResultTy();
  9423. }
  9424. // Allow block pointers to be compared with null pointer constants.
  9425. if (!IsRelational
  9426. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9427. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9428. if (!LHSIsNull && !RHSIsNull) {
  9429. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9430. ->getPointeeType()->isVoidType())
  9431. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9432. ->getPointeeType()->isVoidType())))
  9433. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9434. << LHSType << RHSType << LHS.get()->getSourceRange()
  9435. << RHS.get()->getSourceRange();
  9436. }
  9437. if (LHSIsNull && !RHSIsNull)
  9438. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9439. RHSType->isPointerType() ? CK_BitCast
  9440. : CK_AnyPointerToBlockPointerCast);
  9441. else
  9442. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9443. LHSType->isPointerType() ? CK_BitCast
  9444. : CK_AnyPointerToBlockPointerCast);
  9445. return computeResultTy();
  9446. }
  9447. if (LHSType->isObjCObjectPointerType() ||
  9448. RHSType->isObjCObjectPointerType()) {
  9449. const PointerType *LPT = LHSType->getAs<PointerType>();
  9450. const PointerType *RPT = RHSType->getAs<PointerType>();
  9451. if (LPT || RPT) {
  9452. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9453. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9454. if (!LPtrToVoid && !RPtrToVoid &&
  9455. !Context.typesAreCompatible(LHSType, RHSType)) {
  9456. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9457. /*isError*/false);
  9458. }
  9459. if (LHSIsNull && !RHSIsNull) {
  9460. Expr *E = LHS.get();
  9461. if (getLangOpts().ObjCAutoRefCount)
  9462. CheckObjCConversion(SourceRange(), RHSType, E,
  9463. CCK_ImplicitConversion);
  9464. LHS = ImpCastExprToType(E, RHSType,
  9465. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9466. }
  9467. else {
  9468. Expr *E = RHS.get();
  9469. if (getLangOpts().ObjCAutoRefCount)
  9470. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9471. /*Diagnose=*/true,
  9472. /*DiagnoseCFAudited=*/false, Opc);
  9473. RHS = ImpCastExprToType(E, LHSType,
  9474. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9475. }
  9476. return computeResultTy();
  9477. }
  9478. if (LHSType->isObjCObjectPointerType() &&
  9479. RHSType->isObjCObjectPointerType()) {
  9480. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9481. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9482. /*isError*/false);
  9483. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9484. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9485. if (LHSIsNull && !RHSIsNull)
  9486. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9487. else
  9488. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9489. return computeResultTy();
  9490. }
  9491. if (!IsRelational && LHSType->isBlockPointerType() &&
  9492. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9493. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9494. CK_BlockPointerToObjCPointerCast);
  9495. return computeResultTy();
  9496. } else if (!IsRelational &&
  9497. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9498. RHSType->isBlockPointerType()) {
  9499. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9500. CK_BlockPointerToObjCPointerCast);
  9501. return computeResultTy();
  9502. }
  9503. }
  9504. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9505. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9506. unsigned DiagID = 0;
  9507. bool isError = false;
  9508. if (LangOpts.DebuggerSupport) {
  9509. // Under a debugger, allow the comparison of pointers to integers,
  9510. // since users tend to want to compare addresses.
  9511. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9512. (RHSIsNull && RHSType->isIntegerType())) {
  9513. if (IsRelational) {
  9514. isError = getLangOpts().CPlusPlus;
  9515. DiagID =
  9516. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9517. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9518. }
  9519. } else if (getLangOpts().CPlusPlus) {
  9520. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9521. isError = true;
  9522. } else if (IsRelational)
  9523. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9524. else
  9525. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9526. if (DiagID) {
  9527. Diag(Loc, DiagID)
  9528. << LHSType << RHSType << LHS.get()->getSourceRange()
  9529. << RHS.get()->getSourceRange();
  9530. if (isError)
  9531. return QualType();
  9532. }
  9533. if (LHSType->isIntegerType())
  9534. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9535. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9536. else
  9537. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9538. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9539. return computeResultTy();
  9540. }
  9541. // Handle block pointers.
  9542. if (!IsRelational && RHSIsNull
  9543. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9544. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9545. return computeResultTy();
  9546. }
  9547. if (!IsRelational && LHSIsNull
  9548. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9549. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9550. return computeResultTy();
  9551. }
  9552. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9553. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9554. return computeResultTy();
  9555. }
  9556. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9557. return computeResultTy();
  9558. }
  9559. if (LHSIsNull && RHSType->isQueueT()) {
  9560. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9561. return computeResultTy();
  9562. }
  9563. if (LHSType->isQueueT() && RHSIsNull) {
  9564. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9565. return computeResultTy();
  9566. }
  9567. }
  9568. return InvalidOperands(Loc, LHS, RHS);
  9569. }
  9570. // Return a signed ext_vector_type that is of identical size and number of
  9571. // elements. For floating point vectors, return an integer type of identical
  9572. // size and number of elements. In the non ext_vector_type case, search from
  9573. // the largest type to the smallest type to avoid cases where long long == long,
  9574. // where long gets picked over long long.
  9575. QualType Sema::GetSignedVectorType(QualType V) {
  9576. const VectorType *VTy = V->getAs<VectorType>();
  9577. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9578. if (isa<ExtVectorType>(VTy)) {
  9579. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9580. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9581. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9582. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9583. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9584. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9585. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9586. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9587. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9588. "Unhandled vector element size in vector compare");
  9589. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9590. }
  9591. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9592. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9593. VectorType::GenericVector);
  9594. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9595. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9596. VectorType::GenericVector);
  9597. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9598. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9599. VectorType::GenericVector);
  9600. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9601. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9602. VectorType::GenericVector);
  9603. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9604. "Unhandled vector element size in vector compare");
  9605. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9606. VectorType::GenericVector);
  9607. }
  9608. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9609. /// operates on extended vector types. Instead of producing an IntTy result,
  9610. /// like a scalar comparison, a vector comparison produces a vector of integer
  9611. /// types.
  9612. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9613. SourceLocation Loc,
  9614. BinaryOperatorKind Opc) {
  9615. // Check to make sure we're operating on vectors of the same type and width,
  9616. // Allowing one side to be a scalar of element type.
  9617. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9618. /*AllowBothBool*/true,
  9619. /*AllowBoolConversions*/getLangOpts().ZVector);
  9620. if (vType.isNull())
  9621. return vType;
  9622. QualType LHSType = LHS.get()->getType();
  9623. // If AltiVec, the comparison results in a numeric type, i.e.
  9624. // bool for C++, int for C
  9625. if (getLangOpts().AltiVec &&
  9626. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9627. return Context.getLogicalOperationType();
  9628. // For non-floating point types, check for self-comparisons of the form
  9629. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9630. // often indicate logic errors in the program.
  9631. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9632. // Check for comparisons of floating point operands using != and ==.
  9633. if (BinaryOperator::isEqualityOp(Opc) &&
  9634. LHSType->hasFloatingRepresentation()) {
  9635. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9636. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9637. }
  9638. // Return a signed type for the vector.
  9639. return GetSignedVectorType(vType);
  9640. }
  9641. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9642. SourceLocation Loc) {
  9643. // Ensure that either both operands are of the same vector type, or
  9644. // one operand is of a vector type and the other is of its element type.
  9645. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9646. /*AllowBothBool*/true,
  9647. /*AllowBoolConversions*/false);
  9648. if (vType.isNull())
  9649. return InvalidOperands(Loc, LHS, RHS);
  9650. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9651. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9652. return InvalidOperands(Loc, LHS, RHS);
  9653. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9654. // usage of the logical operators && and || with vectors in C. This
  9655. // check could be notionally dropped.
  9656. if (!getLangOpts().CPlusPlus &&
  9657. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9658. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9659. return GetSignedVectorType(LHS.get()->getType());
  9660. }
  9661. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9662. SourceLocation Loc,
  9663. BinaryOperatorKind Opc) {
  9664. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9665. bool IsCompAssign =
  9666. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9667. if (LHS.get()->getType()->isVectorType() ||
  9668. RHS.get()->getType()->isVectorType()) {
  9669. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9670. RHS.get()->getType()->hasIntegerRepresentation())
  9671. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9672. /*AllowBothBool*/true,
  9673. /*AllowBoolConversions*/getLangOpts().ZVector);
  9674. return InvalidOperands(Loc, LHS, RHS);
  9675. }
  9676. if (Opc == BO_And)
  9677. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9678. ExprResult LHSResult = LHS, RHSResult = RHS;
  9679. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9680. IsCompAssign);
  9681. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9682. return QualType();
  9683. LHS = LHSResult.get();
  9684. RHS = RHSResult.get();
  9685. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9686. return compType;
  9687. return InvalidOperands(Loc, LHS, RHS);
  9688. }
  9689. // C99 6.5.[13,14]
  9690. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9691. SourceLocation Loc,
  9692. BinaryOperatorKind Opc) {
  9693. // Check vector operands differently.
  9694. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9695. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9696. // Diagnose cases where the user write a logical and/or but probably meant a
  9697. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9698. // is a constant.
  9699. if (LHS.get()->getType()->isIntegerType() &&
  9700. !LHS.get()->getType()->isBooleanType() &&
  9701. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9702. // Don't warn in macros or template instantiations.
  9703. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9704. // If the RHS can be constant folded, and if it constant folds to something
  9705. // that isn't 0 or 1 (which indicate a potential logical operation that
  9706. // happened to fold to true/false) then warn.
  9707. // Parens on the RHS are ignored.
  9708. Expr::EvalResult EVResult;
  9709. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9710. llvm::APSInt Result = EVResult.Val.getInt();
  9711. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9712. !RHS.get()->getExprLoc().isMacroID()) ||
  9713. (Result != 0 && Result != 1)) {
  9714. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9715. << RHS.get()->getSourceRange()
  9716. << (Opc == BO_LAnd ? "&&" : "||");
  9717. // Suggest replacing the logical operator with the bitwise version
  9718. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9719. << (Opc == BO_LAnd ? "&" : "|")
  9720. << FixItHint::CreateReplacement(SourceRange(
  9721. Loc, getLocForEndOfToken(Loc)),
  9722. Opc == BO_LAnd ? "&" : "|");
  9723. if (Opc == BO_LAnd)
  9724. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9725. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9726. << FixItHint::CreateRemoval(
  9727. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  9728. RHS.get()->getEndLoc()));
  9729. }
  9730. }
  9731. }
  9732. if (!Context.getLangOpts().CPlusPlus) {
  9733. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9734. // not operate on the built-in scalar and vector float types.
  9735. if (Context.getLangOpts().OpenCL &&
  9736. Context.getLangOpts().OpenCLVersion < 120) {
  9737. if (LHS.get()->getType()->isFloatingType() ||
  9738. RHS.get()->getType()->isFloatingType())
  9739. return InvalidOperands(Loc, LHS, RHS);
  9740. }
  9741. LHS = UsualUnaryConversions(LHS.get());
  9742. if (LHS.isInvalid())
  9743. return QualType();
  9744. RHS = UsualUnaryConversions(RHS.get());
  9745. if (RHS.isInvalid())
  9746. return QualType();
  9747. if (!LHS.get()->getType()->isScalarType() ||
  9748. !RHS.get()->getType()->isScalarType())
  9749. return InvalidOperands(Loc, LHS, RHS);
  9750. return Context.IntTy;
  9751. }
  9752. // The following is safe because we only use this method for
  9753. // non-overloadable operands.
  9754. // C++ [expr.log.and]p1
  9755. // C++ [expr.log.or]p1
  9756. // The operands are both contextually converted to type bool.
  9757. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9758. if (LHSRes.isInvalid())
  9759. return InvalidOperands(Loc, LHS, RHS);
  9760. LHS = LHSRes;
  9761. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9762. if (RHSRes.isInvalid())
  9763. return InvalidOperands(Loc, LHS, RHS);
  9764. RHS = RHSRes;
  9765. // C++ [expr.log.and]p2
  9766. // C++ [expr.log.or]p2
  9767. // The result is a bool.
  9768. return Context.BoolTy;
  9769. }
  9770. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9771. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9772. if (!ME) return false;
  9773. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9774. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9775. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9776. if (!Base) return false;
  9777. return Base->getMethodDecl() != nullptr;
  9778. }
  9779. /// Is the given expression (which must be 'const') a reference to a
  9780. /// variable which was originally non-const, but which has become
  9781. /// 'const' due to being captured within a block?
  9782. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9783. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9784. assert(E->isLValue() && E->getType().isConstQualified());
  9785. E = E->IgnoreParens();
  9786. // Must be a reference to a declaration from an enclosing scope.
  9787. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9788. if (!DRE) return NCCK_None;
  9789. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9790. // The declaration must be a variable which is not declared 'const'.
  9791. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9792. if (!var) return NCCK_None;
  9793. if (var->getType().isConstQualified()) return NCCK_None;
  9794. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9795. // Decide whether the first capture was for a block or a lambda.
  9796. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9797. // Decide whether the first capture was for a block or a lambda.
  9798. while (DC) {
  9799. // For init-capture, it is possible that the variable belongs to the
  9800. // template pattern of the current context.
  9801. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  9802. if (var->isInitCapture() &&
  9803. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  9804. break;
  9805. if (DC == var->getDeclContext())
  9806. break;
  9807. Prev = DC;
  9808. DC = DC->getParent();
  9809. }
  9810. // Unless we have an init-capture, we've gone one step too far.
  9811. if (!var->isInitCapture())
  9812. DC = Prev;
  9813. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  9814. }
  9815. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  9816. Ty = Ty.getNonReferenceType();
  9817. if (IsDereference && Ty->isPointerType())
  9818. Ty = Ty->getPointeeType();
  9819. return !Ty.isConstQualified();
  9820. }
  9821. // Update err_typecheck_assign_const and note_typecheck_assign_const
  9822. // when this enum is changed.
  9823. enum {
  9824. ConstFunction,
  9825. ConstVariable,
  9826. ConstMember,
  9827. ConstMethod,
  9828. NestedConstMember,
  9829. ConstUnknown, // Keep as last element
  9830. };
  9831. /// Emit the "read-only variable not assignable" error and print notes to give
  9832. /// more information about why the variable is not assignable, such as pointing
  9833. /// to the declaration of a const variable, showing that a method is const, or
  9834. /// that the function is returning a const reference.
  9835. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  9836. SourceLocation Loc) {
  9837. SourceRange ExprRange = E->getSourceRange();
  9838. // Only emit one error on the first const found. All other consts will emit
  9839. // a note to the error.
  9840. bool DiagnosticEmitted = false;
  9841. // Track if the current expression is the result of a dereference, and if the
  9842. // next checked expression is the result of a dereference.
  9843. bool IsDereference = false;
  9844. bool NextIsDereference = false;
  9845. // Loop to process MemberExpr chains.
  9846. while (true) {
  9847. IsDereference = NextIsDereference;
  9848. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  9849. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9850. NextIsDereference = ME->isArrow();
  9851. const ValueDecl *VD = ME->getMemberDecl();
  9852. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  9853. // Mutable fields can be modified even if the class is const.
  9854. if (Field->isMutable()) {
  9855. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  9856. break;
  9857. }
  9858. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  9859. if (!DiagnosticEmitted) {
  9860. S.Diag(Loc, diag::err_typecheck_assign_const)
  9861. << ExprRange << ConstMember << false /*static*/ << Field
  9862. << Field->getType();
  9863. DiagnosticEmitted = true;
  9864. }
  9865. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9866. << ConstMember << false /*static*/ << Field << Field->getType()
  9867. << Field->getSourceRange();
  9868. }
  9869. E = ME->getBase();
  9870. continue;
  9871. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  9872. if (VDecl->getType().isConstQualified()) {
  9873. if (!DiagnosticEmitted) {
  9874. S.Diag(Loc, diag::err_typecheck_assign_const)
  9875. << ExprRange << ConstMember << true /*static*/ << VDecl
  9876. << VDecl->getType();
  9877. DiagnosticEmitted = true;
  9878. }
  9879. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9880. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  9881. << VDecl->getSourceRange();
  9882. }
  9883. // Static fields do not inherit constness from parents.
  9884. break;
  9885. }
  9886. break; // End MemberExpr
  9887. } else if (const ArraySubscriptExpr *ASE =
  9888. dyn_cast<ArraySubscriptExpr>(E)) {
  9889. E = ASE->getBase()->IgnoreParenImpCasts();
  9890. continue;
  9891. } else if (const ExtVectorElementExpr *EVE =
  9892. dyn_cast<ExtVectorElementExpr>(E)) {
  9893. E = EVE->getBase()->IgnoreParenImpCasts();
  9894. continue;
  9895. }
  9896. break;
  9897. }
  9898. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9899. // Function calls
  9900. const FunctionDecl *FD = CE->getDirectCallee();
  9901. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  9902. if (!DiagnosticEmitted) {
  9903. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9904. << ConstFunction << FD;
  9905. DiagnosticEmitted = true;
  9906. }
  9907. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  9908. diag::note_typecheck_assign_const)
  9909. << ConstFunction << FD << FD->getReturnType()
  9910. << FD->getReturnTypeSourceRange();
  9911. }
  9912. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9913. // Point to variable declaration.
  9914. if (const ValueDecl *VD = DRE->getDecl()) {
  9915. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  9916. if (!DiagnosticEmitted) {
  9917. S.Diag(Loc, diag::err_typecheck_assign_const)
  9918. << ExprRange << ConstVariable << VD << VD->getType();
  9919. DiagnosticEmitted = true;
  9920. }
  9921. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9922. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  9923. }
  9924. }
  9925. } else if (isa<CXXThisExpr>(E)) {
  9926. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  9927. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  9928. if (MD->isConst()) {
  9929. if (!DiagnosticEmitted) {
  9930. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9931. << ConstMethod << MD;
  9932. DiagnosticEmitted = true;
  9933. }
  9934. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  9935. << ConstMethod << MD << MD->getSourceRange();
  9936. }
  9937. }
  9938. }
  9939. }
  9940. if (DiagnosticEmitted)
  9941. return;
  9942. // Can't determine a more specific message, so display the generic error.
  9943. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  9944. }
  9945. enum OriginalExprKind {
  9946. OEK_Variable,
  9947. OEK_Member,
  9948. OEK_LValue
  9949. };
  9950. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  9951. const RecordType *Ty,
  9952. SourceLocation Loc, SourceRange Range,
  9953. OriginalExprKind OEK,
  9954. bool &DiagnosticEmitted) {
  9955. std::vector<const RecordType *> RecordTypeList;
  9956. RecordTypeList.push_back(Ty);
  9957. unsigned NextToCheckIndex = 0;
  9958. // We walk the record hierarchy breadth-first to ensure that we print
  9959. // diagnostics in field nesting order.
  9960. while (RecordTypeList.size() > NextToCheckIndex) {
  9961. bool IsNested = NextToCheckIndex > 0;
  9962. for (const FieldDecl *Field :
  9963. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  9964. // First, check every field for constness.
  9965. QualType FieldTy = Field->getType();
  9966. if (FieldTy.isConstQualified()) {
  9967. if (!DiagnosticEmitted) {
  9968. S.Diag(Loc, diag::err_typecheck_assign_const)
  9969. << Range << NestedConstMember << OEK << VD
  9970. << IsNested << Field;
  9971. DiagnosticEmitted = true;
  9972. }
  9973. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  9974. << NestedConstMember << IsNested << Field
  9975. << FieldTy << Field->getSourceRange();
  9976. }
  9977. // Then we append it to the list to check next in order.
  9978. FieldTy = FieldTy.getCanonicalType();
  9979. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  9980. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  9981. RecordTypeList.push_back(FieldRecTy);
  9982. }
  9983. }
  9984. ++NextToCheckIndex;
  9985. }
  9986. }
  9987. /// Emit an error for the case where a record we are trying to assign to has a
  9988. /// const-qualified field somewhere in its hierarchy.
  9989. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  9990. SourceLocation Loc) {
  9991. QualType Ty = E->getType();
  9992. assert(Ty->isRecordType() && "lvalue was not record?");
  9993. SourceRange Range = E->getSourceRange();
  9994. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  9995. bool DiagEmitted = false;
  9996. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  9997. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  9998. Range, OEK_Member, DiagEmitted);
  9999. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10000. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  10001. Range, OEK_Variable, DiagEmitted);
  10002. else
  10003. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  10004. Range, OEK_LValue, DiagEmitted);
  10005. if (!DiagEmitted)
  10006. DiagnoseConstAssignment(S, E, Loc);
  10007. }
  10008. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  10009. /// emit an error and return true. If so, return false.
  10010. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  10011. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  10012. S.CheckShadowingDeclModification(E, Loc);
  10013. SourceLocation OrigLoc = Loc;
  10014. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  10015. &Loc);
  10016. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  10017. IsLV = Expr::MLV_InvalidMessageExpression;
  10018. if (IsLV == Expr::MLV_Valid)
  10019. return false;
  10020. unsigned DiagID = 0;
  10021. bool NeedType = false;
  10022. switch (IsLV) { // C99 6.5.16p2
  10023. case Expr::MLV_ConstQualified:
  10024. // Use a specialized diagnostic when we're assigning to an object
  10025. // from an enclosing function or block.
  10026. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  10027. if (NCCK == NCCK_Block)
  10028. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  10029. else
  10030. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  10031. break;
  10032. }
  10033. // In ARC, use some specialized diagnostics for occasions where we
  10034. // infer 'const'. These are always pseudo-strong variables.
  10035. if (S.getLangOpts().ObjCAutoRefCount) {
  10036. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  10037. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  10038. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  10039. // Use the normal diagnostic if it's pseudo-__strong but the
  10040. // user actually wrote 'const'.
  10041. if (var->isARCPseudoStrong() &&
  10042. (!var->getTypeSourceInfo() ||
  10043. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  10044. // There are three pseudo-strong cases:
  10045. // - self
  10046. ObjCMethodDecl *method = S.getCurMethodDecl();
  10047. if (method && var == method->getSelfDecl()) {
  10048. DiagID = method->isClassMethod()
  10049. ? diag::err_typecheck_arc_assign_self_class_method
  10050. : diag::err_typecheck_arc_assign_self;
  10051. // - Objective-C externally_retained attribute.
  10052. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  10053. isa<ParmVarDecl>(var)) {
  10054. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  10055. // - fast enumeration variables
  10056. } else {
  10057. DiagID = diag::err_typecheck_arr_assign_enumeration;
  10058. }
  10059. SourceRange Assign;
  10060. if (Loc != OrigLoc)
  10061. Assign = SourceRange(OrigLoc, OrigLoc);
  10062. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10063. // We need to preserve the AST regardless, so migration tool
  10064. // can do its job.
  10065. return false;
  10066. }
  10067. }
  10068. }
  10069. // If none of the special cases above are triggered, then this is a
  10070. // simple const assignment.
  10071. if (DiagID == 0) {
  10072. DiagnoseConstAssignment(S, E, Loc);
  10073. return true;
  10074. }
  10075. break;
  10076. case Expr::MLV_ConstAddrSpace:
  10077. DiagnoseConstAssignment(S, E, Loc);
  10078. return true;
  10079. case Expr::MLV_ConstQualifiedField:
  10080. DiagnoseRecursiveConstFields(S, E, Loc);
  10081. return true;
  10082. case Expr::MLV_ArrayType:
  10083. case Expr::MLV_ArrayTemporary:
  10084. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10085. NeedType = true;
  10086. break;
  10087. case Expr::MLV_NotObjectType:
  10088. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10089. NeedType = true;
  10090. break;
  10091. case Expr::MLV_LValueCast:
  10092. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10093. break;
  10094. case Expr::MLV_Valid:
  10095. llvm_unreachable("did not take early return for MLV_Valid");
  10096. case Expr::MLV_InvalidExpression:
  10097. case Expr::MLV_MemberFunction:
  10098. case Expr::MLV_ClassTemporary:
  10099. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10100. break;
  10101. case Expr::MLV_IncompleteType:
  10102. case Expr::MLV_IncompleteVoidType:
  10103. return S.RequireCompleteType(Loc, E->getType(),
  10104. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10105. case Expr::MLV_DuplicateVectorComponents:
  10106. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10107. break;
  10108. case Expr::MLV_NoSetterProperty:
  10109. llvm_unreachable("readonly properties should be processed differently");
  10110. case Expr::MLV_InvalidMessageExpression:
  10111. DiagID = diag::err_readonly_message_assignment;
  10112. break;
  10113. case Expr::MLV_SubObjCPropertySetting:
  10114. DiagID = diag::err_no_subobject_property_setting;
  10115. break;
  10116. }
  10117. SourceRange Assign;
  10118. if (Loc != OrigLoc)
  10119. Assign = SourceRange(OrigLoc, OrigLoc);
  10120. if (NeedType)
  10121. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10122. else
  10123. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10124. return true;
  10125. }
  10126. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10127. SourceLocation Loc,
  10128. Sema &Sema) {
  10129. if (Sema.inTemplateInstantiation())
  10130. return;
  10131. if (Sema.isUnevaluatedContext())
  10132. return;
  10133. if (Loc.isInvalid() || Loc.isMacroID())
  10134. return;
  10135. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10136. return;
  10137. // C / C++ fields
  10138. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10139. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10140. if (ML && MR) {
  10141. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10142. return;
  10143. const ValueDecl *LHSDecl =
  10144. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10145. const ValueDecl *RHSDecl =
  10146. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10147. if (LHSDecl != RHSDecl)
  10148. return;
  10149. if (LHSDecl->getType().isVolatileQualified())
  10150. return;
  10151. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10152. if (RefTy->getPointeeType().isVolatileQualified())
  10153. return;
  10154. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10155. }
  10156. // Objective-C instance variables
  10157. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10158. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10159. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10160. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10161. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10162. if (RL && RR && RL->getDecl() == RR->getDecl())
  10163. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10164. }
  10165. }
  10166. // C99 6.5.16.1
  10167. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10168. SourceLocation Loc,
  10169. QualType CompoundType) {
  10170. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10171. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10172. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10173. return QualType();
  10174. QualType LHSType = LHSExpr->getType();
  10175. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10176. CompoundType;
  10177. // OpenCL v1.2 s6.1.1.1 p2:
  10178. // The half data type can only be used to declare a pointer to a buffer that
  10179. // contains half values
  10180. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10181. LHSType->isHalfType()) {
  10182. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10183. << LHSType.getUnqualifiedType();
  10184. return QualType();
  10185. }
  10186. AssignConvertType ConvTy;
  10187. if (CompoundType.isNull()) {
  10188. Expr *RHSCheck = RHS.get();
  10189. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10190. QualType LHSTy(LHSType);
  10191. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10192. if (RHS.isInvalid())
  10193. return QualType();
  10194. // Special case of NSObject attributes on c-style pointer types.
  10195. if (ConvTy == IncompatiblePointer &&
  10196. ((Context.isObjCNSObjectType(LHSType) &&
  10197. RHSType->isObjCObjectPointerType()) ||
  10198. (Context.isObjCNSObjectType(RHSType) &&
  10199. LHSType->isObjCObjectPointerType())))
  10200. ConvTy = Compatible;
  10201. if (ConvTy == Compatible &&
  10202. LHSType->isObjCObjectType())
  10203. Diag(Loc, diag::err_objc_object_assignment)
  10204. << LHSType;
  10205. // If the RHS is a unary plus or minus, check to see if they = and + are
  10206. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10207. // instead of "x += 4".
  10208. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10209. RHSCheck = ICE->getSubExpr();
  10210. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10211. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10212. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10213. // Only if the two operators are exactly adjacent.
  10214. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10215. // And there is a space or other character before the subexpr of the
  10216. // unary +/-. We don't want to warn on "x=-1".
  10217. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10218. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10219. Diag(Loc, diag::warn_not_compound_assign)
  10220. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10221. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10222. }
  10223. }
  10224. if (ConvTy == Compatible) {
  10225. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10226. // Warn about retain cycles where a block captures the LHS, but
  10227. // not if the LHS is a simple variable into which the block is
  10228. // being stored...unless that variable can be captured by reference!
  10229. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10230. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10231. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10232. checkRetainCycles(LHSExpr, RHS.get());
  10233. }
  10234. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10235. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10236. // It is safe to assign a weak reference into a strong variable.
  10237. // Although this code can still have problems:
  10238. // id x = self.weakProp;
  10239. // id y = self.weakProp;
  10240. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10241. // paths through the function. This should be revisited if
  10242. // -Wrepeated-use-of-weak is made flow-sensitive.
  10243. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10244. // variable, which will be valid for the current autorelease scope.
  10245. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10246. RHS.get()->getBeginLoc()))
  10247. getCurFunction()->markSafeWeakUse(RHS.get());
  10248. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10249. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10250. }
  10251. }
  10252. } else {
  10253. // Compound assignment "x += y"
  10254. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10255. }
  10256. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10257. RHS.get(), AA_Assigning))
  10258. return QualType();
  10259. CheckForNullPointerDereference(*this, LHSExpr);
  10260. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10261. // left operand unless the left operand has qualified type, in which case
  10262. // it is the unqualified version of the type of the left operand.
  10263. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10264. // is converted to the type of the assignment expression (above).
  10265. // C++ 5.17p1: the type of the assignment expression is that of its left
  10266. // operand.
  10267. return (getLangOpts().CPlusPlus
  10268. ? LHSType : LHSType.getUnqualifiedType());
  10269. }
  10270. // Only ignore explicit casts to void.
  10271. static bool IgnoreCommaOperand(const Expr *E) {
  10272. E = E->IgnoreParens();
  10273. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10274. if (CE->getCastKind() == CK_ToVoid) {
  10275. return true;
  10276. }
  10277. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10278. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10279. CE->getSubExpr()->getType()->isDependentType()) {
  10280. return true;
  10281. }
  10282. }
  10283. return false;
  10284. }
  10285. // Look for instances where it is likely the comma operator is confused with
  10286. // another operator. There is a whitelist of acceptable expressions for the
  10287. // left hand side of the comma operator, otherwise emit a warning.
  10288. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10289. // No warnings in macros
  10290. if (Loc.isMacroID())
  10291. return;
  10292. // Don't warn in template instantiations.
  10293. if (inTemplateInstantiation())
  10294. return;
  10295. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10296. // instead, skip more than needed, then call back into here with the
  10297. // CommaVisitor in SemaStmt.cpp.
  10298. // The whitelisted locations are the initialization and increment portions
  10299. // of a for loop. The additional checks are on the condition of
  10300. // if statements, do/while loops, and for loops.
  10301. // Differences in scope flags for C89 mode requires the extra logic.
  10302. const unsigned ForIncrementFlags =
  10303. getLangOpts().C99 || getLangOpts().CPlusPlus
  10304. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10305. : Scope::ContinueScope | Scope::BreakScope;
  10306. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10307. const unsigned ScopeFlags = getCurScope()->getFlags();
  10308. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10309. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10310. return;
  10311. // If there are multiple comma operators used together, get the RHS of the
  10312. // of the comma operator as the LHS.
  10313. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10314. if (BO->getOpcode() != BO_Comma)
  10315. break;
  10316. LHS = BO->getRHS();
  10317. }
  10318. // Only allow some expressions on LHS to not warn.
  10319. if (IgnoreCommaOperand(LHS))
  10320. return;
  10321. Diag(Loc, diag::warn_comma_operator);
  10322. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10323. << LHS->getSourceRange()
  10324. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10325. LangOpts.CPlusPlus ? "static_cast<void>("
  10326. : "(void)(")
  10327. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10328. ")");
  10329. }
  10330. // C99 6.5.17
  10331. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10332. SourceLocation Loc) {
  10333. LHS = S.CheckPlaceholderExpr(LHS.get());
  10334. RHS = S.CheckPlaceholderExpr(RHS.get());
  10335. if (LHS.isInvalid() || RHS.isInvalid())
  10336. return QualType();
  10337. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10338. // operands, but not unary promotions.
  10339. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10340. // So we treat the LHS as a ignored value, and in C++ we allow the
  10341. // containing site to determine what should be done with the RHS.
  10342. LHS = S.IgnoredValueConversions(LHS.get());
  10343. if (LHS.isInvalid())
  10344. return QualType();
  10345. S.DiagnoseUnusedExprResult(LHS.get());
  10346. if (!S.getLangOpts().CPlusPlus) {
  10347. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10348. if (RHS.isInvalid())
  10349. return QualType();
  10350. if (!RHS.get()->getType()->isVoidType())
  10351. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10352. diag::err_incomplete_type);
  10353. }
  10354. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10355. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10356. return RHS.get()->getType();
  10357. }
  10358. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10359. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10360. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10361. ExprValueKind &VK,
  10362. ExprObjectKind &OK,
  10363. SourceLocation OpLoc,
  10364. bool IsInc, bool IsPrefix) {
  10365. if (Op->isTypeDependent())
  10366. return S.Context.DependentTy;
  10367. QualType ResType = Op->getType();
  10368. // Atomic types can be used for increment / decrement where the non-atomic
  10369. // versions can, so ignore the _Atomic() specifier for the purpose of
  10370. // checking.
  10371. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10372. ResType = ResAtomicType->getValueType();
  10373. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10374. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10375. // Decrement of bool is not allowed.
  10376. if (!IsInc) {
  10377. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10378. return QualType();
  10379. }
  10380. // Increment of bool sets it to true, but is deprecated.
  10381. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10382. : diag::warn_increment_bool)
  10383. << Op->getSourceRange();
  10384. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10385. // Error on enum increments and decrements in C++ mode
  10386. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10387. return QualType();
  10388. } else if (ResType->isRealType()) {
  10389. // OK!
  10390. } else if (ResType->isPointerType()) {
  10391. // C99 6.5.2.4p2, 6.5.6p2
  10392. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10393. return QualType();
  10394. } else if (ResType->isObjCObjectPointerType()) {
  10395. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10396. // Otherwise, we just need a complete type.
  10397. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10398. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10399. return QualType();
  10400. } else if (ResType->isAnyComplexType()) {
  10401. // C99 does not support ++/-- on complex types, we allow as an extension.
  10402. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10403. << ResType << Op->getSourceRange();
  10404. } else if (ResType->isPlaceholderType()) {
  10405. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10406. if (PR.isInvalid()) return QualType();
  10407. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10408. IsInc, IsPrefix);
  10409. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10410. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10411. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10412. (ResType->getAs<VectorType>()->getVectorKind() !=
  10413. VectorType::AltiVecBool)) {
  10414. // The z vector extensions allow ++ and -- for non-bool vectors.
  10415. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10416. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  10417. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10418. } else {
  10419. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10420. << ResType << int(IsInc) << Op->getSourceRange();
  10421. return QualType();
  10422. }
  10423. // At this point, we know we have a real, complex or pointer type.
  10424. // Now make sure the operand is a modifiable lvalue.
  10425. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10426. return QualType();
  10427. // In C++, a prefix increment is the same type as the operand. Otherwise
  10428. // (in C or with postfix), the increment is the unqualified type of the
  10429. // operand.
  10430. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10431. VK = VK_LValue;
  10432. OK = Op->getObjectKind();
  10433. return ResType;
  10434. } else {
  10435. VK = VK_RValue;
  10436. return ResType.getUnqualifiedType();
  10437. }
  10438. }
  10439. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10440. /// This routine allows us to typecheck complex/recursive expressions
  10441. /// where the declaration is needed for type checking. We only need to
  10442. /// handle cases when the expression references a function designator
  10443. /// or is an lvalue. Here are some examples:
  10444. /// - &(x) => x
  10445. /// - &*****f => f for f a function designator.
  10446. /// - &s.xx => s
  10447. /// - &s.zz[1].yy -> s, if zz is an array
  10448. /// - *(x + 1) -> x, if x is an array
  10449. /// - &"123"[2] -> 0
  10450. /// - & __real__ x -> x
  10451. static ValueDecl *getPrimaryDecl(Expr *E) {
  10452. switch (E->getStmtClass()) {
  10453. case Stmt::DeclRefExprClass:
  10454. return cast<DeclRefExpr>(E)->getDecl();
  10455. case Stmt::MemberExprClass:
  10456. // If this is an arrow operator, the address is an offset from
  10457. // the base's value, so the object the base refers to is
  10458. // irrelevant.
  10459. if (cast<MemberExpr>(E)->isArrow())
  10460. return nullptr;
  10461. // Otherwise, the expression refers to a part of the base
  10462. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10463. case Stmt::ArraySubscriptExprClass: {
  10464. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10465. // promotion of register arrays earlier.
  10466. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10467. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10468. if (ICE->getSubExpr()->getType()->isArrayType())
  10469. return getPrimaryDecl(ICE->getSubExpr());
  10470. }
  10471. return nullptr;
  10472. }
  10473. case Stmt::UnaryOperatorClass: {
  10474. UnaryOperator *UO = cast<UnaryOperator>(E);
  10475. switch(UO->getOpcode()) {
  10476. case UO_Real:
  10477. case UO_Imag:
  10478. case UO_Extension:
  10479. return getPrimaryDecl(UO->getSubExpr());
  10480. default:
  10481. return nullptr;
  10482. }
  10483. }
  10484. case Stmt::ParenExprClass:
  10485. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10486. case Stmt::ImplicitCastExprClass:
  10487. // If the result of an implicit cast is an l-value, we care about
  10488. // the sub-expression; otherwise, the result here doesn't matter.
  10489. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10490. default:
  10491. return nullptr;
  10492. }
  10493. }
  10494. namespace {
  10495. enum {
  10496. AO_Bit_Field = 0,
  10497. AO_Vector_Element = 1,
  10498. AO_Property_Expansion = 2,
  10499. AO_Register_Variable = 3,
  10500. AO_No_Error = 4
  10501. };
  10502. }
  10503. /// Diagnose invalid operand for address of operations.
  10504. ///
  10505. /// \param Type The type of operand which cannot have its address taken.
  10506. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10507. Expr *E, unsigned Type) {
  10508. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10509. }
  10510. /// CheckAddressOfOperand - The operand of & must be either a function
  10511. /// designator or an lvalue designating an object. If it is an lvalue, the
  10512. /// object cannot be declared with storage class register or be a bit field.
  10513. /// Note: The usual conversions are *not* applied to the operand of the &
  10514. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10515. /// In C++, the operand might be an overloaded function name, in which case
  10516. /// we allow the '&' but retain the overloaded-function type.
  10517. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10518. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10519. if (PTy->getKind() == BuiltinType::Overload) {
  10520. Expr *E = OrigOp.get()->IgnoreParens();
  10521. if (!isa<OverloadExpr>(E)) {
  10522. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10523. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10524. << OrigOp.get()->getSourceRange();
  10525. return QualType();
  10526. }
  10527. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10528. if (isa<UnresolvedMemberExpr>(Ovl))
  10529. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10530. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10531. << OrigOp.get()->getSourceRange();
  10532. return QualType();
  10533. }
  10534. return Context.OverloadTy;
  10535. }
  10536. if (PTy->getKind() == BuiltinType::UnknownAny)
  10537. return Context.UnknownAnyTy;
  10538. if (PTy->getKind() == BuiltinType::BoundMember) {
  10539. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10540. << OrigOp.get()->getSourceRange();
  10541. return QualType();
  10542. }
  10543. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10544. if (OrigOp.isInvalid()) return QualType();
  10545. }
  10546. if (OrigOp.get()->isTypeDependent())
  10547. return Context.DependentTy;
  10548. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10549. // Make sure to ignore parentheses in subsequent checks
  10550. Expr *op = OrigOp.get()->IgnoreParens();
  10551. // In OpenCL captures for blocks called as lambda functions
  10552. // are located in the private address space. Blocks used in
  10553. // enqueue_kernel can be located in a different address space
  10554. // depending on a vendor implementation. Thus preventing
  10555. // taking an address of the capture to avoid invalid AS casts.
  10556. if (LangOpts.OpenCL) {
  10557. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10558. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10559. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10560. return QualType();
  10561. }
  10562. }
  10563. if (getLangOpts().C99) {
  10564. // Implement C99-only parts of addressof rules.
  10565. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10566. if (uOp->getOpcode() == UO_Deref)
  10567. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10568. // (assuming the deref expression is valid).
  10569. return uOp->getSubExpr()->getType();
  10570. }
  10571. // Technically, there should be a check for array subscript
  10572. // expressions here, but the result of one is always an lvalue anyway.
  10573. }
  10574. ValueDecl *dcl = getPrimaryDecl(op);
  10575. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10576. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10577. op->getBeginLoc()))
  10578. return QualType();
  10579. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10580. unsigned AddressOfError = AO_No_Error;
  10581. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10582. bool sfinae = (bool)isSFINAEContext();
  10583. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10584. : diag::ext_typecheck_addrof_temporary)
  10585. << op->getType() << op->getSourceRange();
  10586. if (sfinae)
  10587. return QualType();
  10588. // Materialize the temporary as an lvalue so that we can take its address.
  10589. OrigOp = op =
  10590. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10591. } else if (isa<ObjCSelectorExpr>(op)) {
  10592. return Context.getPointerType(op->getType());
  10593. } else if (lval == Expr::LV_MemberFunction) {
  10594. // If it's an instance method, make a member pointer.
  10595. // The expression must have exactly the form &A::foo.
  10596. // If the underlying expression isn't a decl ref, give up.
  10597. if (!isa<DeclRefExpr>(op)) {
  10598. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10599. << OrigOp.get()->getSourceRange();
  10600. return QualType();
  10601. }
  10602. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10603. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10604. // The id-expression was parenthesized.
  10605. if (OrigOp.get() != DRE) {
  10606. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10607. << OrigOp.get()->getSourceRange();
  10608. // The method was named without a qualifier.
  10609. } else if (!DRE->getQualifier()) {
  10610. if (MD->getParent()->getName().empty())
  10611. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10612. << op->getSourceRange();
  10613. else {
  10614. SmallString<32> Str;
  10615. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10616. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10617. << op->getSourceRange()
  10618. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10619. }
  10620. }
  10621. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10622. if (isa<CXXDestructorDecl>(MD))
  10623. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10624. QualType MPTy = Context.getMemberPointerType(
  10625. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10626. // Under the MS ABI, lock down the inheritance model now.
  10627. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10628. (void)isCompleteType(OpLoc, MPTy);
  10629. return MPTy;
  10630. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10631. // C99 6.5.3.2p1
  10632. // The operand must be either an l-value or a function designator
  10633. if (!op->getType()->isFunctionType()) {
  10634. // Use a special diagnostic for loads from property references.
  10635. if (isa<PseudoObjectExpr>(op)) {
  10636. AddressOfError = AO_Property_Expansion;
  10637. } else {
  10638. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10639. << op->getType() << op->getSourceRange();
  10640. return QualType();
  10641. }
  10642. }
  10643. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10644. // The operand cannot be a bit-field
  10645. AddressOfError = AO_Bit_Field;
  10646. } else if (op->getObjectKind() == OK_VectorComponent) {
  10647. // The operand cannot be an element of a vector
  10648. AddressOfError = AO_Vector_Element;
  10649. } else if (dcl) { // C99 6.5.3.2p1
  10650. // We have an lvalue with a decl. Make sure the decl is not declared
  10651. // with the register storage-class specifier.
  10652. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10653. // in C++ it is not error to take address of a register
  10654. // variable (c++03 7.1.1P3)
  10655. if (vd->getStorageClass() == SC_Register &&
  10656. !getLangOpts().CPlusPlus) {
  10657. AddressOfError = AO_Register_Variable;
  10658. }
  10659. } else if (isa<MSPropertyDecl>(dcl)) {
  10660. AddressOfError = AO_Property_Expansion;
  10661. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10662. return Context.OverloadTy;
  10663. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10664. // Okay: we can take the address of a field.
  10665. // Could be a pointer to member, though, if there is an explicit
  10666. // scope qualifier for the class.
  10667. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10668. DeclContext *Ctx = dcl->getDeclContext();
  10669. if (Ctx && Ctx->isRecord()) {
  10670. if (dcl->getType()->isReferenceType()) {
  10671. Diag(OpLoc,
  10672. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10673. << dcl->getDeclName() << dcl->getType();
  10674. return QualType();
  10675. }
  10676. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10677. Ctx = Ctx->getParent();
  10678. QualType MPTy = Context.getMemberPointerType(
  10679. op->getType(),
  10680. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10681. // Under the MS ABI, lock down the inheritance model now.
  10682. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10683. (void)isCompleteType(OpLoc, MPTy);
  10684. return MPTy;
  10685. }
  10686. }
  10687. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10688. !isa<BindingDecl>(dcl))
  10689. llvm_unreachable("Unknown/unexpected decl type");
  10690. }
  10691. if (AddressOfError != AO_No_Error) {
  10692. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10693. return QualType();
  10694. }
  10695. if (lval == Expr::LV_IncompleteVoidType) {
  10696. // Taking the address of a void variable is technically illegal, but we
  10697. // allow it in cases which are otherwise valid.
  10698. // Example: "extern void x; void* y = &x;".
  10699. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10700. }
  10701. // If the operand has type "type", the result has type "pointer to type".
  10702. if (op->getType()->isObjCObjectType())
  10703. return Context.getObjCObjectPointerType(op->getType());
  10704. CheckAddressOfPackedMember(op);
  10705. return Context.getPointerType(op->getType());
  10706. }
  10707. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10708. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10709. if (!DRE)
  10710. return;
  10711. const Decl *D = DRE->getDecl();
  10712. if (!D)
  10713. return;
  10714. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10715. if (!Param)
  10716. return;
  10717. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10718. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10719. return;
  10720. if (FunctionScopeInfo *FD = S.getCurFunction())
  10721. if (!FD->ModifiedNonNullParams.count(Param))
  10722. FD->ModifiedNonNullParams.insert(Param);
  10723. }
  10724. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10725. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10726. SourceLocation OpLoc) {
  10727. if (Op->isTypeDependent())
  10728. return S.Context.DependentTy;
  10729. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10730. if (ConvResult.isInvalid())
  10731. return QualType();
  10732. Op = ConvResult.get();
  10733. QualType OpTy = Op->getType();
  10734. QualType Result;
  10735. if (isa<CXXReinterpretCastExpr>(Op)) {
  10736. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10737. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10738. Op->getSourceRange());
  10739. }
  10740. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10741. {
  10742. Result = PT->getPointeeType();
  10743. }
  10744. else if (const ObjCObjectPointerType *OPT =
  10745. OpTy->getAs<ObjCObjectPointerType>())
  10746. Result = OPT->getPointeeType();
  10747. else {
  10748. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10749. if (PR.isInvalid()) return QualType();
  10750. if (PR.get() != Op)
  10751. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  10752. }
  10753. if (Result.isNull()) {
  10754. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  10755. << OpTy << Op->getSourceRange();
  10756. return QualType();
  10757. }
  10758. // Note that per both C89 and C99, indirection is always legal, even if Result
  10759. // is an incomplete type or void. It would be possible to warn about
  10760. // dereferencing a void pointer, but it's completely well-defined, and such a
  10761. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  10762. // for pointers to 'void' but is fine for any other pointer type:
  10763. //
  10764. // C++ [expr.unary.op]p1:
  10765. // [...] the expression to which [the unary * operator] is applied shall
  10766. // be a pointer to an object type, or a pointer to a function type
  10767. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  10768. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  10769. << OpTy << Op->getSourceRange();
  10770. // Dereferences are usually l-values...
  10771. VK = VK_LValue;
  10772. // ...except that certain expressions are never l-values in C.
  10773. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  10774. VK = VK_RValue;
  10775. return Result;
  10776. }
  10777. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10778. BinaryOperatorKind Opc;
  10779. switch (Kind) {
  10780. default: llvm_unreachable("Unknown binop!");
  10781. case tok::periodstar: Opc = BO_PtrMemD; break;
  10782. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10783. case tok::star: Opc = BO_Mul; break;
  10784. case tok::slash: Opc = BO_Div; break;
  10785. case tok::percent: Opc = BO_Rem; break;
  10786. case tok::plus: Opc = BO_Add; break;
  10787. case tok::minus: Opc = BO_Sub; break;
  10788. case tok::lessless: Opc = BO_Shl; break;
  10789. case tok::greatergreater: Opc = BO_Shr; break;
  10790. case tok::lessequal: Opc = BO_LE; break;
  10791. case tok::less: Opc = BO_LT; break;
  10792. case tok::greaterequal: Opc = BO_GE; break;
  10793. case tok::greater: Opc = BO_GT; break;
  10794. case tok::exclaimequal: Opc = BO_NE; break;
  10795. case tok::equalequal: Opc = BO_EQ; break;
  10796. case tok::spaceship: Opc = BO_Cmp; break;
  10797. case tok::amp: Opc = BO_And; break;
  10798. case tok::caret: Opc = BO_Xor; break;
  10799. case tok::pipe: Opc = BO_Or; break;
  10800. case tok::ampamp: Opc = BO_LAnd; break;
  10801. case tok::pipepipe: Opc = BO_LOr; break;
  10802. case tok::equal: Opc = BO_Assign; break;
  10803. case tok::starequal: Opc = BO_MulAssign; break;
  10804. case tok::slashequal: Opc = BO_DivAssign; break;
  10805. case tok::percentequal: Opc = BO_RemAssign; break;
  10806. case tok::plusequal: Opc = BO_AddAssign; break;
  10807. case tok::minusequal: Opc = BO_SubAssign; break;
  10808. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  10809. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  10810. case tok::ampequal: Opc = BO_AndAssign; break;
  10811. case tok::caretequal: Opc = BO_XorAssign; break;
  10812. case tok::pipeequal: Opc = BO_OrAssign; break;
  10813. case tok::comma: Opc = BO_Comma; break;
  10814. }
  10815. return Opc;
  10816. }
  10817. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  10818. tok::TokenKind Kind) {
  10819. UnaryOperatorKind Opc;
  10820. switch (Kind) {
  10821. default: llvm_unreachable("Unknown unary op!");
  10822. case tok::plusplus: Opc = UO_PreInc; break;
  10823. case tok::minusminus: Opc = UO_PreDec; break;
  10824. case tok::amp: Opc = UO_AddrOf; break;
  10825. case tok::star: Opc = UO_Deref; break;
  10826. case tok::plus: Opc = UO_Plus; break;
  10827. case tok::minus: Opc = UO_Minus; break;
  10828. case tok::tilde: Opc = UO_Not; break;
  10829. case tok::exclaim: Opc = UO_LNot; break;
  10830. case tok::kw___real: Opc = UO_Real; break;
  10831. case tok::kw___imag: Opc = UO_Imag; break;
  10832. case tok::kw___extension__: Opc = UO_Extension; break;
  10833. }
  10834. return Opc;
  10835. }
  10836. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  10837. /// This warning suppressed in the event of macro expansions.
  10838. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  10839. SourceLocation OpLoc, bool IsBuiltin) {
  10840. if (S.inTemplateInstantiation())
  10841. return;
  10842. if (S.isUnevaluatedContext())
  10843. return;
  10844. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  10845. return;
  10846. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10847. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10848. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10849. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10850. if (!LHSDeclRef || !RHSDeclRef ||
  10851. LHSDeclRef->getLocation().isMacroID() ||
  10852. RHSDeclRef->getLocation().isMacroID())
  10853. return;
  10854. const ValueDecl *LHSDecl =
  10855. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  10856. const ValueDecl *RHSDecl =
  10857. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  10858. if (LHSDecl != RHSDecl)
  10859. return;
  10860. if (LHSDecl->getType().isVolatileQualified())
  10861. return;
  10862. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10863. if (RefTy->getPointeeType().isVolatileQualified())
  10864. return;
  10865. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  10866. : diag::warn_self_assignment_overloaded)
  10867. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  10868. << RHSExpr->getSourceRange();
  10869. }
  10870. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  10871. /// is usually indicative of introspection within the Objective-C pointer.
  10872. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  10873. SourceLocation OpLoc) {
  10874. if (!S.getLangOpts().ObjC)
  10875. return;
  10876. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  10877. const Expr *LHS = L.get();
  10878. const Expr *RHS = R.get();
  10879. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10880. ObjCPointerExpr = LHS;
  10881. OtherExpr = RHS;
  10882. }
  10883. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10884. ObjCPointerExpr = RHS;
  10885. OtherExpr = LHS;
  10886. }
  10887. // This warning is deliberately made very specific to reduce false
  10888. // positives with logic that uses '&' for hashing. This logic mainly
  10889. // looks for code trying to introspect into tagged pointers, which
  10890. // code should generally never do.
  10891. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  10892. unsigned Diag = diag::warn_objc_pointer_masking;
  10893. // Determine if we are introspecting the result of performSelectorXXX.
  10894. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  10895. // Special case messages to -performSelector and friends, which
  10896. // can return non-pointer values boxed in a pointer value.
  10897. // Some clients may wish to silence warnings in this subcase.
  10898. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  10899. Selector S = ME->getSelector();
  10900. StringRef SelArg0 = S.getNameForSlot(0);
  10901. if (SelArg0.startswith("performSelector"))
  10902. Diag = diag::warn_objc_pointer_masking_performSelector;
  10903. }
  10904. S.Diag(OpLoc, Diag)
  10905. << ObjCPointerExpr->getSourceRange();
  10906. }
  10907. }
  10908. static NamedDecl *getDeclFromExpr(Expr *E) {
  10909. if (!E)
  10910. return nullptr;
  10911. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  10912. return DRE->getDecl();
  10913. if (auto *ME = dyn_cast<MemberExpr>(E))
  10914. return ME->getMemberDecl();
  10915. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  10916. return IRE->getDecl();
  10917. return nullptr;
  10918. }
  10919. // This helper function promotes a binary operator's operands (which are of a
  10920. // half vector type) to a vector of floats and then truncates the result to
  10921. // a vector of either half or short.
  10922. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  10923. BinaryOperatorKind Opc, QualType ResultTy,
  10924. ExprValueKind VK, ExprObjectKind OK,
  10925. bool IsCompAssign, SourceLocation OpLoc,
  10926. FPOptions FPFeatures) {
  10927. auto &Context = S.getASTContext();
  10928. assert((isVector(ResultTy, Context.HalfTy) ||
  10929. isVector(ResultTy, Context.ShortTy)) &&
  10930. "Result must be a vector of half or short");
  10931. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  10932. isVector(RHS.get()->getType(), Context.HalfTy) &&
  10933. "both operands expected to be a half vector");
  10934. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  10935. QualType BinOpResTy = RHS.get()->getType();
  10936. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  10937. // change BinOpResTy to a vector of ints.
  10938. if (isVector(ResultTy, Context.ShortTy))
  10939. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  10940. if (IsCompAssign)
  10941. return new (Context) CompoundAssignOperator(
  10942. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  10943. OpLoc, FPFeatures);
  10944. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  10945. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  10946. VK, OK, OpLoc, FPFeatures);
  10947. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  10948. }
  10949. static std::pair<ExprResult, ExprResult>
  10950. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  10951. Expr *RHSExpr) {
  10952. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10953. if (!S.getLangOpts().CPlusPlus) {
  10954. // C cannot handle TypoExpr nodes on either side of a binop because it
  10955. // doesn't handle dependent types properly, so make sure any TypoExprs have
  10956. // been dealt with before checking the operands.
  10957. LHS = S.CorrectDelayedTyposInExpr(LHS);
  10958. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  10959. if (Opc != BO_Assign)
  10960. return ExprResult(E);
  10961. // Avoid correcting the RHS to the same Expr as the LHS.
  10962. Decl *D = getDeclFromExpr(E);
  10963. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  10964. });
  10965. }
  10966. return std::make_pair(LHS, RHS);
  10967. }
  10968. /// Returns true if conversion between vectors of halfs and vectors of floats
  10969. /// is needed.
  10970. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  10971. QualType SrcType) {
  10972. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  10973. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  10974. isVector(SrcType, Ctx.HalfTy);
  10975. }
  10976. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  10977. /// operator @p Opc at location @c TokLoc. This routine only supports
  10978. /// built-in operations; ActOnBinOp handles overloaded operators.
  10979. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  10980. BinaryOperatorKind Opc,
  10981. Expr *LHSExpr, Expr *RHSExpr) {
  10982. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  10983. // The syntax only allows initializer lists on the RHS of assignment,
  10984. // so we don't need to worry about accepting invalid code for
  10985. // non-assignment operators.
  10986. // C++11 5.17p9:
  10987. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  10988. // of x = {} is x = T().
  10989. InitializationKind Kind = InitializationKind::CreateDirectList(
  10990. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10991. InitializedEntity Entity =
  10992. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  10993. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  10994. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  10995. if (Init.isInvalid())
  10996. return Init;
  10997. RHSExpr = Init.get();
  10998. }
  10999. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11000. QualType ResultTy; // Result type of the binary operator.
  11001. // The following two variables are used for compound assignment operators
  11002. QualType CompLHSTy; // Type of LHS after promotions for computation
  11003. QualType CompResultTy; // Type of computation result
  11004. ExprValueKind VK = VK_RValue;
  11005. ExprObjectKind OK = OK_Ordinary;
  11006. bool ConvertHalfVec = false;
  11007. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11008. if (!LHS.isUsable() || !RHS.isUsable())
  11009. return ExprError();
  11010. if (getLangOpts().OpenCL) {
  11011. QualType LHSTy = LHSExpr->getType();
  11012. QualType RHSTy = RHSExpr->getType();
  11013. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  11014. // the ATOMIC_VAR_INIT macro.
  11015. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  11016. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11017. if (BO_Assign == Opc)
  11018. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  11019. else
  11020. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11021. return ExprError();
  11022. }
  11023. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11024. // only with a builtin functions and therefore should be disallowed here.
  11025. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  11026. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  11027. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  11028. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  11029. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11030. return ExprError();
  11031. }
  11032. }
  11033. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11034. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11035. if (Opc != BO_Assign && Opc != BO_Comma) {
  11036. checkOpenMPDeviceExpr(LHSExpr);
  11037. checkOpenMPDeviceExpr(RHSExpr);
  11038. }
  11039. }
  11040. switch (Opc) {
  11041. case BO_Assign:
  11042. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  11043. if (getLangOpts().CPlusPlus &&
  11044. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  11045. VK = LHS.get()->getValueKind();
  11046. OK = LHS.get()->getObjectKind();
  11047. }
  11048. if (!ResultTy.isNull()) {
  11049. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11050. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  11051. // Avoid copying a block to the heap if the block is assigned to a local
  11052. // auto variable that is declared in the same scope as the block. This
  11053. // optimization is unsafe if the local variable is declared in an outer
  11054. // scope. For example:
  11055. //
  11056. // BlockTy b;
  11057. // {
  11058. // b = ^{...};
  11059. // }
  11060. // // It is unsafe to invoke the block here if it wasn't copied to the
  11061. // // heap.
  11062. // b();
  11063. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  11064. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  11065. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11066. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11067. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11068. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11069. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  11070. NTCUC_Assignment, NTCUK_Copy);
  11071. }
  11072. RecordModifiableNonNullParam(*this, LHS.get());
  11073. break;
  11074. case BO_PtrMemD:
  11075. case BO_PtrMemI:
  11076. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11077. Opc == BO_PtrMemI);
  11078. break;
  11079. case BO_Mul:
  11080. case BO_Div:
  11081. ConvertHalfVec = true;
  11082. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11083. Opc == BO_Div);
  11084. break;
  11085. case BO_Rem:
  11086. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11087. break;
  11088. case BO_Add:
  11089. ConvertHalfVec = true;
  11090. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11091. break;
  11092. case BO_Sub:
  11093. ConvertHalfVec = true;
  11094. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11095. break;
  11096. case BO_Shl:
  11097. case BO_Shr:
  11098. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11099. break;
  11100. case BO_LE:
  11101. case BO_LT:
  11102. case BO_GE:
  11103. case BO_GT:
  11104. ConvertHalfVec = true;
  11105. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11106. break;
  11107. case BO_EQ:
  11108. case BO_NE:
  11109. ConvertHalfVec = true;
  11110. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11111. break;
  11112. case BO_Cmp:
  11113. ConvertHalfVec = true;
  11114. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11115. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11116. break;
  11117. case BO_And:
  11118. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11119. LLVM_FALLTHROUGH;
  11120. case BO_Xor:
  11121. case BO_Or:
  11122. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11123. break;
  11124. case BO_LAnd:
  11125. case BO_LOr:
  11126. ConvertHalfVec = true;
  11127. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11128. break;
  11129. case BO_MulAssign:
  11130. case BO_DivAssign:
  11131. ConvertHalfVec = true;
  11132. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11133. Opc == BO_DivAssign);
  11134. CompLHSTy = CompResultTy;
  11135. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11136. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11137. break;
  11138. case BO_RemAssign:
  11139. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11140. CompLHSTy = CompResultTy;
  11141. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11142. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11143. break;
  11144. case BO_AddAssign:
  11145. ConvertHalfVec = true;
  11146. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11147. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11148. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11149. break;
  11150. case BO_SubAssign:
  11151. ConvertHalfVec = true;
  11152. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11153. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11154. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11155. break;
  11156. case BO_ShlAssign:
  11157. case BO_ShrAssign:
  11158. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11159. CompLHSTy = CompResultTy;
  11160. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11161. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11162. break;
  11163. case BO_AndAssign:
  11164. case BO_OrAssign: // fallthrough
  11165. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11166. LLVM_FALLTHROUGH;
  11167. case BO_XorAssign:
  11168. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11169. CompLHSTy = CompResultTy;
  11170. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11171. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11172. break;
  11173. case BO_Comma:
  11174. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11175. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11176. VK = RHS.get()->getValueKind();
  11177. OK = RHS.get()->getObjectKind();
  11178. }
  11179. break;
  11180. }
  11181. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11182. return ExprError();
  11183. // Some of the binary operations require promoting operands of half vector to
  11184. // float vectors and truncating the result back to half vector. For now, we do
  11185. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11186. // arm64).
  11187. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11188. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11189. "both sides are half vectors or neither sides are");
  11190. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11191. LHS.get()->getType());
  11192. // Check for array bounds violations for both sides of the BinaryOperator
  11193. CheckArrayAccess(LHS.get());
  11194. CheckArrayAccess(RHS.get());
  11195. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11196. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11197. &Context.Idents.get("object_setClass"),
  11198. SourceLocation(), LookupOrdinaryName);
  11199. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11200. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11201. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11202. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11203. "object_setClass(")
  11204. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11205. ",")
  11206. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11207. }
  11208. else
  11209. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11210. }
  11211. else if (const ObjCIvarRefExpr *OIRE =
  11212. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11213. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11214. // Opc is not a compound assignment if CompResultTy is null.
  11215. if (CompResultTy.isNull()) {
  11216. if (ConvertHalfVec)
  11217. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11218. OpLoc, FPFeatures);
  11219. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11220. OK, OpLoc, FPFeatures);
  11221. }
  11222. // Handle compound assignments.
  11223. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11224. OK_ObjCProperty) {
  11225. VK = VK_LValue;
  11226. OK = LHS.get()->getObjectKind();
  11227. }
  11228. if (ConvertHalfVec)
  11229. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11230. OpLoc, FPFeatures);
  11231. return new (Context) CompoundAssignOperator(
  11232. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11233. OpLoc, FPFeatures);
  11234. }
  11235. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11236. /// operators are mixed in a way that suggests that the programmer forgot that
  11237. /// comparison operators have higher precedence. The most typical example of
  11238. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11239. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11240. SourceLocation OpLoc, Expr *LHSExpr,
  11241. Expr *RHSExpr) {
  11242. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11243. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11244. // Check that one of the sides is a comparison operator and the other isn't.
  11245. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11246. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11247. if (isLeftComp == isRightComp)
  11248. return;
  11249. // Bitwise operations are sometimes used as eager logical ops.
  11250. // Don't diagnose this.
  11251. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11252. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11253. if (isLeftBitwise || isRightBitwise)
  11254. return;
  11255. SourceRange DiagRange = isLeftComp
  11256. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11257. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11258. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11259. SourceRange ParensRange =
  11260. isLeftComp
  11261. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11262. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11263. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11264. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11265. SuggestParentheses(Self, OpLoc,
  11266. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11267. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11268. SuggestParentheses(Self, OpLoc,
  11269. Self.PDiag(diag::note_precedence_bitwise_first)
  11270. << BinaryOperator::getOpcodeStr(Opc),
  11271. ParensRange);
  11272. }
  11273. /// It accepts a '&&' expr that is inside a '||' one.
  11274. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11275. /// in parentheses.
  11276. static void
  11277. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11278. BinaryOperator *Bop) {
  11279. assert(Bop->getOpcode() == BO_LAnd);
  11280. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11281. << Bop->getSourceRange() << OpLoc;
  11282. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11283. Self.PDiag(diag::note_precedence_silence)
  11284. << Bop->getOpcodeStr(),
  11285. Bop->getSourceRange());
  11286. }
  11287. /// Returns true if the given expression can be evaluated as a constant
  11288. /// 'true'.
  11289. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11290. bool Res;
  11291. return !E->isValueDependent() &&
  11292. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11293. }
  11294. /// Returns true if the given expression can be evaluated as a constant
  11295. /// 'false'.
  11296. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11297. bool Res;
  11298. return !E->isValueDependent() &&
  11299. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11300. }
  11301. /// Look for '&&' in the left hand of a '||' expr.
  11302. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11303. Expr *LHSExpr, Expr *RHSExpr) {
  11304. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11305. if (Bop->getOpcode() == BO_LAnd) {
  11306. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11307. if (EvaluatesAsFalse(S, RHSExpr))
  11308. return;
  11309. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11310. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11311. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11312. } else if (Bop->getOpcode() == BO_LOr) {
  11313. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11314. // If it's "a || b && 1 || c" we didn't warn earlier for
  11315. // "a || b && 1", but warn now.
  11316. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11317. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11318. }
  11319. }
  11320. }
  11321. }
  11322. /// Look for '&&' in the right hand of a '||' expr.
  11323. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11324. Expr *LHSExpr, Expr *RHSExpr) {
  11325. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11326. if (Bop->getOpcode() == BO_LAnd) {
  11327. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11328. if (EvaluatesAsFalse(S, LHSExpr))
  11329. return;
  11330. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11331. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11332. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11333. }
  11334. }
  11335. }
  11336. /// Look for bitwise op in the left or right hand of a bitwise op with
  11337. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11338. /// the '&' expression in parentheses.
  11339. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11340. SourceLocation OpLoc, Expr *SubExpr) {
  11341. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11342. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11343. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11344. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11345. << Bop->getSourceRange() << OpLoc;
  11346. SuggestParentheses(S, Bop->getOperatorLoc(),
  11347. S.PDiag(diag::note_precedence_silence)
  11348. << Bop->getOpcodeStr(),
  11349. Bop->getSourceRange());
  11350. }
  11351. }
  11352. }
  11353. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11354. Expr *SubExpr, StringRef Shift) {
  11355. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11356. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11357. StringRef Op = Bop->getOpcodeStr();
  11358. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11359. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11360. SuggestParentheses(S, Bop->getOperatorLoc(),
  11361. S.PDiag(diag::note_precedence_silence) << Op,
  11362. Bop->getSourceRange());
  11363. }
  11364. }
  11365. }
  11366. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11367. Expr *LHSExpr, Expr *RHSExpr) {
  11368. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11369. if (!OCE)
  11370. return;
  11371. FunctionDecl *FD = OCE->getDirectCallee();
  11372. if (!FD || !FD->isOverloadedOperator())
  11373. return;
  11374. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11375. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11376. return;
  11377. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11378. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11379. << (Kind == OO_LessLess);
  11380. SuggestParentheses(S, OCE->getOperatorLoc(),
  11381. S.PDiag(diag::note_precedence_silence)
  11382. << (Kind == OO_LessLess ? "<<" : ">>"),
  11383. OCE->getSourceRange());
  11384. SuggestParentheses(
  11385. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11386. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11387. }
  11388. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11389. /// precedence.
  11390. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11391. SourceLocation OpLoc, Expr *LHSExpr,
  11392. Expr *RHSExpr){
  11393. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11394. if (BinaryOperator::isBitwiseOp(Opc))
  11395. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11396. // Diagnose "arg1 & arg2 | arg3"
  11397. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11398. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11399. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11400. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11401. }
  11402. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11403. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11404. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11405. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11406. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11407. }
  11408. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11409. || Opc == BO_Shr) {
  11410. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11411. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11412. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11413. }
  11414. // Warn on overloaded shift operators and comparisons, such as:
  11415. // cout << 5 == 4;
  11416. if (BinaryOperator::isComparisonOp(Opc))
  11417. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11418. }
  11419. // Binary Operators. 'Tok' is the token for the operator.
  11420. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11421. tok::TokenKind Kind,
  11422. Expr *LHSExpr, Expr *RHSExpr) {
  11423. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11424. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11425. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11426. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11427. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11428. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11429. }
  11430. /// Build an overloaded binary operator expression in the given scope.
  11431. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11432. BinaryOperatorKind Opc,
  11433. Expr *LHS, Expr *RHS) {
  11434. switch (Opc) {
  11435. case BO_Assign:
  11436. case BO_DivAssign:
  11437. case BO_RemAssign:
  11438. case BO_SubAssign:
  11439. case BO_AndAssign:
  11440. case BO_OrAssign:
  11441. case BO_XorAssign:
  11442. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11443. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11444. break;
  11445. default:
  11446. break;
  11447. }
  11448. // Find all of the overloaded operators visible from this
  11449. // point. We perform both an operator-name lookup from the local
  11450. // scope and an argument-dependent lookup based on the types of
  11451. // the arguments.
  11452. UnresolvedSet<16> Functions;
  11453. OverloadedOperatorKind OverOp
  11454. = BinaryOperator::getOverloadedOperator(Opc);
  11455. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11456. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11457. RHS->getType(), Functions);
  11458. // Build the (potentially-overloaded, potentially-dependent)
  11459. // binary operation.
  11460. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11461. }
  11462. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11463. BinaryOperatorKind Opc,
  11464. Expr *LHSExpr, Expr *RHSExpr) {
  11465. ExprResult LHS, RHS;
  11466. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11467. if (!LHS.isUsable() || !RHS.isUsable())
  11468. return ExprError();
  11469. LHSExpr = LHS.get();
  11470. RHSExpr = RHS.get();
  11471. // We want to end up calling one of checkPseudoObjectAssignment
  11472. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11473. // both expressions are overloadable or either is type-dependent),
  11474. // or CreateBuiltinBinOp (in any other case). We also want to get
  11475. // any placeholder types out of the way.
  11476. // Handle pseudo-objects in the LHS.
  11477. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11478. // Assignments with a pseudo-object l-value need special analysis.
  11479. if (pty->getKind() == BuiltinType::PseudoObject &&
  11480. BinaryOperator::isAssignmentOp(Opc))
  11481. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11482. // Don't resolve overloads if the other type is overloadable.
  11483. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11484. // We can't actually test that if we still have a placeholder,
  11485. // though. Fortunately, none of the exceptions we see in that
  11486. // code below are valid when the LHS is an overload set. Note
  11487. // that an overload set can be dependently-typed, but it never
  11488. // instantiates to having an overloadable type.
  11489. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11490. if (resolvedRHS.isInvalid()) return ExprError();
  11491. RHSExpr = resolvedRHS.get();
  11492. if (RHSExpr->isTypeDependent() ||
  11493. RHSExpr->getType()->isOverloadableType())
  11494. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11495. }
  11496. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11497. // template, diagnose the missing 'template' keyword instead of diagnosing
  11498. // an invalid use of a bound member function.
  11499. //
  11500. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11501. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11502. if (Opc == BO_LT && inTemplateInstantiation() &&
  11503. (pty->getKind() == BuiltinType::BoundMember ||
  11504. pty->getKind() == BuiltinType::Overload)) {
  11505. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11506. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11507. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11508. return isa<FunctionTemplateDecl>(ND);
  11509. })) {
  11510. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11511. : OE->getNameLoc(),
  11512. diag::err_template_kw_missing)
  11513. << OE->getName().getAsString() << "";
  11514. return ExprError();
  11515. }
  11516. }
  11517. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11518. if (LHS.isInvalid()) return ExprError();
  11519. LHSExpr = LHS.get();
  11520. }
  11521. // Handle pseudo-objects in the RHS.
  11522. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11523. // An overload in the RHS can potentially be resolved by the type
  11524. // being assigned to.
  11525. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11526. if (getLangOpts().CPlusPlus &&
  11527. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11528. LHSExpr->getType()->isOverloadableType()))
  11529. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11530. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11531. }
  11532. // Don't resolve overloads if the other type is overloadable.
  11533. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11534. LHSExpr->getType()->isOverloadableType())
  11535. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11536. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11537. if (!resolvedRHS.isUsable()) return ExprError();
  11538. RHSExpr = resolvedRHS.get();
  11539. }
  11540. if (getLangOpts().CPlusPlus) {
  11541. // If either expression is type-dependent, always build an
  11542. // overloaded op.
  11543. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11544. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11545. // Otherwise, build an overloaded op if either expression has an
  11546. // overloadable type.
  11547. if (LHSExpr->getType()->isOverloadableType() ||
  11548. RHSExpr->getType()->isOverloadableType())
  11549. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11550. }
  11551. // Build a built-in binary operation.
  11552. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11553. }
  11554. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11555. if (T.isNull() || T->isDependentType())
  11556. return false;
  11557. if (!T->isPromotableIntegerType())
  11558. return true;
  11559. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11560. }
  11561. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11562. UnaryOperatorKind Opc,
  11563. Expr *InputExpr) {
  11564. ExprResult Input = InputExpr;
  11565. ExprValueKind VK = VK_RValue;
  11566. ExprObjectKind OK = OK_Ordinary;
  11567. QualType resultType;
  11568. bool CanOverflow = false;
  11569. bool ConvertHalfVec = false;
  11570. if (getLangOpts().OpenCL) {
  11571. QualType Ty = InputExpr->getType();
  11572. // The only legal unary operation for atomics is '&'.
  11573. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11574. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11575. // only with a builtin functions and therefore should be disallowed here.
  11576. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11577. || Ty->isBlockPointerType())) {
  11578. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11579. << InputExpr->getType()
  11580. << Input.get()->getSourceRange());
  11581. }
  11582. }
  11583. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11584. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11585. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11586. UnaryOperator::isArithmeticOp(Opc))
  11587. checkOpenMPDeviceExpr(InputExpr);
  11588. }
  11589. switch (Opc) {
  11590. case UO_PreInc:
  11591. case UO_PreDec:
  11592. case UO_PostInc:
  11593. case UO_PostDec:
  11594. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11595. OpLoc,
  11596. Opc == UO_PreInc ||
  11597. Opc == UO_PostInc,
  11598. Opc == UO_PreInc ||
  11599. Opc == UO_PreDec);
  11600. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11601. break;
  11602. case UO_AddrOf:
  11603. resultType = CheckAddressOfOperand(Input, OpLoc);
  11604. CheckAddressOfNoDeref(InputExpr);
  11605. RecordModifiableNonNullParam(*this, InputExpr);
  11606. break;
  11607. case UO_Deref: {
  11608. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11609. if (Input.isInvalid()) return ExprError();
  11610. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11611. break;
  11612. }
  11613. case UO_Plus:
  11614. case UO_Minus:
  11615. CanOverflow = Opc == UO_Minus &&
  11616. isOverflowingIntegerType(Context, Input.get()->getType());
  11617. Input = UsualUnaryConversions(Input.get());
  11618. if (Input.isInvalid()) return ExprError();
  11619. // Unary plus and minus require promoting an operand of half vector to a
  11620. // float vector and truncating the result back to a half vector. For now, we
  11621. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11622. // arm or arm64).
  11623. ConvertHalfVec =
  11624. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11625. // If the operand is a half vector, promote it to a float vector.
  11626. if (ConvertHalfVec)
  11627. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11628. resultType = Input.get()->getType();
  11629. if (resultType->isDependentType())
  11630. break;
  11631. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11632. break;
  11633. else if (resultType->isVectorType() &&
  11634. // The z vector extensions don't allow + or - with bool vectors.
  11635. (!Context.getLangOpts().ZVector ||
  11636. resultType->getAs<VectorType>()->getVectorKind() !=
  11637. VectorType::AltiVecBool))
  11638. break;
  11639. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11640. Opc == UO_Plus &&
  11641. resultType->isPointerType())
  11642. break;
  11643. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11644. << resultType << Input.get()->getSourceRange());
  11645. case UO_Not: // bitwise complement
  11646. Input = UsualUnaryConversions(Input.get());
  11647. if (Input.isInvalid())
  11648. return ExprError();
  11649. resultType = Input.get()->getType();
  11650. if (resultType->isDependentType())
  11651. break;
  11652. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11653. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11654. // C99 does not support '~' for complex conjugation.
  11655. Diag(OpLoc, diag::ext_integer_complement_complex)
  11656. << resultType << Input.get()->getSourceRange();
  11657. else if (resultType->hasIntegerRepresentation())
  11658. break;
  11659. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11660. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11661. // on vector float types.
  11662. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11663. if (!T->isIntegerType())
  11664. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11665. << resultType << Input.get()->getSourceRange());
  11666. } else {
  11667. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11668. << resultType << Input.get()->getSourceRange());
  11669. }
  11670. break;
  11671. case UO_LNot: // logical negation
  11672. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11673. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11674. if (Input.isInvalid()) return ExprError();
  11675. resultType = Input.get()->getType();
  11676. // Though we still have to promote half FP to float...
  11677. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11678. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11679. resultType = Context.FloatTy;
  11680. }
  11681. if (resultType->isDependentType())
  11682. break;
  11683. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11684. // C99 6.5.3.3p1: ok, fallthrough;
  11685. if (Context.getLangOpts().CPlusPlus) {
  11686. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11687. // operand contextually converted to bool.
  11688. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11689. ScalarTypeToBooleanCastKind(resultType));
  11690. } else if (Context.getLangOpts().OpenCL &&
  11691. Context.getLangOpts().OpenCLVersion < 120) {
  11692. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11693. // operate on scalar float types.
  11694. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11695. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11696. << resultType << Input.get()->getSourceRange());
  11697. }
  11698. } else if (resultType->isExtVectorType()) {
  11699. if (Context.getLangOpts().OpenCL &&
  11700. Context.getLangOpts().OpenCLVersion < 120 &&
  11701. !Context.getLangOpts().OpenCLCPlusPlus) {
  11702. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11703. // operate on vector float types.
  11704. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11705. if (!T->isIntegerType())
  11706. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11707. << resultType << Input.get()->getSourceRange());
  11708. }
  11709. // Vector logical not returns the signed variant of the operand type.
  11710. resultType = GetSignedVectorType(resultType);
  11711. break;
  11712. } else {
  11713. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11714. // type in C++. We should allow that here too.
  11715. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11716. << resultType << Input.get()->getSourceRange());
  11717. }
  11718. // LNot always has type int. C99 6.5.3.3p5.
  11719. // In C++, it's bool. C++ 5.3.1p8
  11720. resultType = Context.getLogicalOperationType();
  11721. break;
  11722. case UO_Real:
  11723. case UO_Imag:
  11724. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11725. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11726. // complex l-values to ordinary l-values and all other values to r-values.
  11727. if (Input.isInvalid()) return ExprError();
  11728. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11729. if (Input.get()->getValueKind() != VK_RValue &&
  11730. Input.get()->getObjectKind() == OK_Ordinary)
  11731. VK = Input.get()->getValueKind();
  11732. } else if (!getLangOpts().CPlusPlus) {
  11733. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11734. Input = DefaultLvalueConversion(Input.get());
  11735. }
  11736. break;
  11737. case UO_Extension:
  11738. resultType = Input.get()->getType();
  11739. VK = Input.get()->getValueKind();
  11740. OK = Input.get()->getObjectKind();
  11741. break;
  11742. case UO_Coawait:
  11743. // It's unnecessary to represent the pass-through operator co_await in the
  11744. // AST; just return the input expression instead.
  11745. assert(!Input.get()->getType()->isDependentType() &&
  11746. "the co_await expression must be non-dependant before "
  11747. "building operator co_await");
  11748. return Input;
  11749. }
  11750. if (resultType.isNull() || Input.isInvalid())
  11751. return ExprError();
  11752. // Check for array bounds violations in the operand of the UnaryOperator,
  11753. // except for the '*' and '&' operators that have to be handled specially
  11754. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  11755. // that are explicitly defined as valid by the standard).
  11756. if (Opc != UO_AddrOf && Opc != UO_Deref)
  11757. CheckArrayAccess(Input.get());
  11758. auto *UO = new (Context)
  11759. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  11760. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  11761. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  11762. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  11763. // Convert the result back to a half vector.
  11764. if (ConvertHalfVec)
  11765. return convertVector(UO, Context.HalfTy, *this);
  11766. return UO;
  11767. }
  11768. /// Determine whether the given expression is a qualified member
  11769. /// access expression, of a form that could be turned into a pointer to member
  11770. /// with the address-of operator.
  11771. bool Sema::isQualifiedMemberAccess(Expr *E) {
  11772. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11773. if (!DRE->getQualifier())
  11774. return false;
  11775. ValueDecl *VD = DRE->getDecl();
  11776. if (!VD->isCXXClassMember())
  11777. return false;
  11778. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  11779. return true;
  11780. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  11781. return Method->isInstance();
  11782. return false;
  11783. }
  11784. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11785. if (!ULE->getQualifier())
  11786. return false;
  11787. for (NamedDecl *D : ULE->decls()) {
  11788. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  11789. if (Method->isInstance())
  11790. return true;
  11791. } else {
  11792. // Overload set does not contain methods.
  11793. break;
  11794. }
  11795. }
  11796. return false;
  11797. }
  11798. return false;
  11799. }
  11800. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  11801. UnaryOperatorKind Opc, Expr *Input) {
  11802. // First things first: handle placeholders so that the
  11803. // overloaded-operator check considers the right type.
  11804. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  11805. // Increment and decrement of pseudo-object references.
  11806. if (pty->getKind() == BuiltinType::PseudoObject &&
  11807. UnaryOperator::isIncrementDecrementOp(Opc))
  11808. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  11809. // extension is always a builtin operator.
  11810. if (Opc == UO_Extension)
  11811. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11812. // & gets special logic for several kinds of placeholder.
  11813. // The builtin code knows what to do.
  11814. if (Opc == UO_AddrOf &&
  11815. (pty->getKind() == BuiltinType::Overload ||
  11816. pty->getKind() == BuiltinType::UnknownAny ||
  11817. pty->getKind() == BuiltinType::BoundMember))
  11818. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11819. // Anything else needs to be handled now.
  11820. ExprResult Result = CheckPlaceholderExpr(Input);
  11821. if (Result.isInvalid()) return ExprError();
  11822. Input = Result.get();
  11823. }
  11824. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  11825. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  11826. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  11827. // Find all of the overloaded operators visible from this
  11828. // point. We perform both an operator-name lookup from the local
  11829. // scope and an argument-dependent lookup based on the types of
  11830. // the arguments.
  11831. UnresolvedSet<16> Functions;
  11832. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  11833. if (S && OverOp != OO_None)
  11834. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  11835. Functions);
  11836. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  11837. }
  11838. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11839. }
  11840. // Unary Operators. 'Tok' is the token for the operator.
  11841. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  11842. tok::TokenKind Op, Expr *Input) {
  11843. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  11844. }
  11845. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  11846. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  11847. LabelDecl *TheDecl) {
  11848. TheDecl->markUsed(Context);
  11849. // Create the AST node. The address of a label always has type 'void*'.
  11850. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  11851. Context.getPointerType(Context.VoidTy));
  11852. }
  11853. void Sema::ActOnStartStmtExpr() {
  11854. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11855. }
  11856. void Sema::ActOnStmtExprError() {
  11857. // Note that function is also called by TreeTransform when leaving a
  11858. // StmtExpr scope without rebuilding anything.
  11859. DiscardCleanupsInEvaluationContext();
  11860. PopExpressionEvaluationContext();
  11861. }
  11862. ExprResult
  11863. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  11864. SourceLocation RPLoc) { // "({..})"
  11865. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  11866. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  11867. if (hasAnyUnrecoverableErrorsInThisFunction())
  11868. DiscardCleanupsInEvaluationContext();
  11869. assert(!Cleanup.exprNeedsCleanups() &&
  11870. "cleanups within StmtExpr not correctly bound!");
  11871. PopExpressionEvaluationContext();
  11872. // FIXME: there are a variety of strange constraints to enforce here, for
  11873. // example, it is not possible to goto into a stmt expression apparently.
  11874. // More semantic analysis is needed.
  11875. // If there are sub-stmts in the compound stmt, take the type of the last one
  11876. // as the type of the stmtexpr.
  11877. QualType Ty = Context.VoidTy;
  11878. bool StmtExprMayBindToTemp = false;
  11879. if (!Compound->body_empty()) {
  11880. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  11881. if (const auto *LastStmt =
  11882. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  11883. if (const Expr *Value = LastStmt->getExprStmt()) {
  11884. StmtExprMayBindToTemp = true;
  11885. Ty = Value->getType();
  11886. }
  11887. }
  11888. }
  11889. // FIXME: Check that expression type is complete/non-abstract; statement
  11890. // expressions are not lvalues.
  11891. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  11892. if (StmtExprMayBindToTemp)
  11893. return MaybeBindToTemporary(ResStmtExpr);
  11894. return ResStmtExpr;
  11895. }
  11896. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  11897. if (ER.isInvalid())
  11898. return ExprError();
  11899. // Do function/array conversion on the last expression, but not
  11900. // lvalue-to-rvalue. However, initialize an unqualified type.
  11901. ER = DefaultFunctionArrayConversion(ER.get());
  11902. if (ER.isInvalid())
  11903. return ExprError();
  11904. Expr *E = ER.get();
  11905. if (E->isTypeDependent())
  11906. return E;
  11907. // In ARC, if the final expression ends in a consume, splice
  11908. // the consume out and bind it later. In the alternate case
  11909. // (when dealing with a retainable type), the result
  11910. // initialization will create a produce. In both cases the
  11911. // result will be +1, and we'll need to balance that out with
  11912. // a bind.
  11913. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  11914. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  11915. return Cast->getSubExpr();
  11916. // FIXME: Provide a better location for the initialization.
  11917. return PerformCopyInitialization(
  11918. InitializedEntity::InitializeStmtExprResult(
  11919. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  11920. SourceLocation(), E);
  11921. }
  11922. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  11923. TypeSourceInfo *TInfo,
  11924. ArrayRef<OffsetOfComponent> Components,
  11925. SourceLocation RParenLoc) {
  11926. QualType ArgTy = TInfo->getType();
  11927. bool Dependent = ArgTy->isDependentType();
  11928. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  11929. // We must have at least one component that refers to the type, and the first
  11930. // one is known to be a field designator. Verify that the ArgTy represents
  11931. // a struct/union/class.
  11932. if (!Dependent && !ArgTy->isRecordType())
  11933. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  11934. << ArgTy << TypeRange);
  11935. // Type must be complete per C99 7.17p3 because a declaring a variable
  11936. // with an incomplete type would be ill-formed.
  11937. if (!Dependent
  11938. && RequireCompleteType(BuiltinLoc, ArgTy,
  11939. diag::err_offsetof_incomplete_type, TypeRange))
  11940. return ExprError();
  11941. bool DidWarnAboutNonPOD = false;
  11942. QualType CurrentType = ArgTy;
  11943. SmallVector<OffsetOfNode, 4> Comps;
  11944. SmallVector<Expr*, 4> Exprs;
  11945. for (const OffsetOfComponent &OC : Components) {
  11946. if (OC.isBrackets) {
  11947. // Offset of an array sub-field. TODO: Should we allow vector elements?
  11948. if (!CurrentType->isDependentType()) {
  11949. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  11950. if(!AT)
  11951. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  11952. << CurrentType);
  11953. CurrentType = AT->getElementType();
  11954. } else
  11955. CurrentType = Context.DependentTy;
  11956. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  11957. if (IdxRval.isInvalid())
  11958. return ExprError();
  11959. Expr *Idx = IdxRval.get();
  11960. // The expression must be an integral expression.
  11961. // FIXME: An integral constant expression?
  11962. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  11963. !Idx->getType()->isIntegerType())
  11964. return ExprError(
  11965. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  11966. << Idx->getSourceRange());
  11967. // Record this array index.
  11968. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  11969. Exprs.push_back(Idx);
  11970. continue;
  11971. }
  11972. // Offset of a field.
  11973. if (CurrentType->isDependentType()) {
  11974. // We have the offset of a field, but we can't look into the dependent
  11975. // type. Just record the identifier of the field.
  11976. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  11977. CurrentType = Context.DependentTy;
  11978. continue;
  11979. }
  11980. // We need to have a complete type to look into.
  11981. if (RequireCompleteType(OC.LocStart, CurrentType,
  11982. diag::err_offsetof_incomplete_type))
  11983. return ExprError();
  11984. // Look for the designated field.
  11985. const RecordType *RC = CurrentType->getAs<RecordType>();
  11986. if (!RC)
  11987. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  11988. << CurrentType);
  11989. RecordDecl *RD = RC->getDecl();
  11990. // C++ [lib.support.types]p5:
  11991. // The macro offsetof accepts a restricted set of type arguments in this
  11992. // International Standard. type shall be a POD structure or a POD union
  11993. // (clause 9).
  11994. // C++11 [support.types]p4:
  11995. // If type is not a standard-layout class (Clause 9), the results are
  11996. // undefined.
  11997. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11998. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  11999. unsigned DiagID =
  12000. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  12001. : diag::ext_offsetof_non_pod_type;
  12002. if (!IsSafe && !DidWarnAboutNonPOD &&
  12003. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  12004. PDiag(DiagID)
  12005. << SourceRange(Components[0].LocStart, OC.LocEnd)
  12006. << CurrentType))
  12007. DidWarnAboutNonPOD = true;
  12008. }
  12009. // Look for the field.
  12010. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  12011. LookupQualifiedName(R, RD);
  12012. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  12013. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  12014. if (!MemberDecl) {
  12015. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  12016. MemberDecl = IndirectMemberDecl->getAnonField();
  12017. }
  12018. if (!MemberDecl)
  12019. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  12020. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  12021. OC.LocEnd));
  12022. // C99 7.17p3:
  12023. // (If the specified member is a bit-field, the behavior is undefined.)
  12024. //
  12025. // We diagnose this as an error.
  12026. if (MemberDecl->isBitField()) {
  12027. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  12028. << MemberDecl->getDeclName()
  12029. << SourceRange(BuiltinLoc, RParenLoc);
  12030. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  12031. return ExprError();
  12032. }
  12033. RecordDecl *Parent = MemberDecl->getParent();
  12034. if (IndirectMemberDecl)
  12035. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  12036. // If the member was found in a base class, introduce OffsetOfNodes for
  12037. // the base class indirections.
  12038. CXXBasePaths Paths;
  12039. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  12040. Paths)) {
  12041. if (Paths.getDetectedVirtual()) {
  12042. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  12043. << MemberDecl->getDeclName()
  12044. << SourceRange(BuiltinLoc, RParenLoc);
  12045. return ExprError();
  12046. }
  12047. CXXBasePath &Path = Paths.front();
  12048. for (const CXXBasePathElement &B : Path)
  12049. Comps.push_back(OffsetOfNode(B.Base));
  12050. }
  12051. if (IndirectMemberDecl) {
  12052. for (auto *FI : IndirectMemberDecl->chain()) {
  12053. assert(isa<FieldDecl>(FI));
  12054. Comps.push_back(OffsetOfNode(OC.LocStart,
  12055. cast<FieldDecl>(FI), OC.LocEnd));
  12056. }
  12057. } else
  12058. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  12059. CurrentType = MemberDecl->getType().getNonReferenceType();
  12060. }
  12061. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  12062. Comps, Exprs, RParenLoc);
  12063. }
  12064. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  12065. SourceLocation BuiltinLoc,
  12066. SourceLocation TypeLoc,
  12067. ParsedType ParsedArgTy,
  12068. ArrayRef<OffsetOfComponent> Components,
  12069. SourceLocation RParenLoc) {
  12070. TypeSourceInfo *ArgTInfo;
  12071. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12072. if (ArgTy.isNull())
  12073. return ExprError();
  12074. if (!ArgTInfo)
  12075. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12076. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12077. }
  12078. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12079. Expr *CondExpr,
  12080. Expr *LHSExpr, Expr *RHSExpr,
  12081. SourceLocation RPLoc) {
  12082. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12083. ExprValueKind VK = VK_RValue;
  12084. ExprObjectKind OK = OK_Ordinary;
  12085. QualType resType;
  12086. bool ValueDependent = false;
  12087. bool CondIsTrue = false;
  12088. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12089. resType = Context.DependentTy;
  12090. ValueDependent = true;
  12091. } else {
  12092. // The conditional expression is required to be a constant expression.
  12093. llvm::APSInt condEval(32);
  12094. ExprResult CondICE
  12095. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12096. diag::err_typecheck_choose_expr_requires_constant, false);
  12097. if (CondICE.isInvalid())
  12098. return ExprError();
  12099. CondExpr = CondICE.get();
  12100. CondIsTrue = condEval.getZExtValue();
  12101. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12102. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12103. resType = ActiveExpr->getType();
  12104. ValueDependent = ActiveExpr->isValueDependent();
  12105. VK = ActiveExpr->getValueKind();
  12106. OK = ActiveExpr->getObjectKind();
  12107. }
  12108. return new (Context)
  12109. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12110. CondIsTrue, resType->isDependentType(), ValueDependent);
  12111. }
  12112. //===----------------------------------------------------------------------===//
  12113. // Clang Extensions.
  12114. //===----------------------------------------------------------------------===//
  12115. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12116. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12117. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12118. if (LangOpts.CPlusPlus) {
  12119. Decl *ManglingContextDecl;
  12120. if (MangleNumberingContext *MCtx =
  12121. getCurrentMangleNumberContext(Block->getDeclContext(),
  12122. ManglingContextDecl)) {
  12123. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12124. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12125. }
  12126. }
  12127. PushBlockScope(CurScope, Block);
  12128. CurContext->addDecl(Block);
  12129. if (CurScope)
  12130. PushDeclContext(CurScope, Block);
  12131. else
  12132. CurContext = Block;
  12133. getCurBlock()->HasImplicitReturnType = true;
  12134. // Enter a new evaluation context to insulate the block from any
  12135. // cleanups from the enclosing full-expression.
  12136. PushExpressionEvaluationContext(
  12137. ExpressionEvaluationContext::PotentiallyEvaluated);
  12138. }
  12139. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12140. Scope *CurScope) {
  12141. assert(ParamInfo.getIdentifier() == nullptr &&
  12142. "block-id should have no identifier!");
  12143. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12144. BlockScopeInfo *CurBlock = getCurBlock();
  12145. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12146. QualType T = Sig->getType();
  12147. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12148. // in turn, make the block expression contain unexpanded parameter packs.
  12149. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12150. // Drop the parameters.
  12151. FunctionProtoType::ExtProtoInfo EPI;
  12152. EPI.HasTrailingReturn = false;
  12153. EPI.TypeQuals.addConst();
  12154. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12155. Sig = Context.getTrivialTypeSourceInfo(T);
  12156. }
  12157. // GetTypeForDeclarator always produces a function type for a block
  12158. // literal signature. Furthermore, it is always a FunctionProtoType
  12159. // unless the function was written with a typedef.
  12160. assert(T->isFunctionType() &&
  12161. "GetTypeForDeclarator made a non-function block signature");
  12162. // Look for an explicit signature in that function type.
  12163. FunctionProtoTypeLoc ExplicitSignature;
  12164. if ((ExplicitSignature = Sig->getTypeLoc()
  12165. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12166. // Check whether that explicit signature was synthesized by
  12167. // GetTypeForDeclarator. If so, don't save that as part of the
  12168. // written signature.
  12169. if (ExplicitSignature.getLocalRangeBegin() ==
  12170. ExplicitSignature.getLocalRangeEnd()) {
  12171. // This would be much cheaper if we stored TypeLocs instead of
  12172. // TypeSourceInfos.
  12173. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12174. unsigned Size = Result.getFullDataSize();
  12175. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12176. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12177. ExplicitSignature = FunctionProtoTypeLoc();
  12178. }
  12179. }
  12180. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12181. CurBlock->FunctionType = T;
  12182. const FunctionType *Fn = T->getAs<FunctionType>();
  12183. QualType RetTy = Fn->getReturnType();
  12184. bool isVariadic =
  12185. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12186. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12187. // Context.DependentTy is used as a placeholder for a missing block
  12188. // return type. TODO: what should we do with declarators like:
  12189. // ^ * { ... }
  12190. // If the answer is "apply template argument deduction"....
  12191. if (RetTy != Context.DependentTy) {
  12192. CurBlock->ReturnType = RetTy;
  12193. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12194. CurBlock->HasImplicitReturnType = false;
  12195. }
  12196. // Push block parameters from the declarator if we had them.
  12197. SmallVector<ParmVarDecl*, 8> Params;
  12198. if (ExplicitSignature) {
  12199. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12200. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12201. if (Param->getIdentifier() == nullptr &&
  12202. !Param->isImplicit() &&
  12203. !Param->isInvalidDecl() &&
  12204. !getLangOpts().CPlusPlus)
  12205. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12206. Params.push_back(Param);
  12207. }
  12208. // Fake up parameter variables if we have a typedef, like
  12209. // ^ fntype { ... }
  12210. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12211. for (const auto &I : Fn->param_types()) {
  12212. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12213. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12214. Params.push_back(Param);
  12215. }
  12216. }
  12217. // Set the parameters on the block decl.
  12218. if (!Params.empty()) {
  12219. CurBlock->TheDecl->setParams(Params);
  12220. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12221. /*CheckParameterNames=*/false);
  12222. }
  12223. // Finally we can process decl attributes.
  12224. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12225. // Put the parameter variables in scope.
  12226. for (auto AI : CurBlock->TheDecl->parameters()) {
  12227. AI->setOwningFunction(CurBlock->TheDecl);
  12228. // If this has an identifier, add it to the scope stack.
  12229. if (AI->getIdentifier()) {
  12230. CheckShadow(CurBlock->TheScope, AI);
  12231. PushOnScopeChains(AI, CurBlock->TheScope);
  12232. }
  12233. }
  12234. }
  12235. /// ActOnBlockError - If there is an error parsing a block, this callback
  12236. /// is invoked to pop the information about the block from the action impl.
  12237. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12238. // Leave the expression-evaluation context.
  12239. DiscardCleanupsInEvaluationContext();
  12240. PopExpressionEvaluationContext();
  12241. // Pop off CurBlock, handle nested blocks.
  12242. PopDeclContext();
  12243. PopFunctionScopeInfo();
  12244. }
  12245. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12246. /// literal was successfully completed. ^(int x){...}
  12247. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12248. Stmt *Body, Scope *CurScope) {
  12249. // If blocks are disabled, emit an error.
  12250. if (!LangOpts.Blocks)
  12251. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12252. // Leave the expression-evaluation context.
  12253. if (hasAnyUnrecoverableErrorsInThisFunction())
  12254. DiscardCleanupsInEvaluationContext();
  12255. assert(!Cleanup.exprNeedsCleanups() &&
  12256. "cleanups within block not correctly bound!");
  12257. PopExpressionEvaluationContext();
  12258. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12259. BlockDecl *BD = BSI->TheDecl;
  12260. if (BSI->HasImplicitReturnType)
  12261. deduceClosureReturnType(*BSI);
  12262. QualType RetTy = Context.VoidTy;
  12263. if (!BSI->ReturnType.isNull())
  12264. RetTy = BSI->ReturnType;
  12265. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12266. QualType BlockTy;
  12267. // If the user wrote a function type in some form, try to use that.
  12268. if (!BSI->FunctionType.isNull()) {
  12269. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  12270. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12271. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12272. // Turn protoless block types into nullary block types.
  12273. if (isa<FunctionNoProtoType>(FTy)) {
  12274. FunctionProtoType::ExtProtoInfo EPI;
  12275. EPI.ExtInfo = Ext;
  12276. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12277. // Otherwise, if we don't need to change anything about the function type,
  12278. // preserve its sugar structure.
  12279. } else if (FTy->getReturnType() == RetTy &&
  12280. (!NoReturn || FTy->getNoReturnAttr())) {
  12281. BlockTy = BSI->FunctionType;
  12282. // Otherwise, make the minimal modifications to the function type.
  12283. } else {
  12284. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12285. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12286. EPI.TypeQuals = Qualifiers();
  12287. EPI.ExtInfo = Ext;
  12288. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12289. }
  12290. // If we don't have a function type, just build one from nothing.
  12291. } else {
  12292. FunctionProtoType::ExtProtoInfo EPI;
  12293. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12294. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12295. }
  12296. DiagnoseUnusedParameters(BD->parameters());
  12297. BlockTy = Context.getBlockPointerType(BlockTy);
  12298. // If needed, diagnose invalid gotos and switches in the block.
  12299. if (getCurFunction()->NeedsScopeChecking() &&
  12300. !PP.isCodeCompletionEnabled())
  12301. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12302. BD->setBody(cast<CompoundStmt>(Body));
  12303. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12304. DiagnoseUnguardedAvailabilityViolations(BD);
  12305. // Try to apply the named return value optimization. We have to check again
  12306. // if we can do this, though, because blocks keep return statements around
  12307. // to deduce an implicit return type.
  12308. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12309. !BD->isDependentContext())
  12310. computeNRVO(Body, BSI);
  12311. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  12312. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  12313. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  12314. NTCUK_Destruct|NTCUK_Copy);
  12315. PopDeclContext();
  12316. // Pop the block scope now but keep it alive to the end of this function.
  12317. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12318. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12319. // Set the captured variables on the block.
  12320. SmallVector<BlockDecl::Capture, 4> Captures;
  12321. for (Capture &Cap : BSI->Captures) {
  12322. if (Cap.isInvalid() || Cap.isThisCapture())
  12323. continue;
  12324. VarDecl *Var = Cap.getVariable();
  12325. Expr *CopyExpr = nullptr;
  12326. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12327. if (const RecordType *Record =
  12328. Cap.getCaptureType()->getAs<RecordType>()) {
  12329. // The capture logic needs the destructor, so make sure we mark it.
  12330. // Usually this is unnecessary because most local variables have
  12331. // their destructors marked at declaration time, but parameters are
  12332. // an exception because it's technically only the call site that
  12333. // actually requires the destructor.
  12334. if (isa<ParmVarDecl>(Var))
  12335. FinalizeVarWithDestructor(Var, Record);
  12336. // Enter a separate potentially-evaluated context while building block
  12337. // initializers to isolate their cleanups from those of the block
  12338. // itself.
  12339. // FIXME: Is this appropriate even when the block itself occurs in an
  12340. // unevaluated operand?
  12341. EnterExpressionEvaluationContext EvalContext(
  12342. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12343. SourceLocation Loc = Cap.getLocation();
  12344. ExprResult Result = BuildDeclarationNameExpr(
  12345. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12346. // According to the blocks spec, the capture of a variable from
  12347. // the stack requires a const copy constructor. This is not true
  12348. // of the copy/move done to move a __block variable to the heap.
  12349. if (!Result.isInvalid() &&
  12350. !Result.get()->getType().isConstQualified()) {
  12351. Result = ImpCastExprToType(Result.get(),
  12352. Result.get()->getType().withConst(),
  12353. CK_NoOp, VK_LValue);
  12354. }
  12355. if (!Result.isInvalid()) {
  12356. Result = PerformCopyInitialization(
  12357. InitializedEntity::InitializeBlock(Var->getLocation(),
  12358. Cap.getCaptureType(), false),
  12359. Loc, Result.get());
  12360. }
  12361. // Build a full-expression copy expression if initialization
  12362. // succeeded and used a non-trivial constructor. Recover from
  12363. // errors by pretending that the copy isn't necessary.
  12364. if (!Result.isInvalid() &&
  12365. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12366. ->isTrivial()) {
  12367. Result = MaybeCreateExprWithCleanups(Result);
  12368. CopyExpr = Result.get();
  12369. }
  12370. }
  12371. }
  12372. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12373. CopyExpr);
  12374. Captures.push_back(NewCap);
  12375. }
  12376. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12377. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12378. // If the block isn't obviously global, i.e. it captures anything at
  12379. // all, then we need to do a few things in the surrounding context:
  12380. if (Result->getBlockDecl()->hasCaptures()) {
  12381. // First, this expression has a new cleanup object.
  12382. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12383. Cleanup.setExprNeedsCleanups(true);
  12384. // It also gets a branch-protected scope if any of the captured
  12385. // variables needs destruction.
  12386. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12387. const VarDecl *var = CI.getVariable();
  12388. if (var->getType().isDestructedType() != QualType::DK_none) {
  12389. setFunctionHasBranchProtectedScope();
  12390. break;
  12391. }
  12392. }
  12393. }
  12394. if (getCurFunction())
  12395. getCurFunction()->addBlock(BD);
  12396. return Result;
  12397. }
  12398. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12399. SourceLocation RPLoc) {
  12400. TypeSourceInfo *TInfo;
  12401. GetTypeFromParser(Ty, &TInfo);
  12402. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12403. }
  12404. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12405. Expr *E, TypeSourceInfo *TInfo,
  12406. SourceLocation RPLoc) {
  12407. Expr *OrigExpr = E;
  12408. bool IsMS = false;
  12409. // CUDA device code does not support varargs.
  12410. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12411. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12412. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12413. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12414. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12415. }
  12416. }
  12417. // NVPTX does not support va_arg expression.
  12418. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12419. Context.getTargetInfo().getTriple().isNVPTX())
  12420. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12421. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12422. // as Microsoft ABI on an actual Microsoft platform, where
  12423. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12424. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12425. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12426. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12427. if (Context.hasSameType(MSVaListType, E->getType())) {
  12428. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12429. return ExprError();
  12430. IsMS = true;
  12431. }
  12432. }
  12433. // Get the va_list type
  12434. QualType VaListType = Context.getBuiltinVaListType();
  12435. if (!IsMS) {
  12436. if (VaListType->isArrayType()) {
  12437. // Deal with implicit array decay; for example, on x86-64,
  12438. // va_list is an array, but it's supposed to decay to
  12439. // a pointer for va_arg.
  12440. VaListType = Context.getArrayDecayedType(VaListType);
  12441. // Make sure the input expression also decays appropriately.
  12442. ExprResult Result = UsualUnaryConversions(E);
  12443. if (Result.isInvalid())
  12444. return ExprError();
  12445. E = Result.get();
  12446. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12447. // If va_list is a record type and we are compiling in C++ mode,
  12448. // check the argument using reference binding.
  12449. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12450. Context, Context.getLValueReferenceType(VaListType), false);
  12451. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12452. if (Init.isInvalid())
  12453. return ExprError();
  12454. E = Init.getAs<Expr>();
  12455. } else {
  12456. // Otherwise, the va_list argument must be an l-value because
  12457. // it is modified by va_arg.
  12458. if (!E->isTypeDependent() &&
  12459. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12460. return ExprError();
  12461. }
  12462. }
  12463. if (!IsMS && !E->isTypeDependent() &&
  12464. !Context.hasSameType(VaListType, E->getType()))
  12465. return ExprError(
  12466. Diag(E->getBeginLoc(),
  12467. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12468. << OrigExpr->getType() << E->getSourceRange());
  12469. if (!TInfo->getType()->isDependentType()) {
  12470. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12471. diag::err_second_parameter_to_va_arg_incomplete,
  12472. TInfo->getTypeLoc()))
  12473. return ExprError();
  12474. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12475. TInfo->getType(),
  12476. diag::err_second_parameter_to_va_arg_abstract,
  12477. TInfo->getTypeLoc()))
  12478. return ExprError();
  12479. if (!TInfo->getType().isPODType(Context)) {
  12480. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12481. TInfo->getType()->isObjCLifetimeType()
  12482. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12483. : diag::warn_second_parameter_to_va_arg_not_pod)
  12484. << TInfo->getType()
  12485. << TInfo->getTypeLoc().getSourceRange();
  12486. }
  12487. // Check for va_arg where arguments of the given type will be promoted
  12488. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12489. QualType PromoteType;
  12490. if (TInfo->getType()->isPromotableIntegerType()) {
  12491. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12492. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12493. PromoteType = QualType();
  12494. }
  12495. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12496. PromoteType = Context.DoubleTy;
  12497. if (!PromoteType.isNull())
  12498. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12499. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12500. << TInfo->getType()
  12501. << PromoteType
  12502. << TInfo->getTypeLoc().getSourceRange());
  12503. }
  12504. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12505. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12506. }
  12507. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12508. // The type of __null will be int or long, depending on the size of
  12509. // pointers on the target.
  12510. QualType Ty;
  12511. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12512. if (pw == Context.getTargetInfo().getIntWidth())
  12513. Ty = Context.IntTy;
  12514. else if (pw == Context.getTargetInfo().getLongWidth())
  12515. Ty = Context.LongTy;
  12516. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12517. Ty = Context.LongLongTy;
  12518. else {
  12519. llvm_unreachable("I don't know size of pointer!");
  12520. }
  12521. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12522. }
  12523. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12524. SourceLocation BuiltinLoc,
  12525. SourceLocation RPLoc) {
  12526. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12527. }
  12528. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12529. SourceLocation BuiltinLoc,
  12530. SourceLocation RPLoc,
  12531. DeclContext *ParentContext) {
  12532. return new (Context)
  12533. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12534. }
  12535. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12536. bool Diagnose) {
  12537. if (!getLangOpts().ObjC)
  12538. return false;
  12539. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12540. if (!PT)
  12541. return false;
  12542. if (!PT->isObjCIdType()) {
  12543. // Check if the destination is the 'NSString' interface.
  12544. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12545. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12546. return false;
  12547. }
  12548. // Ignore any parens, implicit casts (should only be
  12549. // array-to-pointer decays), and not-so-opaque values. The last is
  12550. // important for making this trigger for property assignments.
  12551. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12552. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12553. if (OV->getSourceExpr())
  12554. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12555. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12556. if (!SL || !SL->isAscii())
  12557. return false;
  12558. if (Diagnose) {
  12559. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12560. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12561. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12562. }
  12563. return true;
  12564. }
  12565. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12566. const Expr *SrcExpr) {
  12567. if (!DstType->isFunctionPointerType() ||
  12568. !SrcExpr->getType()->isFunctionType())
  12569. return false;
  12570. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12571. if (!DRE)
  12572. return false;
  12573. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12574. if (!FD)
  12575. return false;
  12576. return !S.checkAddressOfFunctionIsAvailable(FD,
  12577. /*Complain=*/true,
  12578. SrcExpr->getBeginLoc());
  12579. }
  12580. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12581. SourceLocation Loc,
  12582. QualType DstType, QualType SrcType,
  12583. Expr *SrcExpr, AssignmentAction Action,
  12584. bool *Complained) {
  12585. if (Complained)
  12586. *Complained = false;
  12587. // Decode the result (notice that AST's are still created for extensions).
  12588. bool CheckInferredResultType = false;
  12589. bool isInvalid = false;
  12590. unsigned DiagKind = 0;
  12591. FixItHint Hint;
  12592. ConversionFixItGenerator ConvHints;
  12593. bool MayHaveConvFixit = false;
  12594. bool MayHaveFunctionDiff = false;
  12595. const ObjCInterfaceDecl *IFace = nullptr;
  12596. const ObjCProtocolDecl *PDecl = nullptr;
  12597. switch (ConvTy) {
  12598. case Compatible:
  12599. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12600. return false;
  12601. case PointerToInt:
  12602. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12603. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12604. MayHaveConvFixit = true;
  12605. break;
  12606. case IntToPointer:
  12607. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12608. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12609. MayHaveConvFixit = true;
  12610. break;
  12611. case IncompatiblePointer:
  12612. if (Action == AA_Passing_CFAudited)
  12613. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12614. else if (SrcType->isFunctionPointerType() &&
  12615. DstType->isFunctionPointerType())
  12616. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12617. else
  12618. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12619. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12620. SrcType->isObjCObjectPointerType();
  12621. if (Hint.isNull() && !CheckInferredResultType) {
  12622. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12623. }
  12624. else if (CheckInferredResultType) {
  12625. SrcType = SrcType.getUnqualifiedType();
  12626. DstType = DstType.getUnqualifiedType();
  12627. }
  12628. MayHaveConvFixit = true;
  12629. break;
  12630. case IncompatiblePointerSign:
  12631. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12632. break;
  12633. case FunctionVoidPointer:
  12634. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12635. break;
  12636. case IncompatiblePointerDiscardsQualifiers: {
  12637. // Perform array-to-pointer decay if necessary.
  12638. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12639. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12640. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12641. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12642. DiagKind = diag::err_typecheck_incompatible_address_space;
  12643. break;
  12644. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12645. DiagKind = diag::err_typecheck_incompatible_ownership;
  12646. break;
  12647. }
  12648. llvm_unreachable("unknown error case for discarding qualifiers!");
  12649. // fallthrough
  12650. }
  12651. case CompatiblePointerDiscardsQualifiers:
  12652. // If the qualifiers lost were because we were applying the
  12653. // (deprecated) C++ conversion from a string literal to a char*
  12654. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12655. // Ideally, this check would be performed in
  12656. // checkPointerTypesForAssignment. However, that would require a
  12657. // bit of refactoring (so that the second argument is an
  12658. // expression, rather than a type), which should be done as part
  12659. // of a larger effort to fix checkPointerTypesForAssignment for
  12660. // C++ semantics.
  12661. if (getLangOpts().CPlusPlus &&
  12662. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12663. return false;
  12664. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12665. break;
  12666. case IncompatibleNestedPointerQualifiers:
  12667. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12668. break;
  12669. case IncompatibleNestedPointerAddressSpaceMismatch:
  12670. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12671. break;
  12672. case IntToBlockPointer:
  12673. DiagKind = diag::err_int_to_block_pointer;
  12674. break;
  12675. case IncompatibleBlockPointer:
  12676. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12677. break;
  12678. case IncompatibleObjCQualifiedId: {
  12679. if (SrcType->isObjCQualifiedIdType()) {
  12680. const ObjCObjectPointerType *srcOPT =
  12681. SrcType->getAs<ObjCObjectPointerType>();
  12682. for (auto *srcProto : srcOPT->quals()) {
  12683. PDecl = srcProto;
  12684. break;
  12685. }
  12686. if (const ObjCInterfaceType *IFaceT =
  12687. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12688. IFace = IFaceT->getDecl();
  12689. }
  12690. else if (DstType->isObjCQualifiedIdType()) {
  12691. const ObjCObjectPointerType *dstOPT =
  12692. DstType->getAs<ObjCObjectPointerType>();
  12693. for (auto *dstProto : dstOPT->quals()) {
  12694. PDecl = dstProto;
  12695. break;
  12696. }
  12697. if (const ObjCInterfaceType *IFaceT =
  12698. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12699. IFace = IFaceT->getDecl();
  12700. }
  12701. DiagKind = diag::warn_incompatible_qualified_id;
  12702. break;
  12703. }
  12704. case IncompatibleVectors:
  12705. DiagKind = diag::warn_incompatible_vectors;
  12706. break;
  12707. case IncompatibleObjCWeakRef:
  12708. DiagKind = diag::err_arc_weak_unavailable_assign;
  12709. break;
  12710. case Incompatible:
  12711. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12712. if (Complained)
  12713. *Complained = true;
  12714. return true;
  12715. }
  12716. DiagKind = diag::err_typecheck_convert_incompatible;
  12717. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12718. MayHaveConvFixit = true;
  12719. isInvalid = true;
  12720. MayHaveFunctionDiff = true;
  12721. break;
  12722. }
  12723. QualType FirstType, SecondType;
  12724. switch (Action) {
  12725. case AA_Assigning:
  12726. case AA_Initializing:
  12727. // The destination type comes first.
  12728. FirstType = DstType;
  12729. SecondType = SrcType;
  12730. break;
  12731. case AA_Returning:
  12732. case AA_Passing:
  12733. case AA_Passing_CFAudited:
  12734. case AA_Converting:
  12735. case AA_Sending:
  12736. case AA_Casting:
  12737. // The source type comes first.
  12738. FirstType = SrcType;
  12739. SecondType = DstType;
  12740. break;
  12741. }
  12742. PartialDiagnostic FDiag = PDiag(DiagKind);
  12743. if (Action == AA_Passing_CFAudited)
  12744. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12745. else
  12746. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12747. // If we can fix the conversion, suggest the FixIts.
  12748. assert(ConvHints.isNull() || Hint.isNull());
  12749. if (!ConvHints.isNull()) {
  12750. for (FixItHint &H : ConvHints.Hints)
  12751. FDiag << H;
  12752. } else {
  12753. FDiag << Hint;
  12754. }
  12755. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  12756. if (MayHaveFunctionDiff)
  12757. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  12758. Diag(Loc, FDiag);
  12759. if (DiagKind == diag::warn_incompatible_qualified_id &&
  12760. PDecl && IFace && !IFace->hasDefinition())
  12761. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  12762. << IFace << PDecl;
  12763. if (SecondType == Context.OverloadTy)
  12764. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  12765. FirstType, /*TakingAddress=*/true);
  12766. if (CheckInferredResultType)
  12767. EmitRelatedResultTypeNote(SrcExpr);
  12768. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  12769. EmitRelatedResultTypeNoteForReturn(DstType);
  12770. if (Complained)
  12771. *Complained = true;
  12772. return isInvalid;
  12773. }
  12774. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12775. llvm::APSInt *Result) {
  12776. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  12777. public:
  12778. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12779. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  12780. }
  12781. } Diagnoser;
  12782. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  12783. }
  12784. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12785. llvm::APSInt *Result,
  12786. unsigned DiagID,
  12787. bool AllowFold) {
  12788. class IDDiagnoser : public VerifyICEDiagnoser {
  12789. unsigned DiagID;
  12790. public:
  12791. IDDiagnoser(unsigned DiagID)
  12792. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  12793. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12794. S.Diag(Loc, DiagID) << SR;
  12795. }
  12796. } Diagnoser(DiagID);
  12797. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  12798. }
  12799. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  12800. SourceRange SR) {
  12801. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  12802. }
  12803. ExprResult
  12804. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  12805. VerifyICEDiagnoser &Diagnoser,
  12806. bool AllowFold) {
  12807. SourceLocation DiagLoc = E->getBeginLoc();
  12808. if (getLangOpts().CPlusPlus11) {
  12809. // C++11 [expr.const]p5:
  12810. // If an expression of literal class type is used in a context where an
  12811. // integral constant expression is required, then that class type shall
  12812. // have a single non-explicit conversion function to an integral or
  12813. // unscoped enumeration type
  12814. ExprResult Converted;
  12815. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  12816. public:
  12817. CXX11ConvertDiagnoser(bool Silent)
  12818. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  12819. Silent, true) {}
  12820. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  12821. QualType T) override {
  12822. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  12823. }
  12824. SemaDiagnosticBuilder diagnoseIncomplete(
  12825. Sema &S, SourceLocation Loc, QualType T) override {
  12826. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  12827. }
  12828. SemaDiagnosticBuilder diagnoseExplicitConv(
  12829. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12830. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  12831. }
  12832. SemaDiagnosticBuilder noteExplicitConv(
  12833. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12834. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12835. << ConvTy->isEnumeralType() << ConvTy;
  12836. }
  12837. SemaDiagnosticBuilder diagnoseAmbiguous(
  12838. Sema &S, SourceLocation Loc, QualType T) override {
  12839. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  12840. }
  12841. SemaDiagnosticBuilder noteAmbiguous(
  12842. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12843. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12844. << ConvTy->isEnumeralType() << ConvTy;
  12845. }
  12846. SemaDiagnosticBuilder diagnoseConversion(
  12847. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12848. llvm_unreachable("conversion functions are permitted");
  12849. }
  12850. } ConvertDiagnoser(Diagnoser.Suppress);
  12851. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  12852. ConvertDiagnoser);
  12853. if (Converted.isInvalid())
  12854. return Converted;
  12855. E = Converted.get();
  12856. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  12857. return ExprError();
  12858. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12859. // An ICE must be of integral or unscoped enumeration type.
  12860. if (!Diagnoser.Suppress)
  12861. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12862. return ExprError();
  12863. }
  12864. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  12865. // in the non-ICE case.
  12866. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  12867. if (Result)
  12868. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  12869. if (!isa<ConstantExpr>(E))
  12870. E = ConstantExpr::Create(Context, E);
  12871. return E;
  12872. }
  12873. Expr::EvalResult EvalResult;
  12874. SmallVector<PartialDiagnosticAt, 8> Notes;
  12875. EvalResult.Diag = &Notes;
  12876. // Try to evaluate the expression, and produce diagnostics explaining why it's
  12877. // not a constant expression as a side-effect.
  12878. bool Folded =
  12879. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  12880. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  12881. if (!isa<ConstantExpr>(E))
  12882. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  12883. // In C++11, we can rely on diagnostics being produced for any expression
  12884. // which is not a constant expression. If no diagnostics were produced, then
  12885. // this is a constant expression.
  12886. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  12887. if (Result)
  12888. *Result = EvalResult.Val.getInt();
  12889. return E;
  12890. }
  12891. // If our only note is the usual "invalid subexpression" note, just point
  12892. // the caret at its location rather than producing an essentially
  12893. // redundant note.
  12894. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12895. diag::note_invalid_subexpr_in_const_expr) {
  12896. DiagLoc = Notes[0].first;
  12897. Notes.clear();
  12898. }
  12899. if (!Folded || !AllowFold) {
  12900. if (!Diagnoser.Suppress) {
  12901. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12902. for (const PartialDiagnosticAt &Note : Notes)
  12903. Diag(Note.first, Note.second);
  12904. }
  12905. return ExprError();
  12906. }
  12907. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  12908. for (const PartialDiagnosticAt &Note : Notes)
  12909. Diag(Note.first, Note.second);
  12910. if (Result)
  12911. *Result = EvalResult.Val.getInt();
  12912. return E;
  12913. }
  12914. namespace {
  12915. // Handle the case where we conclude a expression which we speculatively
  12916. // considered to be unevaluated is actually evaluated.
  12917. class TransformToPE : public TreeTransform<TransformToPE> {
  12918. typedef TreeTransform<TransformToPE> BaseTransform;
  12919. public:
  12920. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  12921. // Make sure we redo semantic analysis
  12922. bool AlwaysRebuild() { return true; }
  12923. bool ReplacingOriginal() { return true; }
  12924. // We need to special-case DeclRefExprs referring to FieldDecls which
  12925. // are not part of a member pointer formation; normal TreeTransforming
  12926. // doesn't catch this case because of the way we represent them in the AST.
  12927. // FIXME: This is a bit ugly; is it really the best way to handle this
  12928. // case?
  12929. //
  12930. // Error on DeclRefExprs referring to FieldDecls.
  12931. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  12932. if (isa<FieldDecl>(E->getDecl()) &&
  12933. !SemaRef.isUnevaluatedContext())
  12934. return SemaRef.Diag(E->getLocation(),
  12935. diag::err_invalid_non_static_member_use)
  12936. << E->getDecl() << E->getSourceRange();
  12937. return BaseTransform::TransformDeclRefExpr(E);
  12938. }
  12939. // Exception: filter out member pointer formation
  12940. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  12941. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  12942. return E;
  12943. return BaseTransform::TransformUnaryOperator(E);
  12944. }
  12945. // The body of a lambda-expression is in a separate expression evaluation
  12946. // context so never needs to be transformed.
  12947. // FIXME: Ideally we wouldn't transform the closure type either, and would
  12948. // just recreate the capture expressions and lambda expression.
  12949. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  12950. return SkipLambdaBody(E, Body);
  12951. }
  12952. };
  12953. }
  12954. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  12955. assert(isUnevaluatedContext() &&
  12956. "Should only transform unevaluated expressions");
  12957. ExprEvalContexts.back().Context =
  12958. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  12959. if (isUnevaluatedContext())
  12960. return E;
  12961. return TransformToPE(*this).TransformExpr(E);
  12962. }
  12963. void
  12964. Sema::PushExpressionEvaluationContext(
  12965. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  12966. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12967. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  12968. LambdaContextDecl, ExprContext);
  12969. Cleanup.reset();
  12970. if (!MaybeODRUseExprs.empty())
  12971. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  12972. }
  12973. void
  12974. Sema::PushExpressionEvaluationContext(
  12975. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  12976. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12977. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  12978. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  12979. }
  12980. namespace {
  12981. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  12982. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  12983. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  12984. if (E->getOpcode() == UO_Deref)
  12985. return CheckPossibleDeref(S, E->getSubExpr());
  12986. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  12987. return CheckPossibleDeref(S, E->getBase());
  12988. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  12989. return CheckPossibleDeref(S, E->getBase());
  12990. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  12991. QualType Inner;
  12992. QualType Ty = E->getType();
  12993. if (const auto *Ptr = Ty->getAs<PointerType>())
  12994. Inner = Ptr->getPointeeType();
  12995. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  12996. Inner = Arr->getElementType();
  12997. else
  12998. return nullptr;
  12999. if (Inner->hasAttr(attr::NoDeref))
  13000. return E;
  13001. }
  13002. return nullptr;
  13003. }
  13004. } // namespace
  13005. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  13006. for (const Expr *E : Rec.PossibleDerefs) {
  13007. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  13008. if (DeclRef) {
  13009. const ValueDecl *Decl = DeclRef->getDecl();
  13010. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  13011. << Decl->getName() << E->getSourceRange();
  13012. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  13013. } else {
  13014. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  13015. << E->getSourceRange();
  13016. }
  13017. }
  13018. Rec.PossibleDerefs.clear();
  13019. }
  13020. void Sema::PopExpressionEvaluationContext() {
  13021. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  13022. unsigned NumTypos = Rec.NumTypos;
  13023. if (!Rec.Lambdas.empty()) {
  13024. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  13025. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  13026. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  13027. unsigned D;
  13028. if (Rec.isUnevaluated()) {
  13029. // C++11 [expr.prim.lambda]p2:
  13030. // A lambda-expression shall not appear in an unevaluated operand
  13031. // (Clause 5).
  13032. D = diag::err_lambda_unevaluated_operand;
  13033. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  13034. // C++1y [expr.const]p2:
  13035. // A conditional-expression e is a core constant expression unless the
  13036. // evaluation of e, following the rules of the abstract machine, would
  13037. // evaluate [...] a lambda-expression.
  13038. D = diag::err_lambda_in_constant_expression;
  13039. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  13040. // C++17 [expr.prim.lamda]p2:
  13041. // A lambda-expression shall not appear [...] in a template-argument.
  13042. D = diag::err_lambda_in_invalid_context;
  13043. } else
  13044. llvm_unreachable("Couldn't infer lambda error message.");
  13045. for (const auto *L : Rec.Lambdas)
  13046. Diag(L->getBeginLoc(), D);
  13047. }
  13048. }
  13049. WarnOnPendingNoDerefs(Rec);
  13050. // When are coming out of an unevaluated context, clear out any
  13051. // temporaries that we may have created as part of the evaluation of
  13052. // the expression in that context: they aren't relevant because they
  13053. // will never be constructed.
  13054. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  13055. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  13056. ExprCleanupObjects.end());
  13057. Cleanup = Rec.ParentCleanup;
  13058. CleanupVarDeclMarking();
  13059. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  13060. // Otherwise, merge the contexts together.
  13061. } else {
  13062. Cleanup.mergeFrom(Rec.ParentCleanup);
  13063. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  13064. Rec.SavedMaybeODRUseExprs.end());
  13065. }
  13066. // Pop the current expression evaluation context off the stack.
  13067. ExprEvalContexts.pop_back();
  13068. // The global expression evaluation context record is never popped.
  13069. ExprEvalContexts.back().NumTypos += NumTypos;
  13070. }
  13071. void Sema::DiscardCleanupsInEvaluationContext() {
  13072. ExprCleanupObjects.erase(
  13073. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  13074. ExprCleanupObjects.end());
  13075. Cleanup.reset();
  13076. MaybeODRUseExprs.clear();
  13077. }
  13078. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13079. ExprResult Result = CheckPlaceholderExpr(E);
  13080. if (Result.isInvalid())
  13081. return ExprError();
  13082. E = Result.get();
  13083. if (!E->getType()->isVariablyModifiedType())
  13084. return E;
  13085. return TransformToPotentiallyEvaluated(E);
  13086. }
  13087. /// Are we in a context that is potentially constant evaluated per C++20
  13088. /// [expr.const]p12?
  13089. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13090. /// C++2a [expr.const]p12:
  13091. // An expression or conversion is potentially constant evaluated if it is
  13092. switch (SemaRef.ExprEvalContexts.back().Context) {
  13093. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13094. // -- a manifestly constant-evaluated expression,
  13095. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13096. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13097. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13098. // -- a potentially-evaluated expression,
  13099. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13100. // -- an immediate subexpression of a braced-init-list,
  13101. // -- [FIXME] an expression of the form & cast-expression that occurs
  13102. // within a templated entity
  13103. // -- a subexpression of one of the above that is not a subexpression of
  13104. // a nested unevaluated operand.
  13105. return true;
  13106. case Sema::ExpressionEvaluationContext::Unevaluated:
  13107. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13108. // Expressions in this context are never evaluated.
  13109. return false;
  13110. }
  13111. llvm_unreachable("Invalid context");
  13112. }
  13113. /// Return true if this function has a calling convention that requires mangling
  13114. /// in the size of the parameter pack.
  13115. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  13116. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  13117. // we don't need parameter type sizes.
  13118. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  13119. if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
  13120. TT.getArch() != llvm::Triple::x86_64))
  13121. return false;
  13122. // If this is C++ and this isn't an extern "C" function, parameters do not
  13123. // need to be complete. In this case, C++ mangling will apply, which doesn't
  13124. // use the size of the parameters.
  13125. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  13126. return false;
  13127. // Stdcall, fastcall, and vectorcall need this special treatment.
  13128. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13129. switch (CC) {
  13130. case CC_X86StdCall:
  13131. case CC_X86FastCall:
  13132. case CC_X86VectorCall:
  13133. return true;
  13134. default:
  13135. break;
  13136. }
  13137. return false;
  13138. }
  13139. /// Require that all of the parameter types of function be complete. Normally,
  13140. /// parameter types are only required to be complete when a function is called
  13141. /// or defined, but to mangle functions with certain calling conventions, the
  13142. /// mangler needs to know the size of the parameter list. In this situation,
  13143. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  13144. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  13145. /// result in a linker error. Clang doesn't implement this behavior, and instead
  13146. /// attempts to error at compile time.
  13147. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  13148. SourceLocation Loc) {
  13149. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  13150. FunctionDecl *FD;
  13151. ParmVarDecl *Param;
  13152. public:
  13153. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  13154. : FD(FD), Param(Param) {}
  13155. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13156. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13157. StringRef CCName;
  13158. switch (CC) {
  13159. case CC_X86StdCall:
  13160. CCName = "stdcall";
  13161. break;
  13162. case CC_X86FastCall:
  13163. CCName = "fastcall";
  13164. break;
  13165. case CC_X86VectorCall:
  13166. CCName = "vectorcall";
  13167. break;
  13168. default:
  13169. llvm_unreachable("CC does not need mangling");
  13170. }
  13171. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  13172. << Param->getDeclName() << FD->getDeclName() << CCName;
  13173. }
  13174. };
  13175. for (ParmVarDecl *Param : FD->parameters()) {
  13176. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  13177. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  13178. }
  13179. }
  13180. namespace {
  13181. enum class OdrUseContext {
  13182. /// Declarations in this context are not odr-used.
  13183. None,
  13184. /// Declarations in this context are formally odr-used, but this is a
  13185. /// dependent context.
  13186. Dependent,
  13187. /// Declarations in this context are odr-used but not actually used (yet).
  13188. FormallyOdrUsed,
  13189. /// Declarations in this context are used.
  13190. Used
  13191. };
  13192. }
  13193. /// Are we within a context in which references to resolved functions or to
  13194. /// variables result in odr-use?
  13195. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13196. OdrUseContext Result;
  13197. switch (SemaRef.ExprEvalContexts.back().Context) {
  13198. case Sema::ExpressionEvaluationContext::Unevaluated:
  13199. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13200. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13201. return OdrUseContext::None;
  13202. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13203. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13204. Result = OdrUseContext::Used;
  13205. break;
  13206. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13207. Result = OdrUseContext::FormallyOdrUsed;
  13208. break;
  13209. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13210. // A default argument formally results in odr-use, but doesn't actually
  13211. // result in a use in any real sense until it itself is used.
  13212. Result = OdrUseContext::FormallyOdrUsed;
  13213. break;
  13214. }
  13215. if (SemaRef.CurContext->isDependentContext())
  13216. return OdrUseContext::Dependent;
  13217. return Result;
  13218. }
  13219. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13220. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13221. return Func->isConstexpr() &&
  13222. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13223. }
  13224. /// Mark a function referenced, and check whether it is odr-used
  13225. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13226. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13227. bool MightBeOdrUse) {
  13228. assert(Func && "No function?");
  13229. Func->setReferenced();
  13230. // Recursive functions aren't really used until they're used from some other
  13231. // context.
  13232. bool IsRecursiveCall = CurContext == Func;
  13233. // C++11 [basic.def.odr]p3:
  13234. // A function whose name appears as a potentially-evaluated expression is
  13235. // odr-used if it is the unique lookup result or the selected member of a
  13236. // set of overloaded functions [...].
  13237. //
  13238. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13239. // can just check that here.
  13240. OdrUseContext OdrUse =
  13241. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13242. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13243. OdrUse = OdrUseContext::FormallyOdrUsed;
  13244. // C++20 [expr.const]p12:
  13245. // A function [...] is needed for constant evaluation if it is [...] a
  13246. // constexpr function that is named by an expression that is potentially
  13247. // constant evaluated
  13248. bool NeededForConstantEvaluation =
  13249. isPotentiallyConstantEvaluatedContext(*this) &&
  13250. isImplicitlyDefinableConstexprFunction(Func);
  13251. // Determine whether we require a function definition to exist, per
  13252. // C++11 [temp.inst]p3:
  13253. // Unless a function template specialization has been explicitly
  13254. // instantiated or explicitly specialized, the function template
  13255. // specialization is implicitly instantiated when the specialization is
  13256. // referenced in a context that requires a function definition to exist.
  13257. // C++20 [temp.inst]p7:
  13258. // The existence of a definition of a [...] function is considered to
  13259. // affect the semantics of the program if the [...] function is needed for
  13260. // constant evaluation by an expression
  13261. // C++20 [basic.def.odr]p10:
  13262. // Every program shall contain exactly one definition of every non-inline
  13263. // function or variable that is odr-used in that program outside of a
  13264. // discarded statement
  13265. // C++20 [special]p1:
  13266. // The implementation will implicitly define [defaulted special members]
  13267. // if they are odr-used or needed for constant evaluation.
  13268. //
  13269. // Note that we skip the implicit instantiation of templates that are only
  13270. // used in unused default arguments or by recursive calls to themselves.
  13271. // This is formally non-conforming, but seems reasonable in practice.
  13272. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13273. NeededForConstantEvaluation);
  13274. // C++14 [temp.expl.spec]p6:
  13275. // If a template [...] is explicitly specialized then that specialization
  13276. // shall be declared before the first use of that specialization that would
  13277. // cause an implicit instantiation to take place, in every translation unit
  13278. // in which such a use occurs
  13279. if (NeedDefinition &&
  13280. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13281. Func->getMemberSpecializationInfo()))
  13282. checkSpecializationVisibility(Loc, Func);
  13283. // C++14 [except.spec]p17:
  13284. // An exception-specification is considered to be needed when:
  13285. // - the function is odr-used or, if it appears in an unevaluated operand,
  13286. // would be odr-used if the expression were potentially-evaluated;
  13287. //
  13288. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13289. // function is a pure virtual function we're calling, and in that case the
  13290. // function was selected by overload resolution and we need to resolve its
  13291. // exception specification for a different reason.
  13292. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13293. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13294. ResolveExceptionSpec(Loc, FPT);
  13295. if (getLangOpts().CUDA)
  13296. CheckCUDACall(Loc, Func);
  13297. // If we need a definition, try to create one.
  13298. if (NeedDefinition && !Func->getBody()) {
  13299. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  13300. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13301. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13302. if (Constructor->isDefaultConstructor()) {
  13303. if (Constructor->isTrivial() &&
  13304. !Constructor->hasAttr<DLLExportAttr>())
  13305. return;
  13306. DefineImplicitDefaultConstructor(Loc, Constructor);
  13307. } else if (Constructor->isCopyConstructor()) {
  13308. DefineImplicitCopyConstructor(Loc, Constructor);
  13309. } else if (Constructor->isMoveConstructor()) {
  13310. DefineImplicitMoveConstructor(Loc, Constructor);
  13311. }
  13312. } else if (Constructor->getInheritedConstructor()) {
  13313. DefineInheritingConstructor(Loc, Constructor);
  13314. }
  13315. } else if (CXXDestructorDecl *Destructor =
  13316. dyn_cast<CXXDestructorDecl>(Func)) {
  13317. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13318. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13319. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13320. return;
  13321. DefineImplicitDestructor(Loc, Destructor);
  13322. }
  13323. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13324. MarkVTableUsed(Loc, Destructor->getParent());
  13325. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13326. if (MethodDecl->isOverloadedOperator() &&
  13327. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13328. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13329. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13330. if (MethodDecl->isCopyAssignmentOperator())
  13331. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13332. else if (MethodDecl->isMoveAssignmentOperator())
  13333. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13334. }
  13335. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13336. MethodDecl->getParent()->isLambda()) {
  13337. CXXConversionDecl *Conversion =
  13338. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13339. if (Conversion->isLambdaToBlockPointerConversion())
  13340. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13341. else
  13342. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13343. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13344. MarkVTableUsed(Loc, MethodDecl->getParent());
  13345. }
  13346. // Implicit instantiation of function templates and member functions of
  13347. // class templates.
  13348. if (Func->isImplicitlyInstantiable()) {
  13349. TemplateSpecializationKind TSK =
  13350. Func->getTemplateSpecializationKindForInstantiation();
  13351. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13352. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13353. if (FirstInstantiation) {
  13354. PointOfInstantiation = Loc;
  13355. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13356. } else if (TSK != TSK_ImplicitInstantiation) {
  13357. // Use the point of use as the point of instantiation, instead of the
  13358. // point of explicit instantiation (which we track as the actual point
  13359. // of instantiation). This gives better backtraces in diagnostics.
  13360. PointOfInstantiation = Loc;
  13361. }
  13362. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13363. Func->isConstexpr()) {
  13364. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13365. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13366. CodeSynthesisContexts.size())
  13367. PendingLocalImplicitInstantiations.push_back(
  13368. std::make_pair(Func, PointOfInstantiation));
  13369. else if (Func->isConstexpr())
  13370. // Do not defer instantiations of constexpr functions, to avoid the
  13371. // expression evaluator needing to call back into Sema if it sees a
  13372. // call to such a function.
  13373. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13374. else {
  13375. Func->setInstantiationIsPending(true);
  13376. PendingInstantiations.push_back(
  13377. std::make_pair(Func, PointOfInstantiation));
  13378. // Notify the consumer that a function was implicitly instantiated.
  13379. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13380. }
  13381. }
  13382. } else {
  13383. // Walk redefinitions, as some of them may be instantiable.
  13384. for (auto i : Func->redecls()) {
  13385. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13386. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13387. }
  13388. }
  13389. }
  13390. // If this is the first "real" use, act on that.
  13391. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13392. // Keep track of used but undefined functions.
  13393. if (!Func->isDefined()) {
  13394. if (mightHaveNonExternalLinkage(Func))
  13395. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13396. else if (Func->getMostRecentDecl()->isInlined() &&
  13397. !LangOpts.GNUInline &&
  13398. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13399. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13400. else if (isExternalWithNoLinkageType(Func))
  13401. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13402. }
  13403. // Some x86 Windows calling conventions mangle the size of the parameter
  13404. // pack into the name. Computing the size of the parameters requires the
  13405. // parameter types to be complete. Check that now.
  13406. if (funcHasParameterSizeMangling(*this, Func))
  13407. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  13408. Func->markUsed(Context);
  13409. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
  13410. checkOpenMPDeviceFunction(Loc, Func);
  13411. }
  13412. }
  13413. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13414. /// MarkVariableReferenced since it does additional checks and then
  13415. /// calls MarkVarDeclODRUsed.
  13416. /// If the variable must be captured:
  13417. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13418. /// - else capture it in the DeclContext that maps to the
  13419. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13420. static void
  13421. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13422. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13423. // Keep track of used but undefined variables.
  13424. // FIXME: We shouldn't suppress this warning for static data members.
  13425. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13426. (!Var->isExternallyVisible() || Var->isInline() ||
  13427. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13428. !(Var->isStaticDataMember() && Var->hasInit())) {
  13429. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13430. if (old.isInvalid())
  13431. old = Loc;
  13432. }
  13433. QualType CaptureType, DeclRefType;
  13434. if (SemaRef.LangOpts.OpenMP)
  13435. SemaRef.tryCaptureOpenMPLambdas(Var);
  13436. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13437. /*EllipsisLoc*/ SourceLocation(),
  13438. /*BuildAndDiagnose*/ true,
  13439. CaptureType, DeclRefType,
  13440. FunctionScopeIndexToStopAt);
  13441. Var->markUsed(SemaRef.Context);
  13442. }
  13443. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13444. SourceLocation Loc,
  13445. unsigned CapturingScopeIndex) {
  13446. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13447. }
  13448. static void
  13449. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13450. ValueDecl *var, DeclContext *DC) {
  13451. DeclContext *VarDC = var->getDeclContext();
  13452. // If the parameter still belongs to the translation unit, then
  13453. // we're actually just using one parameter in the declaration of
  13454. // the next.
  13455. if (isa<ParmVarDecl>(var) &&
  13456. isa<TranslationUnitDecl>(VarDC))
  13457. return;
  13458. // For C code, don't diagnose about capture if we're not actually in code
  13459. // right now; it's impossible to write a non-constant expression outside of
  13460. // function context, so we'll get other (more useful) diagnostics later.
  13461. //
  13462. // For C++, things get a bit more nasty... it would be nice to suppress this
  13463. // diagnostic for certain cases like using a local variable in an array bound
  13464. // for a member of a local class, but the correct predicate is not obvious.
  13465. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13466. return;
  13467. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13468. unsigned ContextKind = 3; // unknown
  13469. if (isa<CXXMethodDecl>(VarDC) &&
  13470. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13471. ContextKind = 2;
  13472. } else if (isa<FunctionDecl>(VarDC)) {
  13473. ContextKind = 0;
  13474. } else if (isa<BlockDecl>(VarDC)) {
  13475. ContextKind = 1;
  13476. }
  13477. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13478. << var << ValueKind << ContextKind << VarDC;
  13479. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13480. << var;
  13481. // FIXME: Add additional diagnostic info about class etc. which prevents
  13482. // capture.
  13483. }
  13484. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13485. bool &SubCapturesAreNested,
  13486. QualType &CaptureType,
  13487. QualType &DeclRefType) {
  13488. // Check whether we've already captured it.
  13489. if (CSI->CaptureMap.count(Var)) {
  13490. // If we found a capture, any subcaptures are nested.
  13491. SubCapturesAreNested = true;
  13492. // Retrieve the capture type for this variable.
  13493. CaptureType = CSI->getCapture(Var).getCaptureType();
  13494. // Compute the type of an expression that refers to this variable.
  13495. DeclRefType = CaptureType.getNonReferenceType();
  13496. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13497. // are mutable in the sense that user can change their value - they are
  13498. // private instances of the captured declarations.
  13499. const Capture &Cap = CSI->getCapture(Var);
  13500. if (Cap.isCopyCapture() &&
  13501. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13502. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13503. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13504. DeclRefType.addConst();
  13505. return true;
  13506. }
  13507. return false;
  13508. }
  13509. // Only block literals, captured statements, and lambda expressions can
  13510. // capture; other scopes don't work.
  13511. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13512. SourceLocation Loc,
  13513. const bool Diagnose, Sema &S) {
  13514. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13515. return getLambdaAwareParentOfDeclContext(DC);
  13516. else if (Var->hasLocalStorage()) {
  13517. if (Diagnose)
  13518. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13519. }
  13520. return nullptr;
  13521. }
  13522. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13523. // certain types of variables (unnamed, variably modified types etc.)
  13524. // so check for eligibility.
  13525. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13526. SourceLocation Loc,
  13527. const bool Diagnose, Sema &S) {
  13528. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13529. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13530. // Lambdas are not allowed to capture unnamed variables
  13531. // (e.g. anonymous unions).
  13532. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13533. // assuming that's the intent.
  13534. if (IsLambda && !Var->getDeclName()) {
  13535. if (Diagnose) {
  13536. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13537. S.Diag(Var->getLocation(), diag::note_declared_at);
  13538. }
  13539. return false;
  13540. }
  13541. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13542. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13543. if (Diagnose) {
  13544. S.Diag(Loc, diag::err_ref_vm_type);
  13545. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13546. << Var->getDeclName();
  13547. }
  13548. return false;
  13549. }
  13550. // Prohibit structs with flexible array members too.
  13551. // We cannot capture what is in the tail end of the struct.
  13552. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13553. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13554. if (Diagnose) {
  13555. if (IsBlock)
  13556. S.Diag(Loc, diag::err_ref_flexarray_type);
  13557. else
  13558. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13559. << Var->getDeclName();
  13560. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13561. << Var->getDeclName();
  13562. }
  13563. return false;
  13564. }
  13565. }
  13566. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13567. // Lambdas and captured statements are not allowed to capture __block
  13568. // variables; they don't support the expected semantics.
  13569. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13570. if (Diagnose) {
  13571. S.Diag(Loc, diag::err_capture_block_variable)
  13572. << Var->getDeclName() << !IsLambda;
  13573. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13574. << Var->getDeclName();
  13575. }
  13576. return false;
  13577. }
  13578. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13579. if (S.getLangOpts().OpenCL && IsBlock &&
  13580. Var->getType()->isBlockPointerType()) {
  13581. if (Diagnose)
  13582. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13583. return false;
  13584. }
  13585. return true;
  13586. }
  13587. // Returns true if the capture by block was successful.
  13588. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13589. SourceLocation Loc,
  13590. const bool BuildAndDiagnose,
  13591. QualType &CaptureType,
  13592. QualType &DeclRefType,
  13593. const bool Nested,
  13594. Sema &S, bool Invalid) {
  13595. bool ByRef = false;
  13596. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13597. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13598. // (decayed to pointers).
  13599. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13600. if (BuildAndDiagnose) {
  13601. S.Diag(Loc, diag::err_ref_array_type);
  13602. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13603. << Var->getDeclName();
  13604. Invalid = true;
  13605. } else {
  13606. return false;
  13607. }
  13608. }
  13609. // Forbid the block-capture of autoreleasing variables.
  13610. if (!Invalid &&
  13611. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13612. if (BuildAndDiagnose) {
  13613. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13614. << /*block*/ 0;
  13615. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13616. << Var->getDeclName();
  13617. Invalid = true;
  13618. } else {
  13619. return false;
  13620. }
  13621. }
  13622. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13623. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13624. // This function finds out whether there is an AttributedType of kind
  13625. // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
  13626. // attr::ObjCOwnership implies __autoreleasing was explicitly specified
  13627. // rather than being added implicitly by the compiler.
  13628. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  13629. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  13630. if (AttrTy->getAttrKind() == attr::ObjCOwnership)
  13631. return true;
  13632. // Peel off AttributedTypes that are not of kind ObjCOwnership.
  13633. Ty = AttrTy->getModifiedType();
  13634. }
  13635. return false;
  13636. };
  13637. QualType PointeeTy = PT->getPointeeType();
  13638. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13639. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13640. !IsObjCOwnershipAttributedType(PointeeTy)) {
  13641. if (BuildAndDiagnose) {
  13642. SourceLocation VarLoc = Var->getLocation();
  13643. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13644. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13645. }
  13646. }
  13647. }
  13648. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13649. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13650. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13651. // Block capture by reference does not change the capture or
  13652. // declaration reference types.
  13653. ByRef = true;
  13654. } else {
  13655. // Block capture by copy introduces 'const'.
  13656. CaptureType = CaptureType.getNonReferenceType().withConst();
  13657. DeclRefType = CaptureType;
  13658. }
  13659. // Actually capture the variable.
  13660. if (BuildAndDiagnose)
  13661. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  13662. CaptureType, Invalid);
  13663. return !Invalid;
  13664. }
  13665. /// Capture the given variable in the captured region.
  13666. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  13667. VarDecl *Var,
  13668. SourceLocation Loc,
  13669. const bool BuildAndDiagnose,
  13670. QualType &CaptureType,
  13671. QualType &DeclRefType,
  13672. const bool RefersToCapturedVariable,
  13673. Sema &S, bool Invalid) {
  13674. // By default, capture variables by reference.
  13675. bool ByRef = true;
  13676. // Using an LValue reference type is consistent with Lambdas (see below).
  13677. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  13678. if (S.isOpenMPCapturedDecl(Var)) {
  13679. bool HasConst = DeclRefType.isConstQualified();
  13680. DeclRefType = DeclRefType.getUnqualifiedType();
  13681. // Don't lose diagnostics about assignments to const.
  13682. if (HasConst)
  13683. DeclRefType.addConst();
  13684. }
  13685. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
  13686. }
  13687. if (ByRef)
  13688. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13689. else
  13690. CaptureType = DeclRefType;
  13691. // Actually capture the variable.
  13692. if (BuildAndDiagnose)
  13693. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  13694. Loc, SourceLocation(), CaptureType, Invalid);
  13695. return !Invalid;
  13696. }
  13697. /// Capture the given variable in the lambda.
  13698. static bool captureInLambda(LambdaScopeInfo *LSI,
  13699. VarDecl *Var,
  13700. SourceLocation Loc,
  13701. const bool BuildAndDiagnose,
  13702. QualType &CaptureType,
  13703. QualType &DeclRefType,
  13704. const bool RefersToCapturedVariable,
  13705. const Sema::TryCaptureKind Kind,
  13706. SourceLocation EllipsisLoc,
  13707. const bool IsTopScope,
  13708. Sema &S, bool Invalid) {
  13709. // Determine whether we are capturing by reference or by value.
  13710. bool ByRef = false;
  13711. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13712. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13713. } else {
  13714. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13715. }
  13716. // Compute the type of the field that will capture this variable.
  13717. if (ByRef) {
  13718. // C++11 [expr.prim.lambda]p15:
  13719. // An entity is captured by reference if it is implicitly or
  13720. // explicitly captured but not captured by copy. It is
  13721. // unspecified whether additional unnamed non-static data
  13722. // members are declared in the closure type for entities
  13723. // captured by reference.
  13724. //
  13725. // FIXME: It is not clear whether we want to build an lvalue reference
  13726. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13727. // to do the former, while EDG does the latter. Core issue 1249 will
  13728. // clarify, but for now we follow GCC because it's a more permissive and
  13729. // easily defensible position.
  13730. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13731. } else {
  13732. // C++11 [expr.prim.lambda]p14:
  13733. // For each entity captured by copy, an unnamed non-static
  13734. // data member is declared in the closure type. The
  13735. // declaration order of these members is unspecified. The type
  13736. // of such a data member is the type of the corresponding
  13737. // captured entity if the entity is not a reference to an
  13738. // object, or the referenced type otherwise. [Note: If the
  13739. // captured entity is a reference to a function, the
  13740. // corresponding data member is also a reference to a
  13741. // function. - end note ]
  13742. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  13743. if (!RefType->getPointeeType()->isFunctionType())
  13744. CaptureType = RefType->getPointeeType();
  13745. }
  13746. // Forbid the lambda copy-capture of autoreleasing variables.
  13747. if (!Invalid &&
  13748. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13749. if (BuildAndDiagnose) {
  13750. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  13751. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13752. << Var->getDeclName();
  13753. Invalid = true;
  13754. } else {
  13755. return false;
  13756. }
  13757. }
  13758. // Make sure that by-copy captures are of a complete and non-abstract type.
  13759. if (!Invalid && BuildAndDiagnose) {
  13760. if (!CaptureType->isDependentType() &&
  13761. S.RequireCompleteType(Loc, CaptureType,
  13762. diag::err_capture_of_incomplete_type,
  13763. Var->getDeclName()))
  13764. Invalid = true;
  13765. else if (S.RequireNonAbstractType(Loc, CaptureType,
  13766. diag::err_capture_of_abstract_type))
  13767. Invalid = true;
  13768. }
  13769. }
  13770. // Compute the type of a reference to this captured variable.
  13771. if (ByRef)
  13772. DeclRefType = CaptureType.getNonReferenceType();
  13773. else {
  13774. // C++ [expr.prim.lambda]p5:
  13775. // The closure type for a lambda-expression has a public inline
  13776. // function call operator [...]. This function call operator is
  13777. // declared const (9.3.1) if and only if the lambda-expression's
  13778. // parameter-declaration-clause is not followed by mutable.
  13779. DeclRefType = CaptureType.getNonReferenceType();
  13780. if (!LSI->Mutable && !CaptureType->isReferenceType())
  13781. DeclRefType.addConst();
  13782. }
  13783. // Add the capture.
  13784. if (BuildAndDiagnose)
  13785. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  13786. Loc, EllipsisLoc, CaptureType, Invalid);
  13787. return !Invalid;
  13788. }
  13789. bool Sema::tryCaptureVariable(
  13790. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  13791. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  13792. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  13793. // An init-capture is notionally from the context surrounding its
  13794. // declaration, but its parent DC is the lambda class.
  13795. DeclContext *VarDC = Var->getDeclContext();
  13796. if (Var->isInitCapture())
  13797. VarDC = VarDC->getParent();
  13798. DeclContext *DC = CurContext;
  13799. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  13800. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  13801. // We need to sync up the Declaration Context with the
  13802. // FunctionScopeIndexToStopAt
  13803. if (FunctionScopeIndexToStopAt) {
  13804. unsigned FSIndex = FunctionScopes.size() - 1;
  13805. while (FSIndex != MaxFunctionScopesIndex) {
  13806. DC = getLambdaAwareParentOfDeclContext(DC);
  13807. --FSIndex;
  13808. }
  13809. }
  13810. // If the variable is declared in the current context, there is no need to
  13811. // capture it.
  13812. if (VarDC == DC) return true;
  13813. // Capture global variables if it is required to use private copy of this
  13814. // variable.
  13815. bool IsGlobal = !Var->hasLocalStorage();
  13816. if (IsGlobal &&
  13817. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  13818. MaxFunctionScopesIndex)))
  13819. return true;
  13820. Var = Var->getCanonicalDecl();
  13821. // Walk up the stack to determine whether we can capture the variable,
  13822. // performing the "simple" checks that don't depend on type. We stop when
  13823. // we've either hit the declared scope of the variable or find an existing
  13824. // capture of that variable. We start from the innermost capturing-entity
  13825. // (the DC) and ensure that all intervening capturing-entities
  13826. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  13827. // declcontext can either capture the variable or have already captured
  13828. // the variable.
  13829. CaptureType = Var->getType();
  13830. DeclRefType = CaptureType.getNonReferenceType();
  13831. bool Nested = false;
  13832. bool Explicit = (Kind != TryCapture_Implicit);
  13833. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  13834. do {
  13835. // Only block literals, captured statements, and lambda expressions can
  13836. // capture; other scopes don't work.
  13837. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  13838. ExprLoc,
  13839. BuildAndDiagnose,
  13840. *this);
  13841. // We need to check for the parent *first* because, if we *have*
  13842. // private-captured a global variable, we need to recursively capture it in
  13843. // intermediate blocks, lambdas, etc.
  13844. if (!ParentDC) {
  13845. if (IsGlobal) {
  13846. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  13847. break;
  13848. }
  13849. return true;
  13850. }
  13851. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  13852. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  13853. // Check whether we've already captured it.
  13854. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  13855. DeclRefType)) {
  13856. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  13857. break;
  13858. }
  13859. // If we are instantiating a generic lambda call operator body,
  13860. // we do not want to capture new variables. What was captured
  13861. // during either a lambdas transformation or initial parsing
  13862. // should be used.
  13863. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  13864. if (BuildAndDiagnose) {
  13865. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13866. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  13867. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13868. Diag(Var->getLocation(), diag::note_previous_decl)
  13869. << Var->getDeclName();
  13870. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  13871. } else
  13872. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  13873. }
  13874. return true;
  13875. }
  13876. // Try to capture variable-length arrays types.
  13877. if (Var->getType()->isVariablyModifiedType()) {
  13878. // We're going to walk down into the type and look for VLA
  13879. // expressions.
  13880. QualType QTy = Var->getType();
  13881. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  13882. QTy = PVD->getOriginalType();
  13883. captureVariablyModifiedType(Context, QTy, CSI);
  13884. }
  13885. if (getLangOpts().OpenMP) {
  13886. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13887. // OpenMP private variables should not be captured in outer scope, so
  13888. // just break here. Similarly, global variables that are captured in a
  13889. // target region should not be captured outside the scope of the region.
  13890. if (RSI->CapRegionKind == CR_OpenMP) {
  13891. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  13892. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  13893. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  13894. // When we detect target captures we are looking from inside the
  13895. // target region, therefore we need to propagate the capture from the
  13896. // enclosing region. Therefore, the capture is not initially nested.
  13897. if (IsTargetCap)
  13898. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  13899. if (IsTargetCap || IsOpenMPPrivateDecl) {
  13900. Nested = !IsTargetCap;
  13901. DeclRefType = DeclRefType.getUnqualifiedType();
  13902. CaptureType = Context.getLValueReferenceType(DeclRefType);
  13903. break;
  13904. }
  13905. }
  13906. }
  13907. }
  13908. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  13909. // No capture-default, and this is not an explicit capture
  13910. // so cannot capture this variable.
  13911. if (BuildAndDiagnose) {
  13912. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13913. Diag(Var->getLocation(), diag::note_previous_decl)
  13914. << Var->getDeclName();
  13915. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  13916. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  13917. diag::note_lambda_decl);
  13918. // FIXME: If we error out because an outer lambda can not implicitly
  13919. // capture a variable that an inner lambda explicitly captures, we
  13920. // should have the inner lambda do the explicit capture - because
  13921. // it makes for cleaner diagnostics later. This would purely be done
  13922. // so that the diagnostic does not misleadingly claim that a variable
  13923. // can not be captured by a lambda implicitly even though it is captured
  13924. // explicitly. Suggestion:
  13925. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  13926. // at the function head
  13927. // - cache the StartingDeclContext - this must be a lambda
  13928. // - captureInLambda in the innermost lambda the variable.
  13929. }
  13930. return true;
  13931. }
  13932. FunctionScopesIndex--;
  13933. DC = ParentDC;
  13934. Explicit = false;
  13935. } while (!VarDC->Equals(DC));
  13936. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  13937. // computing the type of the capture at each step, checking type-specific
  13938. // requirements, and adding captures if requested.
  13939. // If the variable had already been captured previously, we start capturing
  13940. // at the lambda nested within that one.
  13941. bool Invalid = false;
  13942. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  13943. ++I) {
  13944. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  13945. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13946. // certain types of variables (unnamed, variably modified types etc.)
  13947. // so check for eligibility.
  13948. if (!Invalid)
  13949. Invalid =
  13950. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  13951. // After encountering an error, if we're actually supposed to capture, keep
  13952. // capturing in nested contexts to suppress any follow-on diagnostics.
  13953. if (Invalid && !BuildAndDiagnose)
  13954. return true;
  13955. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  13956. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  13957. DeclRefType, Nested, *this, Invalid);
  13958. Nested = true;
  13959. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13960. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  13961. CaptureType, DeclRefType, Nested,
  13962. *this, Invalid);
  13963. Nested = true;
  13964. } else {
  13965. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13966. Invalid =
  13967. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  13968. DeclRefType, Nested, Kind, EllipsisLoc,
  13969. /*IsTopScope*/ I == N - 1, *this, Invalid);
  13970. Nested = true;
  13971. }
  13972. if (Invalid && !BuildAndDiagnose)
  13973. return true;
  13974. }
  13975. return Invalid;
  13976. }
  13977. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  13978. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  13979. QualType CaptureType;
  13980. QualType DeclRefType;
  13981. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  13982. /*BuildAndDiagnose=*/true, CaptureType,
  13983. DeclRefType, nullptr);
  13984. }
  13985. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  13986. QualType CaptureType;
  13987. QualType DeclRefType;
  13988. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13989. /*BuildAndDiagnose=*/false, CaptureType,
  13990. DeclRefType, nullptr);
  13991. }
  13992. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  13993. QualType CaptureType;
  13994. QualType DeclRefType;
  13995. // Determine whether we can capture this variable.
  13996. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13997. /*BuildAndDiagnose=*/false, CaptureType,
  13998. DeclRefType, nullptr))
  13999. return QualType();
  14000. return DeclRefType;
  14001. }
  14002. namespace {
  14003. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  14004. // The produced TemplateArgumentListInfo* points to data stored within this
  14005. // object, so should only be used in contexts where the pointer will not be
  14006. // used after the CopiedTemplateArgs object is destroyed.
  14007. class CopiedTemplateArgs {
  14008. bool HasArgs;
  14009. TemplateArgumentListInfo TemplateArgStorage;
  14010. public:
  14011. template<typename RefExpr>
  14012. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  14013. if (HasArgs)
  14014. E->copyTemplateArgumentsInto(TemplateArgStorage);
  14015. }
  14016. operator TemplateArgumentListInfo*()
  14017. #ifdef __has_cpp_attribute
  14018. #if __has_cpp_attribute(clang::lifetimebound)
  14019. [[clang::lifetimebound]]
  14020. #endif
  14021. #endif
  14022. {
  14023. return HasArgs ? &TemplateArgStorage : nullptr;
  14024. }
  14025. };
  14026. }
  14027. /// Walk the set of potential results of an expression and mark them all as
  14028. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  14029. ///
  14030. /// \return A new expression if we found any potential results, ExprEmpty() if
  14031. /// not, and ExprError() if we diagnosed an error.
  14032. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  14033. NonOdrUseReason NOUR) {
  14034. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  14035. // an object that satisfies the requirements for appearing in a
  14036. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  14037. // is immediately applied." This function handles the lvalue-to-rvalue
  14038. // conversion part.
  14039. //
  14040. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  14041. // transform it into the relevant kind of non-odr-use node and rebuild the
  14042. // tree of nodes leading to it.
  14043. //
  14044. // This is a mini-TreeTransform that only transforms a restricted subset of
  14045. // nodes (and only certain operands of them).
  14046. // Rebuild a subexpression.
  14047. auto Rebuild = [&](Expr *Sub) {
  14048. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  14049. };
  14050. // Check whether a potential result satisfies the requirements of NOUR.
  14051. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  14052. // Any entity other than a VarDecl is always odr-used whenever it's named
  14053. // in a potentially-evaluated expression.
  14054. auto *VD = dyn_cast<VarDecl>(D);
  14055. if (!VD)
  14056. return true;
  14057. // C++2a [basic.def.odr]p4:
  14058. // A variable x whose name appears as a potentially-evalauted expression
  14059. // e is odr-used by e unless
  14060. // -- x is a reference that is usable in constant expressions, or
  14061. // -- x is a variable of non-reference type that is usable in constant
  14062. // expressions and has no mutable subobjects, and e is an element of
  14063. // the set of potential results of an expression of
  14064. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14065. // conversion is applied, or
  14066. // -- x is a variable of non-reference type, and e is an element of the
  14067. // set of potential results of a discarded-value expression to which
  14068. // the lvalue-to-rvalue conversion is not applied
  14069. //
  14070. // We check the first bullet and the "potentially-evaluated" condition in
  14071. // BuildDeclRefExpr. We check the type requirements in the second bullet
  14072. // in CheckLValueToRValueConversionOperand below.
  14073. switch (NOUR) {
  14074. case NOUR_None:
  14075. case NOUR_Unevaluated:
  14076. llvm_unreachable("unexpected non-odr-use-reason");
  14077. case NOUR_Constant:
  14078. // Constant references were handled when they were built.
  14079. if (VD->getType()->isReferenceType())
  14080. return true;
  14081. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  14082. if (RD->hasMutableFields())
  14083. return true;
  14084. if (!VD->isUsableInConstantExpressions(S.Context))
  14085. return true;
  14086. break;
  14087. case NOUR_Discarded:
  14088. if (VD->getType()->isReferenceType())
  14089. return true;
  14090. break;
  14091. }
  14092. return false;
  14093. };
  14094. // Mark that this expression does not constitute an odr-use.
  14095. auto MarkNotOdrUsed = [&] {
  14096. S.MaybeODRUseExprs.erase(E);
  14097. if (LambdaScopeInfo *LSI = S.getCurLambda())
  14098. LSI->markVariableExprAsNonODRUsed(E);
  14099. };
  14100. // C++2a [basic.def.odr]p2:
  14101. // The set of potential results of an expression e is defined as follows:
  14102. switch (E->getStmtClass()) {
  14103. // -- If e is an id-expression, ...
  14104. case Expr::DeclRefExprClass: {
  14105. auto *DRE = cast<DeclRefExpr>(E);
  14106. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  14107. break;
  14108. // Rebuild as a non-odr-use DeclRefExpr.
  14109. MarkNotOdrUsed();
  14110. return DeclRefExpr::Create(
  14111. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  14112. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  14113. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  14114. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  14115. }
  14116. case Expr::FunctionParmPackExprClass: {
  14117. auto *FPPE = cast<FunctionParmPackExpr>(E);
  14118. // If any of the declarations in the pack is odr-used, then the expression
  14119. // as a whole constitutes an odr-use.
  14120. for (VarDecl *D : *FPPE)
  14121. if (IsPotentialResultOdrUsed(D))
  14122. return ExprEmpty();
  14123. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  14124. // nothing cares about whether we marked this as an odr-use, but it might
  14125. // be useful for non-compiler tools.
  14126. MarkNotOdrUsed();
  14127. break;
  14128. }
  14129. // -- If e is a subscripting operation with an array operand...
  14130. case Expr::ArraySubscriptExprClass: {
  14131. auto *ASE = cast<ArraySubscriptExpr>(E);
  14132. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  14133. if (!OldBase->getType()->isArrayType())
  14134. break;
  14135. ExprResult Base = Rebuild(OldBase);
  14136. if (!Base.isUsable())
  14137. return Base;
  14138. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  14139. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  14140. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  14141. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  14142. ASE->getRBracketLoc());
  14143. }
  14144. case Expr::MemberExprClass: {
  14145. auto *ME = cast<MemberExpr>(E);
  14146. // -- If e is a class member access expression [...] naming a non-static
  14147. // data member...
  14148. if (isa<FieldDecl>(ME->getMemberDecl())) {
  14149. ExprResult Base = Rebuild(ME->getBase());
  14150. if (!Base.isUsable())
  14151. return Base;
  14152. return MemberExpr::Create(
  14153. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  14154. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  14155. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  14156. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  14157. ME->getObjectKind(), ME->isNonOdrUse());
  14158. }
  14159. if (ME->getMemberDecl()->isCXXInstanceMember())
  14160. break;
  14161. // -- If e is a class member access expression naming a static data member,
  14162. // ...
  14163. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  14164. break;
  14165. // Rebuild as a non-odr-use MemberExpr.
  14166. MarkNotOdrUsed();
  14167. return MemberExpr::Create(
  14168. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  14169. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  14170. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  14171. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  14172. return ExprEmpty();
  14173. }
  14174. case Expr::BinaryOperatorClass: {
  14175. auto *BO = cast<BinaryOperator>(E);
  14176. Expr *LHS = BO->getLHS();
  14177. Expr *RHS = BO->getRHS();
  14178. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  14179. if (BO->getOpcode() == BO_PtrMemD) {
  14180. ExprResult Sub = Rebuild(LHS);
  14181. if (!Sub.isUsable())
  14182. return Sub;
  14183. LHS = Sub.get();
  14184. // -- If e is a comma expression, ...
  14185. } else if (BO->getOpcode() == BO_Comma) {
  14186. ExprResult Sub = Rebuild(RHS);
  14187. if (!Sub.isUsable())
  14188. return Sub;
  14189. RHS = Sub.get();
  14190. } else {
  14191. break;
  14192. }
  14193. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  14194. LHS, RHS);
  14195. }
  14196. // -- If e has the form (e1)...
  14197. case Expr::ParenExprClass: {
  14198. auto *PE = cast<ParenExpr>(E);
  14199. ExprResult Sub = Rebuild(PE->getSubExpr());
  14200. if (!Sub.isUsable())
  14201. return Sub;
  14202. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  14203. }
  14204. // -- If e is a glvalue conditional expression, ...
  14205. // We don't apply this to a binary conditional operator. FIXME: Should we?
  14206. case Expr::ConditionalOperatorClass: {
  14207. auto *CO = cast<ConditionalOperator>(E);
  14208. ExprResult LHS = Rebuild(CO->getLHS());
  14209. if (LHS.isInvalid())
  14210. return ExprError();
  14211. ExprResult RHS = Rebuild(CO->getRHS());
  14212. if (RHS.isInvalid())
  14213. return ExprError();
  14214. if (!LHS.isUsable() && !RHS.isUsable())
  14215. return ExprEmpty();
  14216. if (!LHS.isUsable())
  14217. LHS = CO->getLHS();
  14218. if (!RHS.isUsable())
  14219. RHS = CO->getRHS();
  14220. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  14221. CO->getCond(), LHS.get(), RHS.get());
  14222. }
  14223. // [Clang extension]
  14224. // -- If e has the form __extension__ e1...
  14225. case Expr::UnaryOperatorClass: {
  14226. auto *UO = cast<UnaryOperator>(E);
  14227. if (UO->getOpcode() != UO_Extension)
  14228. break;
  14229. ExprResult Sub = Rebuild(UO->getSubExpr());
  14230. if (!Sub.isUsable())
  14231. return Sub;
  14232. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  14233. Sub.get());
  14234. }
  14235. // [Clang extension]
  14236. // -- If e has the form _Generic(...), the set of potential results is the
  14237. // union of the sets of potential results of the associated expressions.
  14238. case Expr::GenericSelectionExprClass: {
  14239. auto *GSE = cast<GenericSelectionExpr>(E);
  14240. SmallVector<Expr *, 4> AssocExprs;
  14241. bool AnyChanged = false;
  14242. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  14243. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  14244. if (AssocExpr.isInvalid())
  14245. return ExprError();
  14246. if (AssocExpr.isUsable()) {
  14247. AssocExprs.push_back(AssocExpr.get());
  14248. AnyChanged = true;
  14249. } else {
  14250. AssocExprs.push_back(OrigAssocExpr);
  14251. }
  14252. }
  14253. return AnyChanged ? S.CreateGenericSelectionExpr(
  14254. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  14255. GSE->getRParenLoc(), GSE->getControllingExpr(),
  14256. GSE->getAssocTypeSourceInfos(), AssocExprs)
  14257. : ExprEmpty();
  14258. }
  14259. // [Clang extension]
  14260. // -- If e has the form __builtin_choose_expr(...), the set of potential
  14261. // results is the union of the sets of potential results of the
  14262. // second and third subexpressions.
  14263. case Expr::ChooseExprClass: {
  14264. auto *CE = cast<ChooseExpr>(E);
  14265. ExprResult LHS = Rebuild(CE->getLHS());
  14266. if (LHS.isInvalid())
  14267. return ExprError();
  14268. ExprResult RHS = Rebuild(CE->getLHS());
  14269. if (RHS.isInvalid())
  14270. return ExprError();
  14271. if (!LHS.get() && !RHS.get())
  14272. return ExprEmpty();
  14273. if (!LHS.isUsable())
  14274. LHS = CE->getLHS();
  14275. if (!RHS.isUsable())
  14276. RHS = CE->getRHS();
  14277. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  14278. RHS.get(), CE->getRParenLoc());
  14279. }
  14280. // Step through non-syntactic nodes.
  14281. case Expr::ConstantExprClass: {
  14282. auto *CE = cast<ConstantExpr>(E);
  14283. ExprResult Sub = Rebuild(CE->getSubExpr());
  14284. if (!Sub.isUsable())
  14285. return Sub;
  14286. return ConstantExpr::Create(S.Context, Sub.get());
  14287. }
  14288. // We could mostly rely on the recursive rebuilding to rebuild implicit
  14289. // casts, but not at the top level, so rebuild them here.
  14290. case Expr::ImplicitCastExprClass: {
  14291. auto *ICE = cast<ImplicitCastExpr>(E);
  14292. // Only step through the narrow set of cast kinds we expect to encounter.
  14293. // Anything else suggests we've left the region in which potential results
  14294. // can be found.
  14295. switch (ICE->getCastKind()) {
  14296. case CK_NoOp:
  14297. case CK_DerivedToBase:
  14298. case CK_UncheckedDerivedToBase: {
  14299. ExprResult Sub = Rebuild(ICE->getSubExpr());
  14300. if (!Sub.isUsable())
  14301. return Sub;
  14302. CXXCastPath Path(ICE->path());
  14303. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  14304. ICE->getValueKind(), &Path);
  14305. }
  14306. default:
  14307. break;
  14308. }
  14309. break;
  14310. }
  14311. default:
  14312. break;
  14313. }
  14314. // Can't traverse through this node. Nothing to do.
  14315. return ExprEmpty();
  14316. }
  14317. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  14318. // Check whether the operand is or contains an object of non-trivial C union
  14319. // type.
  14320. if (E->getType().isVolatileQualified() &&
  14321. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  14322. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  14323. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  14324. Sema::NTCUC_LValueToRValueVolatile,
  14325. NTCUK_Destruct|NTCUK_Copy);
  14326. // C++2a [basic.def.odr]p4:
  14327. // [...] an expression of non-volatile-qualified non-class type to which
  14328. // the lvalue-to-rvalue conversion is applied [...]
  14329. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  14330. return E;
  14331. ExprResult Result =
  14332. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  14333. if (Result.isInvalid())
  14334. return ExprError();
  14335. return Result.get() ? Result : E;
  14336. }
  14337. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  14338. Res = CorrectDelayedTyposInExpr(Res);
  14339. if (!Res.isUsable())
  14340. return Res;
  14341. // If a constant-expression is a reference to a variable where we delay
  14342. // deciding whether it is an odr-use, just assume we will apply the
  14343. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  14344. // (a non-type template argument), we have special handling anyway.
  14345. return CheckLValueToRValueConversionOperand(Res.get());
  14346. }
  14347. void Sema::CleanupVarDeclMarking() {
  14348. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  14349. // call.
  14350. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  14351. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  14352. for (Expr *E : LocalMaybeODRUseExprs) {
  14353. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  14354. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  14355. DRE->getLocation(), *this);
  14356. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  14357. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  14358. *this);
  14359. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  14360. for (VarDecl *VD : *FP)
  14361. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  14362. } else {
  14363. llvm_unreachable("Unexpected expression");
  14364. }
  14365. }
  14366. assert(MaybeODRUseExprs.empty() &&
  14367. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  14368. }
  14369. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  14370. VarDecl *Var, Expr *E) {
  14371. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  14372. isa<FunctionParmPackExpr>(E)) &&
  14373. "Invalid Expr argument to DoMarkVarDeclReferenced");
  14374. Var->setReferenced();
  14375. if (Var->isInvalidDecl())
  14376. return;
  14377. auto *MSI = Var->getMemberSpecializationInfo();
  14378. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  14379. : Var->getTemplateSpecializationKind();
  14380. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  14381. bool UsableInConstantExpr =
  14382. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  14383. // C++20 [expr.const]p12:
  14384. // A variable [...] is needed for constant evaluation if it is [...] a
  14385. // variable whose name appears as a potentially constant evaluated
  14386. // expression that is either a contexpr variable or is of non-volatile
  14387. // const-qualified integral type or of reference type
  14388. bool NeededForConstantEvaluation =
  14389. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  14390. bool NeedDefinition =
  14391. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  14392. VarTemplateSpecializationDecl *VarSpec =
  14393. dyn_cast<VarTemplateSpecializationDecl>(Var);
  14394. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  14395. "Can't instantiate a partial template specialization.");
  14396. // If this might be a member specialization of a static data member, check
  14397. // the specialization is visible. We already did the checks for variable
  14398. // template specializations when we created them.
  14399. if (NeedDefinition && TSK != TSK_Undeclared &&
  14400. !isa<VarTemplateSpecializationDecl>(Var))
  14401. SemaRef.checkSpecializationVisibility(Loc, Var);
  14402. // Perform implicit instantiation of static data members, static data member
  14403. // templates of class templates, and variable template specializations. Delay
  14404. // instantiations of variable templates, except for those that could be used
  14405. // in a constant expression.
  14406. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  14407. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  14408. // instantiation declaration if a variable is usable in a constant
  14409. // expression (among other cases).
  14410. bool TryInstantiating =
  14411. TSK == TSK_ImplicitInstantiation ||
  14412. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  14413. if (TryInstantiating) {
  14414. SourceLocation PointOfInstantiation =
  14415. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  14416. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  14417. if (FirstInstantiation) {
  14418. PointOfInstantiation = Loc;
  14419. if (MSI)
  14420. MSI->setPointOfInstantiation(PointOfInstantiation);
  14421. else
  14422. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  14423. }
  14424. bool InstantiationDependent = false;
  14425. bool IsNonDependent =
  14426. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  14427. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  14428. : true;
  14429. // Do not instantiate specializations that are still type-dependent.
  14430. if (IsNonDependent) {
  14431. if (UsableInConstantExpr) {
  14432. // Do not defer instantiations of variables that could be used in a
  14433. // constant expression.
  14434. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  14435. } else if (FirstInstantiation ||
  14436. isa<VarTemplateSpecializationDecl>(Var)) {
  14437. // FIXME: For a specialization of a variable template, we don't
  14438. // distinguish between "declaration and type implicitly instantiated"
  14439. // and "implicit instantiation of definition requested", so we have
  14440. // no direct way to avoid enqueueing the pending instantiation
  14441. // multiple times.
  14442. SemaRef.PendingInstantiations
  14443. .push_back(std::make_pair(Var, PointOfInstantiation));
  14444. }
  14445. }
  14446. }
  14447. }
  14448. // C++2a [basic.def.odr]p4:
  14449. // A variable x whose name appears as a potentially-evaluated expression e
  14450. // is odr-used by e unless
  14451. // -- x is a reference that is usable in constant expressions
  14452. // -- x is a variable of non-reference type that is usable in constant
  14453. // expressions and has no mutable subobjects [FIXME], and e is an
  14454. // element of the set of potential results of an expression of
  14455. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14456. // conversion is applied
  14457. // -- x is a variable of non-reference type, and e is an element of the set
  14458. // of potential results of a discarded-value expression to which the
  14459. // lvalue-to-rvalue conversion is not applied [FIXME]
  14460. //
  14461. // We check the first part of the second bullet here, and
  14462. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  14463. // FIXME: To get the third bullet right, we need to delay this even for
  14464. // variables that are not usable in constant expressions.
  14465. // If we already know this isn't an odr-use, there's nothing more to do.
  14466. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  14467. if (DRE->isNonOdrUse())
  14468. return;
  14469. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  14470. if (ME->isNonOdrUse())
  14471. return;
  14472. switch (OdrUse) {
  14473. case OdrUseContext::None:
  14474. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  14475. "missing non-odr-use marking for unevaluated decl ref");
  14476. break;
  14477. case OdrUseContext::FormallyOdrUsed:
  14478. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14479. // behavior.
  14480. break;
  14481. case OdrUseContext::Used:
  14482. // If we might later find that this expression isn't actually an odr-use,
  14483. // delay the marking.
  14484. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  14485. SemaRef.MaybeODRUseExprs.insert(E);
  14486. else
  14487. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  14488. break;
  14489. case OdrUseContext::Dependent:
  14490. // If this is a dependent context, we don't need to mark variables as
  14491. // odr-used, but we may still need to track them for lambda capture.
  14492. // FIXME: Do we also need to do this inside dependent typeid expressions
  14493. // (which are modeled as unevaluated at this point)?
  14494. const bool RefersToEnclosingScope =
  14495. (SemaRef.CurContext != Var->getDeclContext() &&
  14496. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14497. if (RefersToEnclosingScope) {
  14498. LambdaScopeInfo *const LSI =
  14499. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14500. if (LSI && (!LSI->CallOperator ||
  14501. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14502. // If a variable could potentially be odr-used, defer marking it so
  14503. // until we finish analyzing the full expression for any
  14504. // lvalue-to-rvalue
  14505. // or discarded value conversions that would obviate odr-use.
  14506. // Add it to the list of potential captures that will be analyzed
  14507. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14508. // unless the variable is a reference that was initialized by a constant
  14509. // expression (this will never need to be captured or odr-used).
  14510. //
  14511. // FIXME: We can simplify this a lot after implementing P0588R1.
  14512. assert(E && "Capture variable should be used in an expression.");
  14513. if (!Var->getType()->isReferenceType() ||
  14514. !Var->isUsableInConstantExpressions(SemaRef.Context))
  14515. LSI->addPotentialCapture(E->IgnoreParens());
  14516. }
  14517. }
  14518. break;
  14519. }
  14520. }
  14521. /// Mark a variable referenced, and check whether it is odr-used
  14522. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14523. /// used directly for normal expressions referring to VarDecl.
  14524. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14525. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14526. }
  14527. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14528. Decl *D, Expr *E, bool MightBeOdrUse) {
  14529. if (SemaRef.isInOpenMPDeclareTargetContext())
  14530. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14531. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14532. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14533. return;
  14534. }
  14535. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14536. // If this is a call to a method via a cast, also mark the method in the
  14537. // derived class used in case codegen can devirtualize the call.
  14538. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14539. if (!ME)
  14540. return;
  14541. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14542. if (!MD)
  14543. return;
  14544. // Only attempt to devirtualize if this is truly a virtual call.
  14545. bool IsVirtualCall = MD->isVirtual() &&
  14546. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14547. if (!IsVirtualCall)
  14548. return;
  14549. // If it's possible to devirtualize the call, mark the called function
  14550. // referenced.
  14551. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14552. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14553. if (DM)
  14554. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14555. }
  14556. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14557. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14558. // TODO: update this with DR# once a defect report is filed.
  14559. // C++11 defect. The address of a pure member should not be an ODR use, even
  14560. // if it's a qualified reference.
  14561. bool OdrUse = true;
  14562. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14563. if (Method->isVirtual() &&
  14564. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14565. OdrUse = false;
  14566. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14567. }
  14568. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14569. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14570. // C++11 [basic.def.odr]p2:
  14571. // A non-overloaded function whose name appears as a potentially-evaluated
  14572. // expression or a member of a set of candidate functions, if selected by
  14573. // overload resolution when referred to from a potentially-evaluated
  14574. // expression, is odr-used, unless it is a pure virtual function and its
  14575. // name is not explicitly qualified.
  14576. bool MightBeOdrUse = true;
  14577. if (E->performsVirtualDispatch(getLangOpts())) {
  14578. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14579. if (Method->isPure())
  14580. MightBeOdrUse = false;
  14581. }
  14582. SourceLocation Loc =
  14583. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14584. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14585. }
  14586. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14587. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14588. for (VarDecl *VD : *E)
  14589. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14590. }
  14591. /// Perform marking for a reference to an arbitrary declaration. It
  14592. /// marks the declaration referenced, and performs odr-use checking for
  14593. /// functions and variables. This method should not be used when building a
  14594. /// normal expression which refers to a variable.
  14595. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14596. bool MightBeOdrUse) {
  14597. if (MightBeOdrUse) {
  14598. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14599. MarkVariableReferenced(Loc, VD);
  14600. return;
  14601. }
  14602. }
  14603. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14604. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14605. return;
  14606. }
  14607. D->setReferenced();
  14608. }
  14609. namespace {
  14610. // Mark all of the declarations used by a type as referenced.
  14611. // FIXME: Not fully implemented yet! We need to have a better understanding
  14612. // of when we're entering a context we should not recurse into.
  14613. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14614. // TreeTransforms rebuilding the type in a new context. Rather than
  14615. // duplicating the TreeTransform logic, we should consider reusing it here.
  14616. // Currently that causes problems when rebuilding LambdaExprs.
  14617. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14618. Sema &S;
  14619. SourceLocation Loc;
  14620. public:
  14621. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14622. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14623. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14624. };
  14625. }
  14626. bool MarkReferencedDecls::TraverseTemplateArgument(
  14627. const TemplateArgument &Arg) {
  14628. {
  14629. // A non-type template argument is a constant-evaluated context.
  14630. EnterExpressionEvaluationContext Evaluated(
  14631. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14632. if (Arg.getKind() == TemplateArgument::Declaration) {
  14633. if (Decl *D = Arg.getAsDecl())
  14634. S.MarkAnyDeclReferenced(Loc, D, true);
  14635. } else if (Arg.getKind() == TemplateArgument::Expression) {
  14636. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  14637. }
  14638. }
  14639. return Inherited::TraverseTemplateArgument(Arg);
  14640. }
  14641. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  14642. MarkReferencedDecls Marker(*this, Loc);
  14643. Marker.TraverseType(T);
  14644. }
  14645. namespace {
  14646. /// Helper class that marks all of the declarations referenced by
  14647. /// potentially-evaluated subexpressions as "referenced".
  14648. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  14649. Sema &S;
  14650. bool SkipLocalVariables;
  14651. public:
  14652. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  14653. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  14654. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  14655. void VisitDeclRefExpr(DeclRefExpr *E) {
  14656. // If we were asked not to visit local variables, don't.
  14657. if (SkipLocalVariables) {
  14658. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  14659. if (VD->hasLocalStorage())
  14660. return;
  14661. }
  14662. S.MarkDeclRefReferenced(E);
  14663. }
  14664. void VisitMemberExpr(MemberExpr *E) {
  14665. S.MarkMemberReferenced(E);
  14666. Inherited::VisitMemberExpr(E);
  14667. }
  14668. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  14669. S.MarkFunctionReferenced(
  14670. E->getBeginLoc(),
  14671. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  14672. Visit(E->getSubExpr());
  14673. }
  14674. void VisitCXXNewExpr(CXXNewExpr *E) {
  14675. if (E->getOperatorNew())
  14676. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  14677. if (E->getOperatorDelete())
  14678. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14679. Inherited::VisitCXXNewExpr(E);
  14680. }
  14681. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  14682. if (E->getOperatorDelete())
  14683. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14684. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  14685. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  14686. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  14687. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  14688. }
  14689. Inherited::VisitCXXDeleteExpr(E);
  14690. }
  14691. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  14692. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  14693. Inherited::VisitCXXConstructExpr(E);
  14694. }
  14695. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  14696. Visit(E->getExpr());
  14697. }
  14698. };
  14699. }
  14700. /// Mark any declarations that appear within this expression or any
  14701. /// potentially-evaluated subexpressions as "referenced".
  14702. ///
  14703. /// \param SkipLocalVariables If true, don't mark local variables as
  14704. /// 'referenced'.
  14705. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  14706. bool SkipLocalVariables) {
  14707. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  14708. }
  14709. /// Emit a diagnostic that describes an effect on the run-time behavior
  14710. /// of the program being compiled.
  14711. ///
  14712. /// This routine emits the given diagnostic when the code currently being
  14713. /// type-checked is "potentially evaluated", meaning that there is a
  14714. /// possibility that the code will actually be executable. Code in sizeof()
  14715. /// expressions, code used only during overload resolution, etc., are not
  14716. /// potentially evaluated. This routine will suppress such diagnostics or,
  14717. /// in the absolutely nutty case of potentially potentially evaluated
  14718. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  14719. /// later.
  14720. ///
  14721. /// This routine should be used for all diagnostics that describe the run-time
  14722. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  14723. /// Failure to do so will likely result in spurious diagnostics or failures
  14724. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  14725. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  14726. const PartialDiagnostic &PD) {
  14727. switch (ExprEvalContexts.back().Context) {
  14728. case ExpressionEvaluationContext::Unevaluated:
  14729. case ExpressionEvaluationContext::UnevaluatedList:
  14730. case ExpressionEvaluationContext::UnevaluatedAbstract:
  14731. case ExpressionEvaluationContext::DiscardedStatement:
  14732. // The argument will never be evaluated, so don't complain.
  14733. break;
  14734. case ExpressionEvaluationContext::ConstantEvaluated:
  14735. // Relevant diagnostics should be produced by constant evaluation.
  14736. break;
  14737. case ExpressionEvaluationContext::PotentiallyEvaluated:
  14738. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  14739. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  14740. FunctionScopes.back()->PossiblyUnreachableDiags.
  14741. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  14742. return true;
  14743. }
  14744. // The initializer of a constexpr variable or of the first declaration of a
  14745. // static data member is not syntactically a constant evaluated constant,
  14746. // but nonetheless is always required to be a constant expression, so we
  14747. // can skip diagnosing.
  14748. // FIXME: Using the mangling context here is a hack.
  14749. if (auto *VD = dyn_cast_or_null<VarDecl>(
  14750. ExprEvalContexts.back().ManglingContextDecl)) {
  14751. if (VD->isConstexpr() ||
  14752. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  14753. break;
  14754. // FIXME: For any other kind of variable, we should build a CFG for its
  14755. // initializer and check whether the context in question is reachable.
  14756. }
  14757. Diag(Loc, PD);
  14758. return true;
  14759. }
  14760. return false;
  14761. }
  14762. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  14763. const PartialDiagnostic &PD) {
  14764. return DiagRuntimeBehavior(
  14765. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  14766. }
  14767. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  14768. CallExpr *CE, FunctionDecl *FD) {
  14769. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  14770. return false;
  14771. // If we're inside a decltype's expression, don't check for a valid return
  14772. // type or construct temporaries until we know whether this is the last call.
  14773. if (ExprEvalContexts.back().ExprContext ==
  14774. ExpressionEvaluationContextRecord::EK_Decltype) {
  14775. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  14776. return false;
  14777. }
  14778. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  14779. FunctionDecl *FD;
  14780. CallExpr *CE;
  14781. public:
  14782. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  14783. : FD(FD), CE(CE) { }
  14784. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  14785. if (!FD) {
  14786. S.Diag(Loc, diag::err_call_incomplete_return)
  14787. << T << CE->getSourceRange();
  14788. return;
  14789. }
  14790. S.Diag(Loc, diag::err_call_function_incomplete_return)
  14791. << CE->getSourceRange() << FD->getDeclName() << T;
  14792. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  14793. << FD->getDeclName();
  14794. }
  14795. } Diagnoser(FD, CE);
  14796. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  14797. return true;
  14798. return false;
  14799. }
  14800. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  14801. // will prevent this condition from triggering, which is what we want.
  14802. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  14803. SourceLocation Loc;
  14804. unsigned diagnostic = diag::warn_condition_is_assignment;
  14805. bool IsOrAssign = false;
  14806. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  14807. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  14808. return;
  14809. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  14810. // Greylist some idioms by putting them into a warning subcategory.
  14811. if (ObjCMessageExpr *ME
  14812. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  14813. Selector Sel = ME->getSelector();
  14814. // self = [<foo> init...]
  14815. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  14816. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  14817. // <foo> = [<bar> nextObject]
  14818. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  14819. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  14820. }
  14821. Loc = Op->getOperatorLoc();
  14822. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  14823. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  14824. return;
  14825. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  14826. Loc = Op->getOperatorLoc();
  14827. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  14828. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  14829. else {
  14830. // Not an assignment.
  14831. return;
  14832. }
  14833. Diag(Loc, diagnostic) << E->getSourceRange();
  14834. SourceLocation Open = E->getBeginLoc();
  14835. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  14836. Diag(Loc, diag::note_condition_assign_silence)
  14837. << FixItHint::CreateInsertion(Open, "(")
  14838. << FixItHint::CreateInsertion(Close, ")");
  14839. if (IsOrAssign)
  14840. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  14841. << FixItHint::CreateReplacement(Loc, "!=");
  14842. else
  14843. Diag(Loc, diag::note_condition_assign_to_comparison)
  14844. << FixItHint::CreateReplacement(Loc, "==");
  14845. }
  14846. /// Redundant parentheses over an equality comparison can indicate
  14847. /// that the user intended an assignment used as condition.
  14848. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  14849. // Don't warn if the parens came from a macro.
  14850. SourceLocation parenLoc = ParenE->getBeginLoc();
  14851. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  14852. return;
  14853. // Don't warn for dependent expressions.
  14854. if (ParenE->isTypeDependent())
  14855. return;
  14856. Expr *E = ParenE->IgnoreParens();
  14857. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  14858. if (opE->getOpcode() == BO_EQ &&
  14859. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  14860. == Expr::MLV_Valid) {
  14861. SourceLocation Loc = opE->getOperatorLoc();
  14862. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  14863. SourceRange ParenERange = ParenE->getSourceRange();
  14864. Diag(Loc, diag::note_equality_comparison_silence)
  14865. << FixItHint::CreateRemoval(ParenERange.getBegin())
  14866. << FixItHint::CreateRemoval(ParenERange.getEnd());
  14867. Diag(Loc, diag::note_equality_comparison_to_assign)
  14868. << FixItHint::CreateReplacement(Loc, "=");
  14869. }
  14870. }
  14871. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  14872. bool IsConstexpr) {
  14873. DiagnoseAssignmentAsCondition(E);
  14874. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  14875. DiagnoseEqualityWithExtraParens(parenE);
  14876. ExprResult result = CheckPlaceholderExpr(E);
  14877. if (result.isInvalid()) return ExprError();
  14878. E = result.get();
  14879. if (!E->isTypeDependent()) {
  14880. if (getLangOpts().CPlusPlus)
  14881. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  14882. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  14883. if (ERes.isInvalid())
  14884. return ExprError();
  14885. E = ERes.get();
  14886. QualType T = E->getType();
  14887. if (!T->isScalarType()) { // C99 6.8.4.1p1
  14888. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  14889. << T << E->getSourceRange();
  14890. return ExprError();
  14891. }
  14892. CheckBoolLikeConversion(E, Loc);
  14893. }
  14894. return E;
  14895. }
  14896. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  14897. Expr *SubExpr, ConditionKind CK) {
  14898. // Empty conditions are valid in for-statements.
  14899. if (!SubExpr)
  14900. return ConditionResult();
  14901. ExprResult Cond;
  14902. switch (CK) {
  14903. case ConditionKind::Boolean:
  14904. Cond = CheckBooleanCondition(Loc, SubExpr);
  14905. break;
  14906. case ConditionKind::ConstexprIf:
  14907. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  14908. break;
  14909. case ConditionKind::Switch:
  14910. Cond = CheckSwitchCondition(Loc, SubExpr);
  14911. break;
  14912. }
  14913. if (Cond.isInvalid())
  14914. return ConditionError();
  14915. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  14916. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  14917. if (!FullExpr.get())
  14918. return ConditionError();
  14919. return ConditionResult(*this, nullptr, FullExpr,
  14920. CK == ConditionKind::ConstexprIf);
  14921. }
  14922. namespace {
  14923. /// A visitor for rebuilding a call to an __unknown_any expression
  14924. /// to have an appropriate type.
  14925. struct RebuildUnknownAnyFunction
  14926. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  14927. Sema &S;
  14928. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  14929. ExprResult VisitStmt(Stmt *S) {
  14930. llvm_unreachable("unexpected statement!");
  14931. }
  14932. ExprResult VisitExpr(Expr *E) {
  14933. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  14934. << E->getSourceRange();
  14935. return ExprError();
  14936. }
  14937. /// Rebuild an expression which simply semantically wraps another
  14938. /// expression which it shares the type and value kind of.
  14939. template <class T> ExprResult rebuildSugarExpr(T *E) {
  14940. ExprResult SubResult = Visit(E->getSubExpr());
  14941. if (SubResult.isInvalid()) return ExprError();
  14942. Expr *SubExpr = SubResult.get();
  14943. E->setSubExpr(SubExpr);
  14944. E->setType(SubExpr->getType());
  14945. E->setValueKind(SubExpr->getValueKind());
  14946. assert(E->getObjectKind() == OK_Ordinary);
  14947. return E;
  14948. }
  14949. ExprResult VisitParenExpr(ParenExpr *E) {
  14950. return rebuildSugarExpr(E);
  14951. }
  14952. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14953. return rebuildSugarExpr(E);
  14954. }
  14955. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14956. ExprResult SubResult = Visit(E->getSubExpr());
  14957. if (SubResult.isInvalid()) return ExprError();
  14958. Expr *SubExpr = SubResult.get();
  14959. E->setSubExpr(SubExpr);
  14960. E->setType(S.Context.getPointerType(SubExpr->getType()));
  14961. assert(E->getValueKind() == VK_RValue);
  14962. assert(E->getObjectKind() == OK_Ordinary);
  14963. return E;
  14964. }
  14965. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  14966. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  14967. E->setType(VD->getType());
  14968. assert(E->getValueKind() == VK_RValue);
  14969. if (S.getLangOpts().CPlusPlus &&
  14970. !(isa<CXXMethodDecl>(VD) &&
  14971. cast<CXXMethodDecl>(VD)->isInstance()))
  14972. E->setValueKind(VK_LValue);
  14973. return E;
  14974. }
  14975. ExprResult VisitMemberExpr(MemberExpr *E) {
  14976. return resolveDecl(E, E->getMemberDecl());
  14977. }
  14978. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14979. return resolveDecl(E, E->getDecl());
  14980. }
  14981. };
  14982. }
  14983. /// Given a function expression of unknown-any type, try to rebuild it
  14984. /// to have a function type.
  14985. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  14986. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  14987. if (Result.isInvalid()) return ExprError();
  14988. return S.DefaultFunctionArrayConversion(Result.get());
  14989. }
  14990. namespace {
  14991. /// A visitor for rebuilding an expression of type __unknown_anytype
  14992. /// into one which resolves the type directly on the referring
  14993. /// expression. Strict preservation of the original source
  14994. /// structure is not a goal.
  14995. struct RebuildUnknownAnyExpr
  14996. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  14997. Sema &S;
  14998. /// The current destination type.
  14999. QualType DestType;
  15000. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  15001. : S(S), DestType(CastType) {}
  15002. ExprResult VisitStmt(Stmt *S) {
  15003. llvm_unreachable("unexpected statement!");
  15004. }
  15005. ExprResult VisitExpr(Expr *E) {
  15006. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15007. << E->getSourceRange();
  15008. return ExprError();
  15009. }
  15010. ExprResult VisitCallExpr(CallExpr *E);
  15011. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  15012. /// Rebuild an expression which simply semantically wraps another
  15013. /// expression which it shares the type and value kind of.
  15014. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15015. ExprResult SubResult = Visit(E->getSubExpr());
  15016. if (SubResult.isInvalid()) return ExprError();
  15017. Expr *SubExpr = SubResult.get();
  15018. E->setSubExpr(SubExpr);
  15019. E->setType(SubExpr->getType());
  15020. E->setValueKind(SubExpr->getValueKind());
  15021. assert(E->getObjectKind() == OK_Ordinary);
  15022. return E;
  15023. }
  15024. ExprResult VisitParenExpr(ParenExpr *E) {
  15025. return rebuildSugarExpr(E);
  15026. }
  15027. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15028. return rebuildSugarExpr(E);
  15029. }
  15030. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15031. const PointerType *Ptr = DestType->getAs<PointerType>();
  15032. if (!Ptr) {
  15033. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  15034. << E->getSourceRange();
  15035. return ExprError();
  15036. }
  15037. if (isa<CallExpr>(E->getSubExpr())) {
  15038. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  15039. << E->getSourceRange();
  15040. return ExprError();
  15041. }
  15042. assert(E->getValueKind() == VK_RValue);
  15043. assert(E->getObjectKind() == OK_Ordinary);
  15044. E->setType(DestType);
  15045. // Build the sub-expression as if it were an object of the pointee type.
  15046. DestType = Ptr->getPointeeType();
  15047. ExprResult SubResult = Visit(E->getSubExpr());
  15048. if (SubResult.isInvalid()) return ExprError();
  15049. E->setSubExpr(SubResult.get());
  15050. return E;
  15051. }
  15052. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  15053. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  15054. ExprResult VisitMemberExpr(MemberExpr *E) {
  15055. return resolveDecl(E, E->getMemberDecl());
  15056. }
  15057. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15058. return resolveDecl(E, E->getDecl());
  15059. }
  15060. };
  15061. }
  15062. /// Rebuilds a call expression which yielded __unknown_anytype.
  15063. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  15064. Expr *CalleeExpr = E->getCallee();
  15065. enum FnKind {
  15066. FK_MemberFunction,
  15067. FK_FunctionPointer,
  15068. FK_BlockPointer
  15069. };
  15070. FnKind Kind;
  15071. QualType CalleeType = CalleeExpr->getType();
  15072. if (CalleeType == S.Context.BoundMemberTy) {
  15073. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  15074. Kind = FK_MemberFunction;
  15075. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  15076. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  15077. CalleeType = Ptr->getPointeeType();
  15078. Kind = FK_FunctionPointer;
  15079. } else {
  15080. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  15081. Kind = FK_BlockPointer;
  15082. }
  15083. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  15084. // Verify that this is a legal result type of a function.
  15085. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15086. unsigned diagID = diag::err_func_returning_array_function;
  15087. if (Kind == FK_BlockPointer)
  15088. diagID = diag::err_block_returning_array_function;
  15089. S.Diag(E->getExprLoc(), diagID)
  15090. << DestType->isFunctionType() << DestType;
  15091. return ExprError();
  15092. }
  15093. // Otherwise, go ahead and set DestType as the call's result.
  15094. E->setType(DestType.getNonLValueExprType(S.Context));
  15095. E->setValueKind(Expr::getValueKindForType(DestType));
  15096. assert(E->getObjectKind() == OK_Ordinary);
  15097. // Rebuild the function type, replacing the result type with DestType.
  15098. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  15099. if (Proto) {
  15100. // __unknown_anytype(...) is a special case used by the debugger when
  15101. // it has no idea what a function's signature is.
  15102. //
  15103. // We want to build this call essentially under the K&R
  15104. // unprototyped rules, but making a FunctionNoProtoType in C++
  15105. // would foul up all sorts of assumptions. However, we cannot
  15106. // simply pass all arguments as variadic arguments, nor can we
  15107. // portably just call the function under a non-variadic type; see
  15108. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  15109. // However, it turns out that in practice it is generally safe to
  15110. // call a function declared as "A foo(B,C,D);" under the prototype
  15111. // "A foo(B,C,D,...);". The only known exception is with the
  15112. // Windows ABI, where any variadic function is implicitly cdecl
  15113. // regardless of its normal CC. Therefore we change the parameter
  15114. // types to match the types of the arguments.
  15115. //
  15116. // This is a hack, but it is far superior to moving the
  15117. // corresponding target-specific code from IR-gen to Sema/AST.
  15118. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  15119. SmallVector<QualType, 8> ArgTypes;
  15120. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  15121. ArgTypes.reserve(E->getNumArgs());
  15122. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  15123. Expr *Arg = E->getArg(i);
  15124. QualType ArgType = Arg->getType();
  15125. if (E->isLValue()) {
  15126. ArgType = S.Context.getLValueReferenceType(ArgType);
  15127. } else if (E->isXValue()) {
  15128. ArgType = S.Context.getRValueReferenceType(ArgType);
  15129. }
  15130. ArgTypes.push_back(ArgType);
  15131. }
  15132. ParamTypes = ArgTypes;
  15133. }
  15134. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  15135. Proto->getExtProtoInfo());
  15136. } else {
  15137. DestType = S.Context.getFunctionNoProtoType(DestType,
  15138. FnType->getExtInfo());
  15139. }
  15140. // Rebuild the appropriate pointer-to-function type.
  15141. switch (Kind) {
  15142. case FK_MemberFunction:
  15143. // Nothing to do.
  15144. break;
  15145. case FK_FunctionPointer:
  15146. DestType = S.Context.getPointerType(DestType);
  15147. break;
  15148. case FK_BlockPointer:
  15149. DestType = S.Context.getBlockPointerType(DestType);
  15150. break;
  15151. }
  15152. // Finally, we can recurse.
  15153. ExprResult CalleeResult = Visit(CalleeExpr);
  15154. if (!CalleeResult.isUsable()) return ExprError();
  15155. E->setCallee(CalleeResult.get());
  15156. // Bind a temporary if necessary.
  15157. return S.MaybeBindToTemporary(E);
  15158. }
  15159. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  15160. // Verify that this is a legal result type of a call.
  15161. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15162. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  15163. << DestType->isFunctionType() << DestType;
  15164. return ExprError();
  15165. }
  15166. // Rewrite the method result type if available.
  15167. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  15168. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  15169. Method->setReturnType(DestType);
  15170. }
  15171. // Change the type of the message.
  15172. E->setType(DestType.getNonReferenceType());
  15173. E->setValueKind(Expr::getValueKindForType(DestType));
  15174. return S.MaybeBindToTemporary(E);
  15175. }
  15176. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  15177. // The only case we should ever see here is a function-to-pointer decay.
  15178. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  15179. assert(E->getValueKind() == VK_RValue);
  15180. assert(E->getObjectKind() == OK_Ordinary);
  15181. E->setType(DestType);
  15182. // Rebuild the sub-expression as the pointee (function) type.
  15183. DestType = DestType->castAs<PointerType>()->getPointeeType();
  15184. ExprResult Result = Visit(E->getSubExpr());
  15185. if (!Result.isUsable()) return ExprError();
  15186. E->setSubExpr(Result.get());
  15187. return E;
  15188. } else if (E->getCastKind() == CK_LValueToRValue) {
  15189. assert(E->getValueKind() == VK_RValue);
  15190. assert(E->getObjectKind() == OK_Ordinary);
  15191. assert(isa<BlockPointerType>(E->getType()));
  15192. E->setType(DestType);
  15193. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  15194. DestType = S.Context.getLValueReferenceType(DestType);
  15195. ExprResult Result = Visit(E->getSubExpr());
  15196. if (!Result.isUsable()) return ExprError();
  15197. E->setSubExpr(Result.get());
  15198. return E;
  15199. } else {
  15200. llvm_unreachable("Unhandled cast type!");
  15201. }
  15202. }
  15203. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  15204. ExprValueKind ValueKind = VK_LValue;
  15205. QualType Type = DestType;
  15206. // We know how to make this work for certain kinds of decls:
  15207. // - functions
  15208. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  15209. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  15210. DestType = Ptr->getPointeeType();
  15211. ExprResult Result = resolveDecl(E, VD);
  15212. if (Result.isInvalid()) return ExprError();
  15213. return S.ImpCastExprToType(Result.get(), Type,
  15214. CK_FunctionToPointerDecay, VK_RValue);
  15215. }
  15216. if (!Type->isFunctionType()) {
  15217. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  15218. << VD << E->getSourceRange();
  15219. return ExprError();
  15220. }
  15221. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  15222. // We must match the FunctionDecl's type to the hack introduced in
  15223. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  15224. // type. See the lengthy commentary in that routine.
  15225. QualType FDT = FD->getType();
  15226. const FunctionType *FnType = FDT->castAs<FunctionType>();
  15227. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  15228. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  15229. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  15230. SourceLocation Loc = FD->getLocation();
  15231. FunctionDecl *NewFD = FunctionDecl::Create(
  15232. S.Context, FD->getDeclContext(), Loc, Loc,
  15233. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  15234. SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
  15235. /*ConstexprKind*/ CSK_unspecified);
  15236. if (FD->getQualifier())
  15237. NewFD->setQualifierInfo(FD->getQualifierLoc());
  15238. SmallVector<ParmVarDecl*, 16> Params;
  15239. for (const auto &AI : FT->param_types()) {
  15240. ParmVarDecl *Param =
  15241. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  15242. Param->setScopeInfo(0, Params.size());
  15243. Params.push_back(Param);
  15244. }
  15245. NewFD->setParams(Params);
  15246. DRE->setDecl(NewFD);
  15247. VD = DRE->getDecl();
  15248. }
  15249. }
  15250. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  15251. if (MD->isInstance()) {
  15252. ValueKind = VK_RValue;
  15253. Type = S.Context.BoundMemberTy;
  15254. }
  15255. // Function references aren't l-values in C.
  15256. if (!S.getLangOpts().CPlusPlus)
  15257. ValueKind = VK_RValue;
  15258. // - variables
  15259. } else if (isa<VarDecl>(VD)) {
  15260. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  15261. Type = RefTy->getPointeeType();
  15262. } else if (Type->isFunctionType()) {
  15263. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  15264. << VD << E->getSourceRange();
  15265. return ExprError();
  15266. }
  15267. // - nothing else
  15268. } else {
  15269. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  15270. << VD << E->getSourceRange();
  15271. return ExprError();
  15272. }
  15273. // Modifying the declaration like this is friendly to IR-gen but
  15274. // also really dangerous.
  15275. VD->setType(DestType);
  15276. E->setType(Type);
  15277. E->setValueKind(ValueKind);
  15278. return E;
  15279. }
  15280. /// Check a cast of an unknown-any type. We intentionally only
  15281. /// trigger this for C-style casts.
  15282. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  15283. Expr *CastExpr, CastKind &CastKind,
  15284. ExprValueKind &VK, CXXCastPath &Path) {
  15285. // The type we're casting to must be either void or complete.
  15286. if (!CastType->isVoidType() &&
  15287. RequireCompleteType(TypeRange.getBegin(), CastType,
  15288. diag::err_typecheck_cast_to_incomplete))
  15289. return ExprError();
  15290. // Rewrite the casted expression from scratch.
  15291. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  15292. if (!result.isUsable()) return ExprError();
  15293. CastExpr = result.get();
  15294. VK = CastExpr->getValueKind();
  15295. CastKind = CK_NoOp;
  15296. return CastExpr;
  15297. }
  15298. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  15299. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  15300. }
  15301. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  15302. Expr *arg, QualType &paramType) {
  15303. // If the syntactic form of the argument is not an explicit cast of
  15304. // any sort, just do default argument promotion.
  15305. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  15306. if (!castArg) {
  15307. ExprResult result = DefaultArgumentPromotion(arg);
  15308. if (result.isInvalid()) return ExprError();
  15309. paramType = result.get()->getType();
  15310. return result;
  15311. }
  15312. // Otherwise, use the type that was written in the explicit cast.
  15313. assert(!arg->hasPlaceholderType());
  15314. paramType = castArg->getTypeAsWritten();
  15315. // Copy-initialize a parameter of that type.
  15316. InitializedEntity entity =
  15317. InitializedEntity::InitializeParameter(Context, paramType,
  15318. /*consumed*/ false);
  15319. return PerformCopyInitialization(entity, callLoc, arg);
  15320. }
  15321. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  15322. Expr *orig = E;
  15323. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  15324. while (true) {
  15325. E = E->IgnoreParenImpCasts();
  15326. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  15327. E = call->getCallee();
  15328. diagID = diag::err_uncasted_call_of_unknown_any;
  15329. } else {
  15330. break;
  15331. }
  15332. }
  15333. SourceLocation loc;
  15334. NamedDecl *d;
  15335. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  15336. loc = ref->getLocation();
  15337. d = ref->getDecl();
  15338. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  15339. loc = mem->getMemberLoc();
  15340. d = mem->getMemberDecl();
  15341. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  15342. diagID = diag::err_uncasted_call_of_unknown_any;
  15343. loc = msg->getSelectorStartLoc();
  15344. d = msg->getMethodDecl();
  15345. if (!d) {
  15346. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  15347. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  15348. << orig->getSourceRange();
  15349. return ExprError();
  15350. }
  15351. } else {
  15352. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15353. << E->getSourceRange();
  15354. return ExprError();
  15355. }
  15356. S.Diag(loc, diagID) << d << orig->getSourceRange();
  15357. // Never recoverable.
  15358. return ExprError();
  15359. }
  15360. /// Check for operands with placeholder types and complain if found.
  15361. /// Returns ExprError() if there was an error and no recovery was possible.
  15362. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  15363. if (!getLangOpts().CPlusPlus) {
  15364. // C cannot handle TypoExpr nodes on either side of a binop because it
  15365. // doesn't handle dependent types properly, so make sure any TypoExprs have
  15366. // been dealt with before checking the operands.
  15367. ExprResult Result = CorrectDelayedTyposInExpr(E);
  15368. if (!Result.isUsable()) return ExprError();
  15369. E = Result.get();
  15370. }
  15371. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  15372. if (!placeholderType) return E;
  15373. switch (placeholderType->getKind()) {
  15374. // Overloaded expressions.
  15375. case BuiltinType::Overload: {
  15376. // Try to resolve a single function template specialization.
  15377. // This is obligatory.
  15378. ExprResult Result = E;
  15379. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  15380. return Result;
  15381. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  15382. // leaves Result unchanged on failure.
  15383. Result = E;
  15384. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  15385. return Result;
  15386. // If that failed, try to recover with a call.
  15387. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  15388. /*complain*/ true);
  15389. return Result;
  15390. }
  15391. // Bound member functions.
  15392. case BuiltinType::BoundMember: {
  15393. ExprResult result = E;
  15394. const Expr *BME = E->IgnoreParens();
  15395. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  15396. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  15397. if (isa<CXXPseudoDestructorExpr>(BME)) {
  15398. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  15399. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  15400. if (ME->getMemberNameInfo().getName().getNameKind() ==
  15401. DeclarationName::CXXDestructorName)
  15402. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  15403. }
  15404. tryToRecoverWithCall(result, PD,
  15405. /*complain*/ true);
  15406. return result;
  15407. }
  15408. // ARC unbridged casts.
  15409. case BuiltinType::ARCUnbridgedCast: {
  15410. Expr *realCast = stripARCUnbridgedCast(E);
  15411. diagnoseARCUnbridgedCast(realCast);
  15412. return realCast;
  15413. }
  15414. // Expressions of unknown type.
  15415. case BuiltinType::UnknownAny:
  15416. return diagnoseUnknownAnyExpr(*this, E);
  15417. // Pseudo-objects.
  15418. case BuiltinType::PseudoObject:
  15419. return checkPseudoObjectRValue(E);
  15420. case BuiltinType::BuiltinFn: {
  15421. // Accept __noop without parens by implicitly converting it to a call expr.
  15422. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  15423. if (DRE) {
  15424. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  15425. if (FD->getBuiltinID() == Builtin::BI__noop) {
  15426. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  15427. CK_BuiltinFnToFnPtr)
  15428. .get();
  15429. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  15430. VK_RValue, SourceLocation());
  15431. }
  15432. }
  15433. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  15434. return ExprError();
  15435. }
  15436. // Expressions of unknown type.
  15437. case BuiltinType::OMPArraySection:
  15438. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15439. return ExprError();
  15440. // Everything else should be impossible.
  15441. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15442. case BuiltinType::Id:
  15443. #include "clang/Basic/OpenCLImageTypes.def"
  15444. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15445. case BuiltinType::Id:
  15446. #include "clang/Basic/OpenCLExtensionTypes.def"
  15447. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15448. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15449. #include "clang/AST/BuiltinTypes.def"
  15450. break;
  15451. }
  15452. llvm_unreachable("invalid placeholder type!");
  15453. }
  15454. bool Sema::CheckCaseExpression(Expr *E) {
  15455. if (E->isTypeDependent())
  15456. return true;
  15457. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15458. return E->getType()->isIntegralOrEnumerationType();
  15459. return false;
  15460. }
  15461. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15462. ExprResult
  15463. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15464. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15465. "Unknown Objective-C Boolean value!");
  15466. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15467. if (!Context.getBOOLDecl()) {
  15468. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15469. Sema::LookupOrdinaryName);
  15470. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15471. NamedDecl *ND = Result.getFoundDecl();
  15472. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15473. Context.setBOOLDecl(TD);
  15474. }
  15475. }
  15476. if (Context.getBOOLDecl())
  15477. BoolT = Context.getBOOLType();
  15478. return new (Context)
  15479. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15480. }
  15481. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15482. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15483. SourceLocation RParen) {
  15484. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15485. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15486. return Spec.getPlatform() == Platform;
  15487. });
  15488. VersionTuple Version;
  15489. if (Spec != AvailSpecs.end())
  15490. Version = Spec->getVersion();
  15491. // The use of `@available` in the enclosing function should be analyzed to
  15492. // warn when it's used inappropriately (i.e. not if(@available)).
  15493. if (getCurFunctionOrMethodDecl())
  15494. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15495. else if (getCurBlock() || getCurLambda())
  15496. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15497. return new (Context)
  15498. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15499. }