SemaExprCXX.cpp 320 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059
  1. //===--- SemaExprCXX.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. /// \file
  10. /// Implements semantic analysis for C++ expressions.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TreeTransform.h"
  15. #include "TypeLocBuilder.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/TypeLoc.h"
  25. #include "clang/Basic/AlignedAllocation.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/DeclSpec.h"
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/ParsedTemplate.h"
  33. #include "clang/Sema/Scope.h"
  34. #include "clang/Sema/ScopeInfo.h"
  35. #include "clang/Sema/SemaLambda.h"
  36. #include "clang/Sema/TemplateDeduction.h"
  37. #include "llvm/ADT/APInt.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. using namespace clang;
  41. using namespace sema;
  42. /// Handle the result of the special case name lookup for inheriting
  43. /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
  44. /// constructor names in member using declarations, even if 'X' is not the
  45. /// name of the corresponding type.
  46. ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
  47. SourceLocation NameLoc,
  48. IdentifierInfo &Name) {
  49. NestedNameSpecifier *NNS = SS.getScopeRep();
  50. // Convert the nested-name-specifier into a type.
  51. QualType Type;
  52. switch (NNS->getKind()) {
  53. case NestedNameSpecifier::TypeSpec:
  54. case NestedNameSpecifier::TypeSpecWithTemplate:
  55. Type = QualType(NNS->getAsType(), 0);
  56. break;
  57. case NestedNameSpecifier::Identifier:
  58. // Strip off the last layer of the nested-name-specifier and build a
  59. // typename type for it.
  60. assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
  61. Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
  62. NNS->getAsIdentifier());
  63. break;
  64. case NestedNameSpecifier::Global:
  65. case NestedNameSpecifier::Super:
  66. case NestedNameSpecifier::Namespace:
  67. case NestedNameSpecifier::NamespaceAlias:
  68. llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
  69. }
  70. // This reference to the type is located entirely at the location of the
  71. // final identifier in the qualified-id.
  72. return CreateParsedType(Type,
  73. Context.getTrivialTypeSourceInfo(Type, NameLoc));
  74. }
  75. ParsedType Sema::getConstructorName(IdentifierInfo &II,
  76. SourceLocation NameLoc,
  77. Scope *S, CXXScopeSpec &SS,
  78. bool EnteringContext) {
  79. CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
  80. assert(CurClass && &II == CurClass->getIdentifier() &&
  81. "not a constructor name");
  82. // When naming a constructor as a member of a dependent context (eg, in a
  83. // friend declaration or an inherited constructor declaration), form an
  84. // unresolved "typename" type.
  85. if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
  86. QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
  87. return ParsedType::make(T);
  88. }
  89. if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
  90. return ParsedType();
  91. // Find the injected-class-name declaration. Note that we make no attempt to
  92. // diagnose cases where the injected-class-name is shadowed: the only
  93. // declaration that can validly shadow the injected-class-name is a
  94. // non-static data member, and if the class contains both a non-static data
  95. // member and a constructor then it is ill-formed (we check that in
  96. // CheckCompletedCXXClass).
  97. CXXRecordDecl *InjectedClassName = nullptr;
  98. for (NamedDecl *ND : CurClass->lookup(&II)) {
  99. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  100. if (RD && RD->isInjectedClassName()) {
  101. InjectedClassName = RD;
  102. break;
  103. }
  104. }
  105. if (!InjectedClassName) {
  106. if (!CurClass->isInvalidDecl()) {
  107. // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
  108. // properly. Work around it here for now.
  109. Diag(SS.getLastQualifierNameLoc(),
  110. diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
  111. }
  112. return ParsedType();
  113. }
  114. QualType T = Context.getTypeDeclType(InjectedClassName);
  115. DiagnoseUseOfDecl(InjectedClassName, NameLoc);
  116. MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
  117. return ParsedType::make(T);
  118. }
  119. ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
  120. IdentifierInfo &II,
  121. SourceLocation NameLoc,
  122. Scope *S, CXXScopeSpec &SS,
  123. ParsedType ObjectTypePtr,
  124. bool EnteringContext) {
  125. // Determine where to perform name lookup.
  126. // FIXME: This area of the standard is very messy, and the current
  127. // wording is rather unclear about which scopes we search for the
  128. // destructor name; see core issues 399 and 555. Issue 399 in
  129. // particular shows where the current description of destructor name
  130. // lookup is completely out of line with existing practice, e.g.,
  131. // this appears to be ill-formed:
  132. //
  133. // namespace N {
  134. // template <typename T> struct S {
  135. // ~S();
  136. // };
  137. // }
  138. //
  139. // void f(N::S<int>* s) {
  140. // s->N::S<int>::~S();
  141. // }
  142. //
  143. // See also PR6358 and PR6359.
  144. // For this reason, we're currently only doing the C++03 version of this
  145. // code; the C++0x version has to wait until we get a proper spec.
  146. QualType SearchType;
  147. DeclContext *LookupCtx = nullptr;
  148. bool isDependent = false;
  149. bool LookInScope = false;
  150. if (SS.isInvalid())
  151. return nullptr;
  152. // If we have an object type, it's because we are in a
  153. // pseudo-destructor-expression or a member access expression, and
  154. // we know what type we're looking for.
  155. if (ObjectTypePtr)
  156. SearchType = GetTypeFromParser(ObjectTypePtr);
  157. if (SS.isSet()) {
  158. NestedNameSpecifier *NNS = SS.getScopeRep();
  159. bool AlreadySearched = false;
  160. bool LookAtPrefix = true;
  161. // C++11 [basic.lookup.qual]p6:
  162. // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
  163. // the type-names are looked up as types in the scope designated by the
  164. // nested-name-specifier. Similarly, in a qualified-id of the form:
  165. //
  166. // nested-name-specifier[opt] class-name :: ~ class-name
  167. //
  168. // the second class-name is looked up in the same scope as the first.
  169. //
  170. // Here, we determine whether the code below is permitted to look at the
  171. // prefix of the nested-name-specifier.
  172. DeclContext *DC = computeDeclContext(SS, EnteringContext);
  173. if (DC && DC->isFileContext()) {
  174. AlreadySearched = true;
  175. LookupCtx = DC;
  176. isDependent = false;
  177. } else if (DC && isa<CXXRecordDecl>(DC)) {
  178. LookAtPrefix = false;
  179. LookInScope = true;
  180. }
  181. // The second case from the C++03 rules quoted further above.
  182. NestedNameSpecifier *Prefix = nullptr;
  183. if (AlreadySearched) {
  184. // Nothing left to do.
  185. } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
  186. CXXScopeSpec PrefixSS;
  187. PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
  188. LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
  189. isDependent = isDependentScopeSpecifier(PrefixSS);
  190. } else if (ObjectTypePtr) {
  191. LookupCtx = computeDeclContext(SearchType);
  192. isDependent = SearchType->isDependentType();
  193. } else {
  194. LookupCtx = computeDeclContext(SS, EnteringContext);
  195. isDependent = LookupCtx && LookupCtx->isDependentContext();
  196. }
  197. } else if (ObjectTypePtr) {
  198. // C++ [basic.lookup.classref]p3:
  199. // If the unqualified-id is ~type-name, the type-name is looked up
  200. // in the context of the entire postfix-expression. If the type T
  201. // of the object expression is of a class type C, the type-name is
  202. // also looked up in the scope of class C. At least one of the
  203. // lookups shall find a name that refers to (possibly
  204. // cv-qualified) T.
  205. LookupCtx = computeDeclContext(SearchType);
  206. isDependent = SearchType->isDependentType();
  207. assert((isDependent || !SearchType->isIncompleteType()) &&
  208. "Caller should have completed object type");
  209. LookInScope = true;
  210. } else {
  211. // Perform lookup into the current scope (only).
  212. LookInScope = true;
  213. }
  214. TypeDecl *NonMatchingTypeDecl = nullptr;
  215. LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
  216. for (unsigned Step = 0; Step != 2; ++Step) {
  217. // Look for the name first in the computed lookup context (if we
  218. // have one) and, if that fails to find a match, in the scope (if
  219. // we're allowed to look there).
  220. Found.clear();
  221. if (Step == 0 && LookupCtx) {
  222. if (RequireCompleteDeclContext(SS, LookupCtx))
  223. return nullptr;
  224. LookupQualifiedName(Found, LookupCtx);
  225. } else if (Step == 1 && LookInScope && S) {
  226. LookupName(Found, S);
  227. } else {
  228. continue;
  229. }
  230. // FIXME: Should we be suppressing ambiguities here?
  231. if (Found.isAmbiguous())
  232. return nullptr;
  233. if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
  234. QualType T = Context.getTypeDeclType(Type);
  235. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  236. if (SearchType.isNull() || SearchType->isDependentType() ||
  237. Context.hasSameUnqualifiedType(T, SearchType)) {
  238. // We found our type!
  239. return CreateParsedType(T,
  240. Context.getTrivialTypeSourceInfo(T, NameLoc));
  241. }
  242. if (!SearchType.isNull())
  243. NonMatchingTypeDecl = Type;
  244. }
  245. // If the name that we found is a class template name, and it is
  246. // the same name as the template name in the last part of the
  247. // nested-name-specifier (if present) or the object type, then
  248. // this is the destructor for that class.
  249. // FIXME: This is a workaround until we get real drafting for core
  250. // issue 399, for which there isn't even an obvious direction.
  251. if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
  252. QualType MemberOfType;
  253. if (SS.isSet()) {
  254. if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
  255. // Figure out the type of the context, if it has one.
  256. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
  257. MemberOfType = Context.getTypeDeclType(Record);
  258. }
  259. }
  260. if (MemberOfType.isNull())
  261. MemberOfType = SearchType;
  262. if (MemberOfType.isNull())
  263. continue;
  264. // We're referring into a class template specialization. If the
  265. // class template we found is the same as the template being
  266. // specialized, we found what we are looking for.
  267. if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
  268. if (ClassTemplateSpecializationDecl *Spec
  269. = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
  270. if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
  271. Template->getCanonicalDecl())
  272. return CreateParsedType(
  273. MemberOfType,
  274. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  275. }
  276. continue;
  277. }
  278. // We're referring to an unresolved class template
  279. // specialization. Determine whether we class template we found
  280. // is the same as the template being specialized or, if we don't
  281. // know which template is being specialized, that it at least
  282. // has the same name.
  283. if (const TemplateSpecializationType *SpecType
  284. = MemberOfType->getAs<TemplateSpecializationType>()) {
  285. TemplateName SpecName = SpecType->getTemplateName();
  286. // The class template we found is the same template being
  287. // specialized.
  288. if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
  289. if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
  290. return CreateParsedType(
  291. MemberOfType,
  292. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  293. continue;
  294. }
  295. // The class template we found has the same name as the
  296. // (dependent) template name being specialized.
  297. if (DependentTemplateName *DepTemplate
  298. = SpecName.getAsDependentTemplateName()) {
  299. if (DepTemplate->isIdentifier() &&
  300. DepTemplate->getIdentifier() == Template->getIdentifier())
  301. return CreateParsedType(
  302. MemberOfType,
  303. Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
  304. continue;
  305. }
  306. }
  307. }
  308. }
  309. if (isDependent) {
  310. // We didn't find our type, but that's okay: it's dependent
  311. // anyway.
  312. // FIXME: What if we have no nested-name-specifier?
  313. QualType T = CheckTypenameType(ETK_None, SourceLocation(),
  314. SS.getWithLocInContext(Context),
  315. II, NameLoc);
  316. return ParsedType::make(T);
  317. }
  318. if (NonMatchingTypeDecl) {
  319. QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
  320. Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
  321. << T << SearchType;
  322. Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
  323. << T;
  324. } else if (ObjectTypePtr)
  325. Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
  326. << &II;
  327. else {
  328. SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
  329. diag::err_destructor_class_name);
  330. if (S) {
  331. const DeclContext *Ctx = S->getEntity();
  332. if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
  333. DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
  334. Class->getNameAsString());
  335. }
  336. }
  337. return nullptr;
  338. }
  339. ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
  340. ParsedType ObjectType) {
  341. if (DS.getTypeSpecType() == DeclSpec::TST_error)
  342. return nullptr;
  343. if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
  344. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  345. return nullptr;
  346. }
  347. assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
  348. "unexpected type in getDestructorType");
  349. QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  350. // If we know the type of the object, check that the correct destructor
  351. // type was named now; we can give better diagnostics this way.
  352. QualType SearchType = GetTypeFromParser(ObjectType);
  353. if (!SearchType.isNull() && !SearchType->isDependentType() &&
  354. !Context.hasSameUnqualifiedType(T, SearchType)) {
  355. Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
  356. << T << SearchType;
  357. return nullptr;
  358. }
  359. return ParsedType::make(T);
  360. }
  361. bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
  362. const UnqualifiedId &Name) {
  363. assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
  364. if (!SS.isValid())
  365. return false;
  366. switch (SS.getScopeRep()->getKind()) {
  367. case NestedNameSpecifier::Identifier:
  368. case NestedNameSpecifier::TypeSpec:
  369. case NestedNameSpecifier::TypeSpecWithTemplate:
  370. // Per C++11 [over.literal]p2, literal operators can only be declared at
  371. // namespace scope. Therefore, this unqualified-id cannot name anything.
  372. // Reject it early, because we have no AST representation for this in the
  373. // case where the scope is dependent.
  374. Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
  375. << SS.getScopeRep();
  376. return true;
  377. case NestedNameSpecifier::Global:
  378. case NestedNameSpecifier::Super:
  379. case NestedNameSpecifier::Namespace:
  380. case NestedNameSpecifier::NamespaceAlias:
  381. return false;
  382. }
  383. llvm_unreachable("unknown nested name specifier kind");
  384. }
  385. /// Build a C++ typeid expression with a type operand.
  386. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  387. SourceLocation TypeidLoc,
  388. TypeSourceInfo *Operand,
  389. SourceLocation RParenLoc) {
  390. // C++ [expr.typeid]p4:
  391. // The top-level cv-qualifiers of the lvalue expression or the type-id
  392. // that is the operand of typeid are always ignored.
  393. // If the type of the type-id is a class type or a reference to a class
  394. // type, the class shall be completely-defined.
  395. Qualifiers Quals;
  396. QualType T
  397. = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
  398. Quals);
  399. if (T->getAs<RecordType>() &&
  400. RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  401. return ExprError();
  402. if (T->isVariablyModifiedType())
  403. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
  404. if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
  405. return ExprError();
  406. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
  407. SourceRange(TypeidLoc, RParenLoc));
  408. }
  409. /// Build a C++ typeid expression with an expression operand.
  410. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
  411. SourceLocation TypeidLoc,
  412. Expr *E,
  413. SourceLocation RParenLoc) {
  414. bool WasEvaluated = false;
  415. if (E && !E->isTypeDependent()) {
  416. if (E->getType()->isPlaceholderType()) {
  417. ExprResult result = CheckPlaceholderExpr(E);
  418. if (result.isInvalid()) return ExprError();
  419. E = result.get();
  420. }
  421. QualType T = E->getType();
  422. if (const RecordType *RecordT = T->getAs<RecordType>()) {
  423. CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
  424. // C++ [expr.typeid]p3:
  425. // [...] If the type of the expression is a class type, the class
  426. // shall be completely-defined.
  427. if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
  428. return ExprError();
  429. // C++ [expr.typeid]p3:
  430. // When typeid is applied to an expression other than an glvalue of a
  431. // polymorphic class type [...] [the] expression is an unevaluated
  432. // operand. [...]
  433. if (RecordD->isPolymorphic() && E->isGLValue()) {
  434. // The subexpression is potentially evaluated; switch the context
  435. // and recheck the subexpression.
  436. ExprResult Result = TransformToPotentiallyEvaluated(E);
  437. if (Result.isInvalid()) return ExprError();
  438. E = Result.get();
  439. // We require a vtable to query the type at run time.
  440. MarkVTableUsed(TypeidLoc, RecordD);
  441. WasEvaluated = true;
  442. }
  443. }
  444. // C++ [expr.typeid]p4:
  445. // [...] If the type of the type-id is a reference to a possibly
  446. // cv-qualified type, the result of the typeid expression refers to a
  447. // std::type_info object representing the cv-unqualified referenced
  448. // type.
  449. Qualifiers Quals;
  450. QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
  451. if (!Context.hasSameType(T, UnqualT)) {
  452. T = UnqualT;
  453. E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
  454. }
  455. }
  456. if (E->getType()->isVariablyModifiedType())
  457. return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
  458. << E->getType());
  459. else if (!inTemplateInstantiation() &&
  460. E->HasSideEffects(Context, WasEvaluated)) {
  461. // The expression operand for typeid is in an unevaluated expression
  462. // context, so side effects could result in unintended consequences.
  463. Diag(E->getExprLoc(), WasEvaluated
  464. ? diag::warn_side_effects_typeid
  465. : diag::warn_side_effects_unevaluated_context);
  466. }
  467. return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
  468. SourceRange(TypeidLoc, RParenLoc));
  469. }
  470. /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
  471. ExprResult
  472. Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
  473. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  474. // typeid is not supported in OpenCL.
  475. if (getLangOpts().OpenCLCPlusPlus) {
  476. return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
  477. << "typeid");
  478. }
  479. // Find the std::type_info type.
  480. if (!getStdNamespace())
  481. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  482. if (!CXXTypeInfoDecl) {
  483. IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
  484. LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
  485. LookupQualifiedName(R, getStdNamespace());
  486. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  487. // Microsoft's typeinfo doesn't have type_info in std but in the global
  488. // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
  489. if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
  490. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  491. CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
  492. }
  493. if (!CXXTypeInfoDecl)
  494. return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  495. }
  496. if (!getLangOpts().RTTI) {
  497. return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
  498. }
  499. QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
  500. if (isType) {
  501. // The operand is a type; handle it as such.
  502. TypeSourceInfo *TInfo = nullptr;
  503. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  504. &TInfo);
  505. if (T.isNull())
  506. return ExprError();
  507. if (!TInfo)
  508. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  509. return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
  510. }
  511. // The operand is an expression.
  512. return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
  513. }
  514. /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
  515. /// a single GUID.
  516. static void
  517. getUuidAttrOfType(Sema &SemaRef, QualType QT,
  518. llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
  519. // Optionally remove one level of pointer, reference or array indirection.
  520. const Type *Ty = QT.getTypePtr();
  521. if (QT->isPointerType() || QT->isReferenceType())
  522. Ty = QT->getPointeeType().getTypePtr();
  523. else if (QT->isArrayType())
  524. Ty = Ty->getBaseElementTypeUnsafe();
  525. const auto *TD = Ty->getAsTagDecl();
  526. if (!TD)
  527. return;
  528. if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
  529. UuidAttrs.insert(Uuid);
  530. return;
  531. }
  532. // __uuidof can grab UUIDs from template arguments.
  533. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
  534. const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
  535. for (const TemplateArgument &TA : TAL.asArray()) {
  536. const UuidAttr *UuidForTA = nullptr;
  537. if (TA.getKind() == TemplateArgument::Type)
  538. getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
  539. else if (TA.getKind() == TemplateArgument::Declaration)
  540. getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
  541. if (UuidForTA)
  542. UuidAttrs.insert(UuidForTA);
  543. }
  544. }
  545. }
  546. /// Build a Microsoft __uuidof expression with a type operand.
  547. ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
  548. SourceLocation TypeidLoc,
  549. TypeSourceInfo *Operand,
  550. SourceLocation RParenLoc) {
  551. StringRef UuidStr;
  552. if (!Operand->getType()->isDependentType()) {
  553. llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
  554. getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
  555. if (UuidAttrs.empty())
  556. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  557. if (UuidAttrs.size() > 1)
  558. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  559. UuidStr = UuidAttrs.back()->getGuid();
  560. }
  561. return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
  562. SourceRange(TypeidLoc, RParenLoc));
  563. }
  564. /// Build a Microsoft __uuidof expression with an expression operand.
  565. ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
  566. SourceLocation TypeidLoc,
  567. Expr *E,
  568. SourceLocation RParenLoc) {
  569. StringRef UuidStr;
  570. if (!E->getType()->isDependentType()) {
  571. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  572. UuidStr = "00000000-0000-0000-0000-000000000000";
  573. } else {
  574. llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
  575. getUuidAttrOfType(*this, E->getType(), UuidAttrs);
  576. if (UuidAttrs.empty())
  577. return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
  578. if (UuidAttrs.size() > 1)
  579. return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
  580. UuidStr = UuidAttrs.back()->getGuid();
  581. }
  582. }
  583. return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
  584. SourceRange(TypeidLoc, RParenLoc));
  585. }
  586. /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
  587. ExprResult
  588. Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
  589. bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
  590. // If MSVCGuidDecl has not been cached, do the lookup.
  591. if (!MSVCGuidDecl) {
  592. IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
  593. LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
  594. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  595. MSVCGuidDecl = R.getAsSingle<RecordDecl>();
  596. if (!MSVCGuidDecl)
  597. return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
  598. }
  599. QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
  600. if (isType) {
  601. // The operand is a type; handle it as such.
  602. TypeSourceInfo *TInfo = nullptr;
  603. QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
  604. &TInfo);
  605. if (T.isNull())
  606. return ExprError();
  607. if (!TInfo)
  608. TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
  609. return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
  610. }
  611. // The operand is an expression.
  612. return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
  613. }
  614. /// ActOnCXXBoolLiteral - Parse {true,false} literals.
  615. ExprResult
  616. Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  617. assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
  618. "Unknown C++ Boolean value!");
  619. return new (Context)
  620. CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
  621. }
  622. /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
  623. ExprResult
  624. Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
  625. return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  626. }
  627. /// ActOnCXXThrow - Parse throw expressions.
  628. ExprResult
  629. Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
  630. bool IsThrownVarInScope = false;
  631. if (Ex) {
  632. // C++0x [class.copymove]p31:
  633. // When certain criteria are met, an implementation is allowed to omit the
  634. // copy/move construction of a class object [...]
  635. //
  636. // - in a throw-expression, when the operand is the name of a
  637. // non-volatile automatic object (other than a function or catch-
  638. // clause parameter) whose scope does not extend beyond the end of the
  639. // innermost enclosing try-block (if there is one), the copy/move
  640. // operation from the operand to the exception object (15.1) can be
  641. // omitted by constructing the automatic object directly into the
  642. // exception object
  643. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
  644. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  645. if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
  646. for( ; S; S = S->getParent()) {
  647. if (S->isDeclScope(Var)) {
  648. IsThrownVarInScope = true;
  649. break;
  650. }
  651. if (S->getFlags() &
  652. (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
  653. Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
  654. Scope::TryScope))
  655. break;
  656. }
  657. }
  658. }
  659. }
  660. return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
  661. }
  662. ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
  663. bool IsThrownVarInScope) {
  664. // Don't report an error if 'throw' is used in system headers.
  665. if (!getLangOpts().CXXExceptions &&
  666. !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
  667. // Delay error emission for the OpenMP device code.
  668. targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
  669. }
  670. // Exceptions aren't allowed in CUDA device code.
  671. if (getLangOpts().CUDA)
  672. CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
  673. << "throw" << CurrentCUDATarget();
  674. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  675. Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
  676. if (Ex && !Ex->isTypeDependent()) {
  677. QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
  678. if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
  679. return ExprError();
  680. // Initialize the exception result. This implicitly weeds out
  681. // abstract types or types with inaccessible copy constructors.
  682. // C++0x [class.copymove]p31:
  683. // When certain criteria are met, an implementation is allowed to omit the
  684. // copy/move construction of a class object [...]
  685. //
  686. // - in a throw-expression, when the operand is the name of a
  687. // non-volatile automatic object (other than a function or
  688. // catch-clause
  689. // parameter) whose scope does not extend beyond the end of the
  690. // innermost enclosing try-block (if there is one), the copy/move
  691. // operation from the operand to the exception object (15.1) can be
  692. // omitted by constructing the automatic object directly into the
  693. // exception object
  694. const VarDecl *NRVOVariable = nullptr;
  695. if (IsThrownVarInScope)
  696. NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
  697. InitializedEntity Entity = InitializedEntity::InitializeException(
  698. OpLoc, ExceptionObjectTy,
  699. /*NRVO=*/NRVOVariable != nullptr);
  700. ExprResult Res = PerformMoveOrCopyInitialization(
  701. Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
  702. if (Res.isInvalid())
  703. return ExprError();
  704. Ex = Res.get();
  705. }
  706. return new (Context)
  707. CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
  708. }
  709. static void
  710. collectPublicBases(CXXRecordDecl *RD,
  711. llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
  712. llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
  713. llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
  714. bool ParentIsPublic) {
  715. for (const CXXBaseSpecifier &BS : RD->bases()) {
  716. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  717. bool NewSubobject;
  718. // Virtual bases constitute the same subobject. Non-virtual bases are
  719. // always distinct subobjects.
  720. if (BS.isVirtual())
  721. NewSubobject = VBases.insert(BaseDecl).second;
  722. else
  723. NewSubobject = true;
  724. if (NewSubobject)
  725. ++SubobjectsSeen[BaseDecl];
  726. // Only add subobjects which have public access throughout the entire chain.
  727. bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
  728. if (PublicPath)
  729. PublicSubobjectsSeen.insert(BaseDecl);
  730. // Recurse on to each base subobject.
  731. collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  732. PublicPath);
  733. }
  734. }
  735. static void getUnambiguousPublicSubobjects(
  736. CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
  737. llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
  738. llvm::SmallSet<CXXRecordDecl *, 2> VBases;
  739. llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
  740. SubobjectsSeen[RD] = 1;
  741. PublicSubobjectsSeen.insert(RD);
  742. collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
  743. /*ParentIsPublic=*/true);
  744. for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
  745. // Skip ambiguous objects.
  746. if (SubobjectsSeen[PublicSubobject] > 1)
  747. continue;
  748. Objects.push_back(PublicSubobject);
  749. }
  750. }
  751. /// CheckCXXThrowOperand - Validate the operand of a throw.
  752. bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
  753. QualType ExceptionObjectTy, Expr *E) {
  754. // If the type of the exception would be an incomplete type or a pointer
  755. // to an incomplete type other than (cv) void the program is ill-formed.
  756. QualType Ty = ExceptionObjectTy;
  757. bool isPointer = false;
  758. if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
  759. Ty = Ptr->getPointeeType();
  760. isPointer = true;
  761. }
  762. if (!isPointer || !Ty->isVoidType()) {
  763. if (RequireCompleteType(ThrowLoc, Ty,
  764. isPointer ? diag::err_throw_incomplete_ptr
  765. : diag::err_throw_incomplete,
  766. E->getSourceRange()))
  767. return true;
  768. if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
  769. diag::err_throw_abstract_type, E))
  770. return true;
  771. }
  772. // If the exception has class type, we need additional handling.
  773. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  774. if (!RD)
  775. return false;
  776. // If we are throwing a polymorphic class type or pointer thereof,
  777. // exception handling will make use of the vtable.
  778. MarkVTableUsed(ThrowLoc, RD);
  779. // If a pointer is thrown, the referenced object will not be destroyed.
  780. if (isPointer)
  781. return false;
  782. // If the class has a destructor, we must be able to call it.
  783. if (!RD->hasIrrelevantDestructor()) {
  784. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  785. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  786. CheckDestructorAccess(E->getExprLoc(), Destructor,
  787. PDiag(diag::err_access_dtor_exception) << Ty);
  788. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  789. return true;
  790. }
  791. }
  792. // The MSVC ABI creates a list of all types which can catch the exception
  793. // object. This list also references the appropriate copy constructor to call
  794. // if the object is caught by value and has a non-trivial copy constructor.
  795. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  796. // We are only interested in the public, unambiguous bases contained within
  797. // the exception object. Bases which are ambiguous or otherwise
  798. // inaccessible are not catchable types.
  799. llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
  800. getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
  801. for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
  802. // Attempt to lookup the copy constructor. Various pieces of machinery
  803. // will spring into action, like template instantiation, which means this
  804. // cannot be a simple walk of the class's decls. Instead, we must perform
  805. // lookup and overload resolution.
  806. CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
  807. if (!CD)
  808. continue;
  809. // Mark the constructor referenced as it is used by this throw expression.
  810. MarkFunctionReferenced(E->getExprLoc(), CD);
  811. // Skip this copy constructor if it is trivial, we don't need to record it
  812. // in the catchable type data.
  813. if (CD->isTrivial())
  814. continue;
  815. // The copy constructor is non-trivial, create a mapping from this class
  816. // type to this constructor.
  817. // N.B. The selection of copy constructor is not sensitive to this
  818. // particular throw-site. Lookup will be performed at the catch-site to
  819. // ensure that the copy constructor is, in fact, accessible (via
  820. // friendship or any other means).
  821. Context.addCopyConstructorForExceptionObject(Subobject, CD);
  822. // We don't keep the instantiated default argument expressions around so
  823. // we must rebuild them here.
  824. for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
  825. if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
  826. return true;
  827. }
  828. }
  829. }
  830. // Under the Itanium C++ ABI, memory for the exception object is allocated by
  831. // the runtime with no ability for the compiler to request additional
  832. // alignment. Warn if the exception type requires alignment beyond the minimum
  833. // guaranteed by the target C++ runtime.
  834. if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
  835. CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
  836. CharUnits ExnObjAlign = Context.getExnObjectAlignment();
  837. if (ExnObjAlign < TypeAlign) {
  838. Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
  839. Diag(ThrowLoc, diag::note_throw_underaligned_obj)
  840. << Ty << (unsigned)TypeAlign.getQuantity()
  841. << (unsigned)ExnObjAlign.getQuantity();
  842. }
  843. }
  844. return false;
  845. }
  846. static QualType adjustCVQualifiersForCXXThisWithinLambda(
  847. ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
  848. DeclContext *CurSemaContext, ASTContext &ASTCtx) {
  849. QualType ClassType = ThisTy->getPointeeType();
  850. LambdaScopeInfo *CurLSI = nullptr;
  851. DeclContext *CurDC = CurSemaContext;
  852. // Iterate through the stack of lambdas starting from the innermost lambda to
  853. // the outermost lambda, checking if '*this' is ever captured by copy - since
  854. // that could change the cv-qualifiers of the '*this' object.
  855. // The object referred to by '*this' starts out with the cv-qualifiers of its
  856. // member function. We then start with the innermost lambda and iterate
  857. // outward checking to see if any lambda performs a by-copy capture of '*this'
  858. // - and if so, any nested lambda must respect the 'constness' of that
  859. // capturing lamdbda's call operator.
  860. //
  861. // Since the FunctionScopeInfo stack is representative of the lexical
  862. // nesting of the lambda expressions during initial parsing (and is the best
  863. // place for querying information about captures about lambdas that are
  864. // partially processed) and perhaps during instantiation of function templates
  865. // that contain lambda expressions that need to be transformed BUT not
  866. // necessarily during instantiation of a nested generic lambda's function call
  867. // operator (which might even be instantiated at the end of the TU) - at which
  868. // time the DeclContext tree is mature enough to query capture information
  869. // reliably - we use a two pronged approach to walk through all the lexically
  870. // enclosing lambda expressions:
  871. //
  872. // 1) Climb down the FunctionScopeInfo stack as long as each item represents
  873. // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
  874. // enclosed by the call-operator of the LSI below it on the stack (while
  875. // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
  876. // the stack represents the innermost lambda.
  877. //
  878. // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
  879. // represents a lambda's call operator. If it does, we must be instantiating
  880. // a generic lambda's call operator (represented by the Current LSI, and
  881. // should be the only scenario where an inconsistency between the LSI and the
  882. // DeclContext should occur), so climb out the DeclContexts if they
  883. // represent lambdas, while querying the corresponding closure types
  884. // regarding capture information.
  885. // 1) Climb down the function scope info stack.
  886. for (int I = FunctionScopes.size();
  887. I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
  888. (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
  889. cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
  890. CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
  891. CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
  892. if (!CurLSI->isCXXThisCaptured())
  893. continue;
  894. auto C = CurLSI->getCXXThisCapture();
  895. if (C.isCopyCapture()) {
  896. ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  897. if (CurLSI->CallOperator->isConst())
  898. ClassType.addConst();
  899. return ASTCtx.getPointerType(ClassType);
  900. }
  901. }
  902. // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
  903. // happen during instantiation of its nested generic lambda call operator)
  904. if (isLambdaCallOperator(CurDC)) {
  905. assert(CurLSI && "While computing 'this' capture-type for a generic "
  906. "lambda, we must have a corresponding LambdaScopeInfo");
  907. assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
  908. "While computing 'this' capture-type for a generic lambda, when we "
  909. "run out of enclosing LSI's, yet the enclosing DC is a "
  910. "lambda-call-operator we must be (i.e. Current LSI) in a generic "
  911. "lambda call oeprator");
  912. assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
  913. auto IsThisCaptured =
  914. [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
  915. IsConst = false;
  916. IsByCopy = false;
  917. for (auto &&C : Closure->captures()) {
  918. if (C.capturesThis()) {
  919. if (C.getCaptureKind() == LCK_StarThis)
  920. IsByCopy = true;
  921. if (Closure->getLambdaCallOperator()->isConst())
  922. IsConst = true;
  923. return true;
  924. }
  925. }
  926. return false;
  927. };
  928. bool IsByCopyCapture = false;
  929. bool IsConstCapture = false;
  930. CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
  931. while (Closure &&
  932. IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
  933. if (IsByCopyCapture) {
  934. ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  935. if (IsConstCapture)
  936. ClassType.addConst();
  937. return ASTCtx.getPointerType(ClassType);
  938. }
  939. Closure = isLambdaCallOperator(Closure->getParent())
  940. ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
  941. : nullptr;
  942. }
  943. }
  944. return ASTCtx.getPointerType(ClassType);
  945. }
  946. QualType Sema::getCurrentThisType() {
  947. DeclContext *DC = getFunctionLevelDeclContext();
  948. QualType ThisTy = CXXThisTypeOverride;
  949. if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
  950. if (method && method->isInstance())
  951. ThisTy = method->getThisType();
  952. }
  953. if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
  954. inTemplateInstantiation()) {
  955. assert(isa<CXXRecordDecl>(DC) &&
  956. "Trying to get 'this' type from static method?");
  957. // This is a lambda call operator that is being instantiated as a default
  958. // initializer. DC must point to the enclosing class type, so we can recover
  959. // the 'this' type from it.
  960. QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
  961. // There are no cv-qualifiers for 'this' within default initializers,
  962. // per [expr.prim.general]p4.
  963. ThisTy = Context.getPointerType(ClassTy);
  964. }
  965. // If we are within a lambda's call operator, the cv-qualifiers of 'this'
  966. // might need to be adjusted if the lambda or any of its enclosing lambda's
  967. // captures '*this' by copy.
  968. if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
  969. return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
  970. CurContext, Context);
  971. return ThisTy;
  972. }
  973. Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
  974. Decl *ContextDecl,
  975. Qualifiers CXXThisTypeQuals,
  976. bool Enabled)
  977. : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
  978. {
  979. if (!Enabled || !ContextDecl)
  980. return;
  981. CXXRecordDecl *Record = nullptr;
  982. if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
  983. Record = Template->getTemplatedDecl();
  984. else
  985. Record = cast<CXXRecordDecl>(ContextDecl);
  986. QualType T = S.Context.getRecordType(Record);
  987. T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
  988. S.CXXThisTypeOverride = S.Context.getPointerType(T);
  989. this->Enabled = true;
  990. }
  991. Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
  992. if (Enabled) {
  993. S.CXXThisTypeOverride = OldCXXThisTypeOverride;
  994. }
  995. }
  996. bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
  997. bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
  998. const bool ByCopy) {
  999. // We don't need to capture this in an unevaluated context.
  1000. if (isUnevaluatedContext() && !Explicit)
  1001. return true;
  1002. assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
  1003. const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  1004. ? *FunctionScopeIndexToStopAt
  1005. : FunctionScopes.size() - 1;
  1006. // Check that we can capture the *enclosing object* (referred to by '*this')
  1007. // by the capturing-entity/closure (lambda/block/etc) at
  1008. // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
  1009. // Note: The *enclosing object* can only be captured by-value by a
  1010. // closure that is a lambda, using the explicit notation:
  1011. // [*this] { ... }.
  1012. // Every other capture of the *enclosing object* results in its by-reference
  1013. // capture.
  1014. // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
  1015. // stack), we can capture the *enclosing object* only if:
  1016. // - 'L' has an explicit byref or byval capture of the *enclosing object*
  1017. // - or, 'L' has an implicit capture.
  1018. // AND
  1019. // -- there is no enclosing closure
  1020. // -- or, there is some enclosing closure 'E' that has already captured the
  1021. // *enclosing object*, and every intervening closure (if any) between 'E'
  1022. // and 'L' can implicitly capture the *enclosing object*.
  1023. // -- or, every enclosing closure can implicitly capture the
  1024. // *enclosing object*
  1025. unsigned NumCapturingClosures = 0;
  1026. for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
  1027. if (CapturingScopeInfo *CSI =
  1028. dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
  1029. if (CSI->CXXThisCaptureIndex != 0) {
  1030. // 'this' is already being captured; there isn't anything more to do.
  1031. CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
  1032. break;
  1033. }
  1034. LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
  1035. if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
  1036. // This context can't implicitly capture 'this'; fail out.
  1037. if (BuildAndDiagnose)
  1038. Diag(Loc, diag::err_this_capture)
  1039. << (Explicit && idx == MaxFunctionScopesIndex);
  1040. return true;
  1041. }
  1042. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
  1043. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
  1044. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
  1045. CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
  1046. (Explicit && idx == MaxFunctionScopesIndex)) {
  1047. // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
  1048. // iteration through can be an explicit capture, all enclosing closures,
  1049. // if any, must perform implicit captures.
  1050. // This closure can capture 'this'; continue looking upwards.
  1051. NumCapturingClosures++;
  1052. continue;
  1053. }
  1054. // This context can't implicitly capture 'this'; fail out.
  1055. if (BuildAndDiagnose)
  1056. Diag(Loc, diag::err_this_capture)
  1057. << (Explicit && idx == MaxFunctionScopesIndex);
  1058. return true;
  1059. }
  1060. break;
  1061. }
  1062. if (!BuildAndDiagnose) return false;
  1063. // If we got here, then the closure at MaxFunctionScopesIndex on the
  1064. // FunctionScopes stack, can capture the *enclosing object*, so capture it
  1065. // (including implicit by-reference captures in any enclosing closures).
  1066. // In the loop below, respect the ByCopy flag only for the closure requesting
  1067. // the capture (i.e. first iteration through the loop below). Ignore it for
  1068. // all enclosing closure's up to NumCapturingClosures (since they must be
  1069. // implicitly capturing the *enclosing object* by reference (see loop
  1070. // above)).
  1071. assert((!ByCopy ||
  1072. dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
  1073. "Only a lambda can capture the enclosing object (referred to by "
  1074. "*this) by copy");
  1075. QualType ThisTy = getCurrentThisType();
  1076. for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
  1077. --idx, --NumCapturingClosures) {
  1078. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
  1079. // The type of the corresponding data member (not a 'this' pointer if 'by
  1080. // copy').
  1081. QualType CaptureType = ThisTy;
  1082. if (ByCopy) {
  1083. // If we are capturing the object referred to by '*this' by copy, ignore
  1084. // any cv qualifiers inherited from the type of the member function for
  1085. // the type of the closure-type's corresponding data member and any use
  1086. // of 'this'.
  1087. CaptureType = ThisTy->getPointeeType();
  1088. CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
  1089. }
  1090. bool isNested = NumCapturingClosures > 1;
  1091. CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
  1092. }
  1093. return false;
  1094. }
  1095. ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
  1096. /// C++ 9.3.2: In the body of a non-static member function, the keyword this
  1097. /// is a non-lvalue expression whose value is the address of the object for
  1098. /// which the function is called.
  1099. QualType ThisTy = getCurrentThisType();
  1100. if (ThisTy.isNull())
  1101. return Diag(Loc, diag::err_invalid_this_use);
  1102. return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
  1103. }
  1104. Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
  1105. bool IsImplicit) {
  1106. auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
  1107. MarkThisReferenced(This);
  1108. return This;
  1109. }
  1110. void Sema::MarkThisReferenced(CXXThisExpr *This) {
  1111. CheckCXXThisCapture(This->getExprLoc());
  1112. }
  1113. bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
  1114. // If we're outside the body of a member function, then we'll have a specified
  1115. // type for 'this'.
  1116. if (CXXThisTypeOverride.isNull())
  1117. return false;
  1118. // Determine whether we're looking into a class that's currently being
  1119. // defined.
  1120. CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
  1121. return Class && Class->isBeingDefined();
  1122. }
  1123. /// Parse construction of a specified type.
  1124. /// Can be interpreted either as function-style casting ("int(x)")
  1125. /// or class type construction ("ClassType(x,y,z)")
  1126. /// or creation of a value-initialized type ("int()").
  1127. ExprResult
  1128. Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
  1129. SourceLocation LParenOrBraceLoc,
  1130. MultiExprArg exprs,
  1131. SourceLocation RParenOrBraceLoc,
  1132. bool ListInitialization) {
  1133. if (!TypeRep)
  1134. return ExprError();
  1135. TypeSourceInfo *TInfo;
  1136. QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
  1137. if (!TInfo)
  1138. TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
  1139. auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
  1140. RParenOrBraceLoc, ListInitialization);
  1141. // Avoid creating a non-type-dependent expression that contains typos.
  1142. // Non-type-dependent expressions are liable to be discarded without
  1143. // checking for embedded typos.
  1144. if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
  1145. !Result.get()->isTypeDependent())
  1146. Result = CorrectDelayedTyposInExpr(Result.get());
  1147. return Result;
  1148. }
  1149. ExprResult
  1150. Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
  1151. SourceLocation LParenOrBraceLoc,
  1152. MultiExprArg Exprs,
  1153. SourceLocation RParenOrBraceLoc,
  1154. bool ListInitialization) {
  1155. QualType Ty = TInfo->getType();
  1156. SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
  1157. if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
  1158. // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
  1159. // directly. We work around this by dropping the locations of the braces.
  1160. SourceRange Locs = ListInitialization
  1161. ? SourceRange()
  1162. : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
  1163. return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
  1164. Exprs, Locs.getEnd());
  1165. }
  1166. assert((!ListInitialization ||
  1167. (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
  1168. "List initialization must have initializer list as expression.");
  1169. SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
  1170. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
  1171. InitializationKind Kind =
  1172. Exprs.size()
  1173. ? ListInitialization
  1174. ? InitializationKind::CreateDirectList(
  1175. TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
  1176. : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
  1177. RParenOrBraceLoc)
  1178. : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
  1179. RParenOrBraceLoc);
  1180. // C++1z [expr.type.conv]p1:
  1181. // If the type is a placeholder for a deduced class type, [...perform class
  1182. // template argument deduction...]
  1183. DeducedType *Deduced = Ty->getContainedDeducedType();
  1184. if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
  1185. Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
  1186. Kind, Exprs);
  1187. if (Ty.isNull())
  1188. return ExprError();
  1189. Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
  1190. }
  1191. // C++ [expr.type.conv]p1:
  1192. // If the expression list is a parenthesized single expression, the type
  1193. // conversion expression is equivalent (in definedness, and if defined in
  1194. // meaning) to the corresponding cast expression.
  1195. if (Exprs.size() == 1 && !ListInitialization &&
  1196. !isa<InitListExpr>(Exprs[0])) {
  1197. Expr *Arg = Exprs[0];
  1198. return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
  1199. RParenOrBraceLoc);
  1200. }
  1201. // For an expression of the form T(), T shall not be an array type.
  1202. QualType ElemTy = Ty;
  1203. if (Ty->isArrayType()) {
  1204. if (!ListInitialization)
  1205. return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
  1206. << FullRange);
  1207. ElemTy = Context.getBaseElementType(Ty);
  1208. }
  1209. // There doesn't seem to be an explicit rule against this but sanity demands
  1210. // we only construct objects with object types.
  1211. if (Ty->isFunctionType())
  1212. return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
  1213. << Ty << FullRange);
  1214. // C++17 [expr.type.conv]p2:
  1215. // If the type is cv void and the initializer is (), the expression is a
  1216. // prvalue of the specified type that performs no initialization.
  1217. if (!Ty->isVoidType() &&
  1218. RequireCompleteType(TyBeginLoc, ElemTy,
  1219. diag::err_invalid_incomplete_type_use, FullRange))
  1220. return ExprError();
  1221. // Otherwise, the expression is a prvalue of the specified type whose
  1222. // result object is direct-initialized (11.6) with the initializer.
  1223. InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
  1224. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
  1225. if (Result.isInvalid())
  1226. return Result;
  1227. Expr *Inner = Result.get();
  1228. if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
  1229. Inner = BTE->getSubExpr();
  1230. if (!isa<CXXTemporaryObjectExpr>(Inner) &&
  1231. !isa<CXXScalarValueInitExpr>(Inner)) {
  1232. // If we created a CXXTemporaryObjectExpr, that node also represents the
  1233. // functional cast. Otherwise, create an explicit cast to represent
  1234. // the syntactic form of a functional-style cast that was used here.
  1235. //
  1236. // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
  1237. // would give a more consistent AST representation than using a
  1238. // CXXTemporaryObjectExpr. It's also weird that the functional cast
  1239. // is sometimes handled by initialization and sometimes not.
  1240. QualType ResultType = Result.get()->getType();
  1241. SourceRange Locs = ListInitialization
  1242. ? SourceRange()
  1243. : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
  1244. Result = CXXFunctionalCastExpr::Create(
  1245. Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
  1246. Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
  1247. }
  1248. return Result;
  1249. }
  1250. bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
  1251. // [CUDA] Ignore this function, if we can't call it.
  1252. const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
  1253. if (getLangOpts().CUDA &&
  1254. IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
  1255. return false;
  1256. SmallVector<const FunctionDecl*, 4> PreventedBy;
  1257. bool Result = Method->isUsualDeallocationFunction(PreventedBy);
  1258. if (Result || !getLangOpts().CUDA || PreventedBy.empty())
  1259. return Result;
  1260. // In case of CUDA, return true if none of the 1-argument deallocator
  1261. // functions are actually callable.
  1262. return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
  1263. assert(FD->getNumParams() == 1 &&
  1264. "Only single-operand functions should be in PreventedBy");
  1265. return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
  1266. });
  1267. }
  1268. /// Determine whether the given function is a non-placement
  1269. /// deallocation function.
  1270. static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
  1271. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
  1272. return S.isUsualDeallocationFunction(Method);
  1273. if (FD->getOverloadedOperator() != OO_Delete &&
  1274. FD->getOverloadedOperator() != OO_Array_Delete)
  1275. return false;
  1276. unsigned UsualParams = 1;
  1277. if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
  1278. S.Context.hasSameUnqualifiedType(
  1279. FD->getParamDecl(UsualParams)->getType(),
  1280. S.Context.getSizeType()))
  1281. ++UsualParams;
  1282. if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
  1283. S.Context.hasSameUnqualifiedType(
  1284. FD->getParamDecl(UsualParams)->getType(),
  1285. S.Context.getTypeDeclType(S.getStdAlignValT())))
  1286. ++UsualParams;
  1287. return UsualParams == FD->getNumParams();
  1288. }
  1289. namespace {
  1290. struct UsualDeallocFnInfo {
  1291. UsualDeallocFnInfo() : Found(), FD(nullptr) {}
  1292. UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
  1293. : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
  1294. Destroying(false), HasSizeT(false), HasAlignValT(false),
  1295. CUDAPref(Sema::CFP_Native) {
  1296. // A function template declaration is never a usual deallocation function.
  1297. if (!FD)
  1298. return;
  1299. unsigned NumBaseParams = 1;
  1300. if (FD->isDestroyingOperatorDelete()) {
  1301. Destroying = true;
  1302. ++NumBaseParams;
  1303. }
  1304. if (NumBaseParams < FD->getNumParams() &&
  1305. S.Context.hasSameUnqualifiedType(
  1306. FD->getParamDecl(NumBaseParams)->getType(),
  1307. S.Context.getSizeType())) {
  1308. ++NumBaseParams;
  1309. HasSizeT = true;
  1310. }
  1311. if (NumBaseParams < FD->getNumParams() &&
  1312. FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
  1313. ++NumBaseParams;
  1314. HasAlignValT = true;
  1315. }
  1316. // In CUDA, determine how much we'd like / dislike to call this.
  1317. if (S.getLangOpts().CUDA)
  1318. if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  1319. CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
  1320. }
  1321. explicit operator bool() const { return FD; }
  1322. bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
  1323. bool WantAlign) const {
  1324. // C++ P0722:
  1325. // A destroying operator delete is preferred over a non-destroying
  1326. // operator delete.
  1327. if (Destroying != Other.Destroying)
  1328. return Destroying;
  1329. // C++17 [expr.delete]p10:
  1330. // If the type has new-extended alignment, a function with a parameter
  1331. // of type std::align_val_t is preferred; otherwise a function without
  1332. // such a parameter is preferred
  1333. if (HasAlignValT != Other.HasAlignValT)
  1334. return HasAlignValT == WantAlign;
  1335. if (HasSizeT != Other.HasSizeT)
  1336. return HasSizeT == WantSize;
  1337. // Use CUDA call preference as a tiebreaker.
  1338. return CUDAPref > Other.CUDAPref;
  1339. }
  1340. DeclAccessPair Found;
  1341. FunctionDecl *FD;
  1342. bool Destroying, HasSizeT, HasAlignValT;
  1343. Sema::CUDAFunctionPreference CUDAPref;
  1344. };
  1345. }
  1346. /// Determine whether a type has new-extended alignment. This may be called when
  1347. /// the type is incomplete (for a delete-expression with an incomplete pointee
  1348. /// type), in which case it will conservatively return false if the alignment is
  1349. /// not known.
  1350. static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
  1351. return S.getLangOpts().AlignedAllocation &&
  1352. S.getASTContext().getTypeAlignIfKnown(AllocType) >
  1353. S.getASTContext().getTargetInfo().getNewAlign();
  1354. }
  1355. /// Select the correct "usual" deallocation function to use from a selection of
  1356. /// deallocation functions (either global or class-scope).
  1357. static UsualDeallocFnInfo resolveDeallocationOverload(
  1358. Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
  1359. llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
  1360. UsualDeallocFnInfo Best;
  1361. for (auto I = R.begin(), E = R.end(); I != E; ++I) {
  1362. UsualDeallocFnInfo Info(S, I.getPair());
  1363. if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
  1364. Info.CUDAPref == Sema::CFP_Never)
  1365. continue;
  1366. if (!Best) {
  1367. Best = Info;
  1368. if (BestFns)
  1369. BestFns->push_back(Info);
  1370. continue;
  1371. }
  1372. if (Best.isBetterThan(Info, WantSize, WantAlign))
  1373. continue;
  1374. // If more than one preferred function is found, all non-preferred
  1375. // functions are eliminated from further consideration.
  1376. if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
  1377. BestFns->clear();
  1378. Best = Info;
  1379. if (BestFns)
  1380. BestFns->push_back(Info);
  1381. }
  1382. return Best;
  1383. }
  1384. /// Determine whether a given type is a class for which 'delete[]' would call
  1385. /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
  1386. /// we need to store the array size (even if the type is
  1387. /// trivially-destructible).
  1388. static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
  1389. QualType allocType) {
  1390. const RecordType *record =
  1391. allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
  1392. if (!record) return false;
  1393. // Try to find an operator delete[] in class scope.
  1394. DeclarationName deleteName =
  1395. S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
  1396. LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
  1397. S.LookupQualifiedName(ops, record->getDecl());
  1398. // We're just doing this for information.
  1399. ops.suppressDiagnostics();
  1400. // Very likely: there's no operator delete[].
  1401. if (ops.empty()) return false;
  1402. // If it's ambiguous, it should be illegal to call operator delete[]
  1403. // on this thing, so it doesn't matter if we allocate extra space or not.
  1404. if (ops.isAmbiguous()) return false;
  1405. // C++17 [expr.delete]p10:
  1406. // If the deallocation functions have class scope, the one without a
  1407. // parameter of type std::size_t is selected.
  1408. auto Best = resolveDeallocationOverload(
  1409. S, ops, /*WantSize*/false,
  1410. /*WantAlign*/hasNewExtendedAlignment(S, allocType));
  1411. return Best && Best.HasSizeT;
  1412. }
  1413. /// Parsed a C++ 'new' expression (C++ 5.3.4).
  1414. ///
  1415. /// E.g.:
  1416. /// @code new (memory) int[size][4] @endcode
  1417. /// or
  1418. /// @code ::new Foo(23, "hello") @endcode
  1419. ///
  1420. /// \param StartLoc The first location of the expression.
  1421. /// \param UseGlobal True if 'new' was prefixed with '::'.
  1422. /// \param PlacementLParen Opening paren of the placement arguments.
  1423. /// \param PlacementArgs Placement new arguments.
  1424. /// \param PlacementRParen Closing paren of the placement arguments.
  1425. /// \param TypeIdParens If the type is in parens, the source range.
  1426. /// \param D The type to be allocated, as well as array dimensions.
  1427. /// \param Initializer The initializing expression or initializer-list, or null
  1428. /// if there is none.
  1429. ExprResult
  1430. Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
  1431. SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
  1432. SourceLocation PlacementRParen, SourceRange TypeIdParens,
  1433. Declarator &D, Expr *Initializer) {
  1434. Optional<Expr *> ArraySize;
  1435. // If the specified type is an array, unwrap it and save the expression.
  1436. if (D.getNumTypeObjects() > 0 &&
  1437. D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
  1438. DeclaratorChunk &Chunk = D.getTypeObject(0);
  1439. if (D.getDeclSpec().hasAutoTypeSpec())
  1440. return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
  1441. << D.getSourceRange());
  1442. if (Chunk.Arr.hasStatic)
  1443. return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
  1444. << D.getSourceRange());
  1445. if (!Chunk.Arr.NumElts && !Initializer)
  1446. return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
  1447. << D.getSourceRange());
  1448. ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
  1449. D.DropFirstTypeObject();
  1450. }
  1451. // Every dimension shall be of constant size.
  1452. if (ArraySize) {
  1453. for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
  1454. if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
  1455. break;
  1456. DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
  1457. if (Expr *NumElts = (Expr *)Array.NumElts) {
  1458. if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
  1459. if (getLangOpts().CPlusPlus14) {
  1460. // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
  1461. // shall be a converted constant expression (5.19) of type std::size_t
  1462. // and shall evaluate to a strictly positive value.
  1463. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  1464. assert(IntWidth && "Builtin type of size 0?");
  1465. llvm::APSInt Value(IntWidth);
  1466. Array.NumElts
  1467. = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
  1468. CCEK_NewExpr)
  1469. .get();
  1470. } else {
  1471. Array.NumElts
  1472. = VerifyIntegerConstantExpression(NumElts, nullptr,
  1473. diag::err_new_array_nonconst)
  1474. .get();
  1475. }
  1476. if (!Array.NumElts)
  1477. return ExprError();
  1478. }
  1479. }
  1480. }
  1481. }
  1482. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
  1483. QualType AllocType = TInfo->getType();
  1484. if (D.isInvalidType())
  1485. return ExprError();
  1486. SourceRange DirectInitRange;
  1487. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
  1488. DirectInitRange = List->getSourceRange();
  1489. return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
  1490. PlacementLParen, PlacementArgs, PlacementRParen,
  1491. TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
  1492. Initializer);
  1493. }
  1494. static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
  1495. Expr *Init) {
  1496. if (!Init)
  1497. return true;
  1498. if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
  1499. return PLE->getNumExprs() == 0;
  1500. if (isa<ImplicitValueInitExpr>(Init))
  1501. return true;
  1502. else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
  1503. return !CCE->isListInitialization() &&
  1504. CCE->getConstructor()->isDefaultConstructor();
  1505. else if (Style == CXXNewExpr::ListInit) {
  1506. assert(isa<InitListExpr>(Init) &&
  1507. "Shouldn't create list CXXConstructExprs for arrays.");
  1508. return true;
  1509. }
  1510. return false;
  1511. }
  1512. bool
  1513. Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
  1514. if (!getLangOpts().AlignedAllocationUnavailable)
  1515. return false;
  1516. if (FD.isDefined())
  1517. return false;
  1518. bool IsAligned = false;
  1519. if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
  1520. return true;
  1521. return false;
  1522. }
  1523. // Emit a diagnostic if an aligned allocation/deallocation function that is not
  1524. // implemented in the standard library is selected.
  1525. void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
  1526. SourceLocation Loc) {
  1527. if (isUnavailableAlignedAllocationFunction(FD)) {
  1528. const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
  1529. StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
  1530. getASTContext().getTargetInfo().getPlatformName());
  1531. OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
  1532. bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
  1533. Diag(Loc, diag::err_aligned_allocation_unavailable)
  1534. << IsDelete << FD.getType().getAsString() << OSName
  1535. << alignedAllocMinVersion(T.getOS()).getAsString();
  1536. Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
  1537. }
  1538. }
  1539. ExprResult
  1540. Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
  1541. SourceLocation PlacementLParen,
  1542. MultiExprArg PlacementArgs,
  1543. SourceLocation PlacementRParen,
  1544. SourceRange TypeIdParens,
  1545. QualType AllocType,
  1546. TypeSourceInfo *AllocTypeInfo,
  1547. Optional<Expr *> ArraySize,
  1548. SourceRange DirectInitRange,
  1549. Expr *Initializer) {
  1550. SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
  1551. SourceLocation StartLoc = Range.getBegin();
  1552. CXXNewExpr::InitializationStyle initStyle;
  1553. if (DirectInitRange.isValid()) {
  1554. assert(Initializer && "Have parens but no initializer.");
  1555. initStyle = CXXNewExpr::CallInit;
  1556. } else if (Initializer && isa<InitListExpr>(Initializer))
  1557. initStyle = CXXNewExpr::ListInit;
  1558. else {
  1559. assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
  1560. isa<CXXConstructExpr>(Initializer)) &&
  1561. "Initializer expression that cannot have been implicitly created.");
  1562. initStyle = CXXNewExpr::NoInit;
  1563. }
  1564. Expr **Inits = &Initializer;
  1565. unsigned NumInits = Initializer ? 1 : 0;
  1566. if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
  1567. assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
  1568. Inits = List->getExprs();
  1569. NumInits = List->getNumExprs();
  1570. }
  1571. // C++11 [expr.new]p15:
  1572. // A new-expression that creates an object of type T initializes that
  1573. // object as follows:
  1574. InitializationKind Kind
  1575. // - If the new-initializer is omitted, the object is default-
  1576. // initialized (8.5); if no initialization is performed,
  1577. // the object has indeterminate value
  1578. = initStyle == CXXNewExpr::NoInit
  1579. ? InitializationKind::CreateDefault(TypeRange.getBegin())
  1580. // - Otherwise, the new-initializer is interpreted according to
  1581. // the
  1582. // initialization rules of 8.5 for direct-initialization.
  1583. : initStyle == CXXNewExpr::ListInit
  1584. ? InitializationKind::CreateDirectList(
  1585. TypeRange.getBegin(), Initializer->getBeginLoc(),
  1586. Initializer->getEndLoc())
  1587. : InitializationKind::CreateDirect(TypeRange.getBegin(),
  1588. DirectInitRange.getBegin(),
  1589. DirectInitRange.getEnd());
  1590. // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  1591. auto *Deduced = AllocType->getContainedDeducedType();
  1592. if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
  1593. if (ArraySize)
  1594. return ExprError(
  1595. Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
  1596. diag::err_deduced_class_template_compound_type)
  1597. << /*array*/ 2
  1598. << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
  1599. InitializedEntity Entity
  1600. = InitializedEntity::InitializeNew(StartLoc, AllocType);
  1601. AllocType = DeduceTemplateSpecializationFromInitializer(
  1602. AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
  1603. if (AllocType.isNull())
  1604. return ExprError();
  1605. } else if (Deduced) {
  1606. bool Braced = (initStyle == CXXNewExpr::ListInit);
  1607. if (NumInits == 1) {
  1608. if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
  1609. Inits = p->getInits();
  1610. NumInits = p->getNumInits();
  1611. Braced = true;
  1612. }
  1613. }
  1614. if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
  1615. return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
  1616. << AllocType << TypeRange);
  1617. if (NumInits > 1) {
  1618. Expr *FirstBad = Inits[1];
  1619. return ExprError(Diag(FirstBad->getBeginLoc(),
  1620. diag::err_auto_new_ctor_multiple_expressions)
  1621. << AllocType << TypeRange);
  1622. }
  1623. if (Braced && !getLangOpts().CPlusPlus17)
  1624. Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
  1625. << AllocType << TypeRange;
  1626. Expr *Deduce = Inits[0];
  1627. QualType DeducedType;
  1628. if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
  1629. return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
  1630. << AllocType << Deduce->getType()
  1631. << TypeRange << Deduce->getSourceRange());
  1632. if (DeducedType.isNull())
  1633. return ExprError();
  1634. AllocType = DeducedType;
  1635. }
  1636. // Per C++0x [expr.new]p5, the type being constructed may be a
  1637. // typedef of an array type.
  1638. if (!ArraySize) {
  1639. if (const ConstantArrayType *Array
  1640. = Context.getAsConstantArrayType(AllocType)) {
  1641. ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
  1642. Context.getSizeType(),
  1643. TypeRange.getEnd());
  1644. AllocType = Array->getElementType();
  1645. }
  1646. }
  1647. if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
  1648. return ExprError();
  1649. // In ARC, infer 'retaining' for the allocated
  1650. if (getLangOpts().ObjCAutoRefCount &&
  1651. AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  1652. AllocType->isObjCLifetimeType()) {
  1653. AllocType = Context.getLifetimeQualifiedType(AllocType,
  1654. AllocType->getObjCARCImplicitLifetime());
  1655. }
  1656. QualType ResultType = Context.getPointerType(AllocType);
  1657. if (ArraySize && *ArraySize &&
  1658. (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
  1659. ExprResult result = CheckPlaceholderExpr(*ArraySize);
  1660. if (result.isInvalid()) return ExprError();
  1661. ArraySize = result.get();
  1662. }
  1663. // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
  1664. // integral or enumeration type with a non-negative value."
  1665. // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
  1666. // enumeration type, or a class type for which a single non-explicit
  1667. // conversion function to integral or unscoped enumeration type exists.
  1668. // C++1y [expr.new]p6: The expression [...] is implicitly converted to
  1669. // std::size_t.
  1670. llvm::Optional<uint64_t> KnownArraySize;
  1671. if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
  1672. ExprResult ConvertedSize;
  1673. if (getLangOpts().CPlusPlus14) {
  1674. assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
  1675. ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
  1676. AA_Converting);
  1677. if (!ConvertedSize.isInvalid() &&
  1678. (*ArraySize)->getType()->getAs<RecordType>())
  1679. // Diagnose the compatibility of this conversion.
  1680. Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
  1681. << (*ArraySize)->getType() << 0 << "'size_t'";
  1682. } else {
  1683. class SizeConvertDiagnoser : public ICEConvertDiagnoser {
  1684. protected:
  1685. Expr *ArraySize;
  1686. public:
  1687. SizeConvertDiagnoser(Expr *ArraySize)
  1688. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
  1689. ArraySize(ArraySize) {}
  1690. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  1691. QualType T) override {
  1692. return S.Diag(Loc, diag::err_array_size_not_integral)
  1693. << S.getLangOpts().CPlusPlus11 << T;
  1694. }
  1695. SemaDiagnosticBuilder diagnoseIncomplete(
  1696. Sema &S, SourceLocation Loc, QualType T) override {
  1697. return S.Diag(Loc, diag::err_array_size_incomplete_type)
  1698. << T << ArraySize->getSourceRange();
  1699. }
  1700. SemaDiagnosticBuilder diagnoseExplicitConv(
  1701. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  1702. return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
  1703. }
  1704. SemaDiagnosticBuilder noteExplicitConv(
  1705. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1706. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1707. << ConvTy->isEnumeralType() << ConvTy;
  1708. }
  1709. SemaDiagnosticBuilder diagnoseAmbiguous(
  1710. Sema &S, SourceLocation Loc, QualType T) override {
  1711. return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
  1712. }
  1713. SemaDiagnosticBuilder noteAmbiguous(
  1714. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  1715. return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
  1716. << ConvTy->isEnumeralType() << ConvTy;
  1717. }
  1718. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  1719. QualType T,
  1720. QualType ConvTy) override {
  1721. return S.Diag(Loc,
  1722. S.getLangOpts().CPlusPlus11
  1723. ? diag::warn_cxx98_compat_array_size_conversion
  1724. : diag::ext_array_size_conversion)
  1725. << T << ConvTy->isEnumeralType() << ConvTy;
  1726. }
  1727. } SizeDiagnoser(*ArraySize);
  1728. ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
  1729. SizeDiagnoser);
  1730. }
  1731. if (ConvertedSize.isInvalid())
  1732. return ExprError();
  1733. ArraySize = ConvertedSize.get();
  1734. QualType SizeType = (*ArraySize)->getType();
  1735. if (!SizeType->isIntegralOrUnscopedEnumerationType())
  1736. return ExprError();
  1737. // C++98 [expr.new]p7:
  1738. // The expression in a direct-new-declarator shall have integral type
  1739. // with a non-negative value.
  1740. //
  1741. // Let's see if this is a constant < 0. If so, we reject it out of hand,
  1742. // per CWG1464. Otherwise, if it's not a constant, we must have an
  1743. // unparenthesized array type.
  1744. if (!(*ArraySize)->isValueDependent()) {
  1745. llvm::APSInt Value;
  1746. // We've already performed any required implicit conversion to integer or
  1747. // unscoped enumeration type.
  1748. // FIXME: Per CWG1464, we are required to check the value prior to
  1749. // converting to size_t. This will never find a negative array size in
  1750. // C++14 onwards, because Value is always unsigned here!
  1751. if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
  1752. if (Value.isSigned() && Value.isNegative()) {
  1753. return ExprError(Diag((*ArraySize)->getBeginLoc(),
  1754. diag::err_typecheck_negative_array_size)
  1755. << (*ArraySize)->getSourceRange());
  1756. }
  1757. if (!AllocType->isDependentType()) {
  1758. unsigned ActiveSizeBits =
  1759. ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
  1760. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
  1761. return ExprError(
  1762. Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
  1763. << Value.toString(10) << (*ArraySize)->getSourceRange());
  1764. }
  1765. KnownArraySize = Value.getZExtValue();
  1766. } else if (TypeIdParens.isValid()) {
  1767. // Can't have dynamic array size when the type-id is in parentheses.
  1768. Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
  1769. << (*ArraySize)->getSourceRange()
  1770. << FixItHint::CreateRemoval(TypeIdParens.getBegin())
  1771. << FixItHint::CreateRemoval(TypeIdParens.getEnd());
  1772. TypeIdParens = SourceRange();
  1773. }
  1774. }
  1775. // Note that we do *not* convert the argument in any way. It can
  1776. // be signed, larger than size_t, whatever.
  1777. }
  1778. FunctionDecl *OperatorNew = nullptr;
  1779. FunctionDecl *OperatorDelete = nullptr;
  1780. unsigned Alignment =
  1781. AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
  1782. unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
  1783. bool PassAlignment = getLangOpts().AlignedAllocation &&
  1784. Alignment > NewAlignment;
  1785. AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
  1786. if (!AllocType->isDependentType() &&
  1787. !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
  1788. FindAllocationFunctions(
  1789. StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
  1790. AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
  1791. OperatorNew, OperatorDelete))
  1792. return ExprError();
  1793. // If this is an array allocation, compute whether the usual array
  1794. // deallocation function for the type has a size_t parameter.
  1795. bool UsualArrayDeleteWantsSize = false;
  1796. if (ArraySize && !AllocType->isDependentType())
  1797. UsualArrayDeleteWantsSize =
  1798. doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
  1799. SmallVector<Expr *, 8> AllPlaceArgs;
  1800. if (OperatorNew) {
  1801. const FunctionProtoType *Proto =
  1802. OperatorNew->getType()->getAs<FunctionProtoType>();
  1803. VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
  1804. : VariadicDoesNotApply;
  1805. // We've already converted the placement args, just fill in any default
  1806. // arguments. Skip the first parameter because we don't have a corresponding
  1807. // argument. Skip the second parameter too if we're passing in the
  1808. // alignment; we've already filled it in.
  1809. if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
  1810. PassAlignment ? 2 : 1, PlacementArgs,
  1811. AllPlaceArgs, CallType))
  1812. return ExprError();
  1813. if (!AllPlaceArgs.empty())
  1814. PlacementArgs = AllPlaceArgs;
  1815. // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
  1816. DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
  1817. // FIXME: Missing call to CheckFunctionCall or equivalent
  1818. // Warn if the type is over-aligned and is being allocated by (unaligned)
  1819. // global operator new.
  1820. if (PlacementArgs.empty() && !PassAlignment &&
  1821. (OperatorNew->isImplicit() ||
  1822. (OperatorNew->getBeginLoc().isValid() &&
  1823. getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
  1824. if (Alignment > NewAlignment)
  1825. Diag(StartLoc, diag::warn_overaligned_type)
  1826. << AllocType
  1827. << unsigned(Alignment / Context.getCharWidth())
  1828. << unsigned(NewAlignment / Context.getCharWidth());
  1829. }
  1830. }
  1831. // Array 'new' can't have any initializers except empty parentheses.
  1832. // Initializer lists are also allowed, in C++11. Rely on the parser for the
  1833. // dialect distinction.
  1834. if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
  1835. SourceRange InitRange(Inits[0]->getBeginLoc(),
  1836. Inits[NumInits - 1]->getEndLoc());
  1837. Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
  1838. return ExprError();
  1839. }
  1840. // If we can perform the initialization, and we've not already done so,
  1841. // do it now.
  1842. if (!AllocType->isDependentType() &&
  1843. !Expr::hasAnyTypeDependentArguments(
  1844. llvm::makeArrayRef(Inits, NumInits))) {
  1845. // The type we initialize is the complete type, including the array bound.
  1846. QualType InitType;
  1847. if (KnownArraySize)
  1848. InitType = Context.getConstantArrayType(
  1849. AllocType,
  1850. llvm::APInt(Context.getTypeSize(Context.getSizeType()),
  1851. *KnownArraySize),
  1852. *ArraySize, ArrayType::Normal, 0);
  1853. else if (ArraySize)
  1854. InitType =
  1855. Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
  1856. else
  1857. InitType = AllocType;
  1858. InitializedEntity Entity
  1859. = InitializedEntity::InitializeNew(StartLoc, InitType);
  1860. InitializationSequence InitSeq(*this, Entity, Kind,
  1861. MultiExprArg(Inits, NumInits));
  1862. ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
  1863. MultiExprArg(Inits, NumInits));
  1864. if (FullInit.isInvalid())
  1865. return ExprError();
  1866. // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
  1867. // we don't want the initialized object to be destructed.
  1868. // FIXME: We should not create these in the first place.
  1869. if (CXXBindTemporaryExpr *Binder =
  1870. dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
  1871. FullInit = Binder->getSubExpr();
  1872. Initializer = FullInit.get();
  1873. // FIXME: If we have a KnownArraySize, check that the array bound of the
  1874. // initializer is no greater than that constant value.
  1875. if (ArraySize && !*ArraySize) {
  1876. auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
  1877. if (CAT) {
  1878. // FIXME: Track that the array size was inferred rather than explicitly
  1879. // specified.
  1880. ArraySize = IntegerLiteral::Create(
  1881. Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
  1882. } else {
  1883. Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
  1884. << Initializer->getSourceRange();
  1885. }
  1886. }
  1887. }
  1888. // Mark the new and delete operators as referenced.
  1889. if (OperatorNew) {
  1890. if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
  1891. return ExprError();
  1892. MarkFunctionReferenced(StartLoc, OperatorNew);
  1893. }
  1894. if (OperatorDelete) {
  1895. if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
  1896. return ExprError();
  1897. MarkFunctionReferenced(StartLoc, OperatorDelete);
  1898. }
  1899. return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
  1900. PassAlignment, UsualArrayDeleteWantsSize,
  1901. PlacementArgs, TypeIdParens, ArraySize, initStyle,
  1902. Initializer, ResultType, AllocTypeInfo, Range,
  1903. DirectInitRange);
  1904. }
  1905. /// Checks that a type is suitable as the allocated type
  1906. /// in a new-expression.
  1907. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
  1908. SourceRange R) {
  1909. // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
  1910. // abstract class type or array thereof.
  1911. if (AllocType->isFunctionType())
  1912. return Diag(Loc, diag::err_bad_new_type)
  1913. << AllocType << 0 << R;
  1914. else if (AllocType->isReferenceType())
  1915. return Diag(Loc, diag::err_bad_new_type)
  1916. << AllocType << 1 << R;
  1917. else if (!AllocType->isDependentType() &&
  1918. RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
  1919. return true;
  1920. else if (RequireNonAbstractType(Loc, AllocType,
  1921. diag::err_allocation_of_abstract_type))
  1922. return true;
  1923. else if (AllocType->isVariablyModifiedType())
  1924. return Diag(Loc, diag::err_variably_modified_new_type)
  1925. << AllocType;
  1926. else if (AllocType.getAddressSpace() != LangAS::Default &&
  1927. !getLangOpts().OpenCLCPlusPlus)
  1928. return Diag(Loc, diag::err_address_space_qualified_new)
  1929. << AllocType.getUnqualifiedType()
  1930. << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
  1931. else if (getLangOpts().ObjCAutoRefCount) {
  1932. if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
  1933. QualType BaseAllocType = Context.getBaseElementType(AT);
  1934. if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
  1935. BaseAllocType->isObjCLifetimeType())
  1936. return Diag(Loc, diag::err_arc_new_array_without_ownership)
  1937. << BaseAllocType;
  1938. }
  1939. }
  1940. return false;
  1941. }
  1942. static bool resolveAllocationOverload(
  1943. Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
  1944. bool &PassAlignment, FunctionDecl *&Operator,
  1945. OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
  1946. OverloadCandidateSet Candidates(R.getNameLoc(),
  1947. OverloadCandidateSet::CSK_Normal);
  1948. for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
  1949. Alloc != AllocEnd; ++Alloc) {
  1950. // Even member operator new/delete are implicitly treated as
  1951. // static, so don't use AddMemberCandidate.
  1952. NamedDecl *D = (*Alloc)->getUnderlyingDecl();
  1953. if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
  1954. S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
  1955. /*ExplicitTemplateArgs=*/nullptr, Args,
  1956. Candidates,
  1957. /*SuppressUserConversions=*/false);
  1958. continue;
  1959. }
  1960. FunctionDecl *Fn = cast<FunctionDecl>(D);
  1961. S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
  1962. /*SuppressUserConversions=*/false);
  1963. }
  1964. // Do the resolution.
  1965. OverloadCandidateSet::iterator Best;
  1966. switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
  1967. case OR_Success: {
  1968. // Got one!
  1969. FunctionDecl *FnDecl = Best->Function;
  1970. if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
  1971. Best->FoundDecl) == Sema::AR_inaccessible)
  1972. return true;
  1973. Operator = FnDecl;
  1974. return false;
  1975. }
  1976. case OR_No_Viable_Function:
  1977. // C++17 [expr.new]p13:
  1978. // If no matching function is found and the allocated object type has
  1979. // new-extended alignment, the alignment argument is removed from the
  1980. // argument list, and overload resolution is performed again.
  1981. if (PassAlignment) {
  1982. PassAlignment = false;
  1983. AlignArg = Args[1];
  1984. Args.erase(Args.begin() + 1);
  1985. return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
  1986. Operator, &Candidates, AlignArg,
  1987. Diagnose);
  1988. }
  1989. // MSVC will fall back on trying to find a matching global operator new
  1990. // if operator new[] cannot be found. Also, MSVC will leak by not
  1991. // generating a call to operator delete or operator delete[], but we
  1992. // will not replicate that bug.
  1993. // FIXME: Find out how this interacts with the std::align_val_t fallback
  1994. // once MSVC implements it.
  1995. if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
  1996. S.Context.getLangOpts().MSVCCompat) {
  1997. R.clear();
  1998. R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
  1999. S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
  2000. // FIXME: This will give bad diagnostics pointing at the wrong functions.
  2001. return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
  2002. Operator, /*Candidates=*/nullptr,
  2003. /*AlignArg=*/nullptr, Diagnose);
  2004. }
  2005. if (Diagnose) {
  2006. PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
  2007. << R.getLookupName() << Range);
  2008. // If we have aligned candidates, only note the align_val_t candidates
  2009. // from AlignedCandidates and the non-align_val_t candidates from
  2010. // Candidates.
  2011. if (AlignedCandidates) {
  2012. auto IsAligned = [](OverloadCandidate &C) {
  2013. return C.Function->getNumParams() > 1 &&
  2014. C.Function->getParamDecl(1)->getType()->isAlignValT();
  2015. };
  2016. auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
  2017. // This was an overaligned allocation, so list the aligned candidates
  2018. // first.
  2019. Args.insert(Args.begin() + 1, AlignArg);
  2020. AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
  2021. R.getNameLoc(), IsAligned);
  2022. Args.erase(Args.begin() + 1);
  2023. Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
  2024. IsUnaligned);
  2025. } else {
  2026. Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
  2027. }
  2028. }
  2029. return true;
  2030. case OR_Ambiguous:
  2031. if (Diagnose) {
  2032. Candidates.NoteCandidates(
  2033. PartialDiagnosticAt(R.getNameLoc(),
  2034. S.PDiag(diag::err_ovl_ambiguous_call)
  2035. << R.getLookupName() << Range),
  2036. S, OCD_ViableCandidates, Args);
  2037. }
  2038. return true;
  2039. case OR_Deleted: {
  2040. if (Diagnose) {
  2041. Candidates.NoteCandidates(
  2042. PartialDiagnosticAt(R.getNameLoc(),
  2043. S.PDiag(diag::err_ovl_deleted_call)
  2044. << R.getLookupName() << Range),
  2045. S, OCD_AllCandidates, Args);
  2046. }
  2047. return true;
  2048. }
  2049. }
  2050. llvm_unreachable("Unreachable, bad result from BestViableFunction");
  2051. }
  2052. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
  2053. AllocationFunctionScope NewScope,
  2054. AllocationFunctionScope DeleteScope,
  2055. QualType AllocType, bool IsArray,
  2056. bool &PassAlignment, MultiExprArg PlaceArgs,
  2057. FunctionDecl *&OperatorNew,
  2058. FunctionDecl *&OperatorDelete,
  2059. bool Diagnose) {
  2060. // --- Choosing an allocation function ---
  2061. // C++ 5.3.4p8 - 14 & 18
  2062. // 1) If looking in AFS_Global scope for allocation functions, only look in
  2063. // the global scope. Else, if AFS_Class, only look in the scope of the
  2064. // allocated class. If AFS_Both, look in both.
  2065. // 2) If an array size is given, look for operator new[], else look for
  2066. // operator new.
  2067. // 3) The first argument is always size_t. Append the arguments from the
  2068. // placement form.
  2069. SmallVector<Expr*, 8> AllocArgs;
  2070. AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
  2071. // We don't care about the actual value of these arguments.
  2072. // FIXME: Should the Sema create the expression and embed it in the syntax
  2073. // tree? Or should the consumer just recalculate the value?
  2074. // FIXME: Using a dummy value will interact poorly with attribute enable_if.
  2075. IntegerLiteral Size(Context, llvm::APInt::getNullValue(
  2076. Context.getTargetInfo().getPointerWidth(0)),
  2077. Context.getSizeType(),
  2078. SourceLocation());
  2079. AllocArgs.push_back(&Size);
  2080. QualType AlignValT = Context.VoidTy;
  2081. if (PassAlignment) {
  2082. DeclareGlobalNewDelete();
  2083. AlignValT = Context.getTypeDeclType(getStdAlignValT());
  2084. }
  2085. CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
  2086. if (PassAlignment)
  2087. AllocArgs.push_back(&Align);
  2088. AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
  2089. // C++ [expr.new]p8:
  2090. // If the allocated type is a non-array type, the allocation
  2091. // function's name is operator new and the deallocation function's
  2092. // name is operator delete. If the allocated type is an array
  2093. // type, the allocation function's name is operator new[] and the
  2094. // deallocation function's name is operator delete[].
  2095. DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
  2096. IsArray ? OO_Array_New : OO_New);
  2097. QualType AllocElemType = Context.getBaseElementType(AllocType);
  2098. // Find the allocation function.
  2099. {
  2100. LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
  2101. // C++1z [expr.new]p9:
  2102. // If the new-expression begins with a unary :: operator, the allocation
  2103. // function's name is looked up in the global scope. Otherwise, if the
  2104. // allocated type is a class type T or array thereof, the allocation
  2105. // function's name is looked up in the scope of T.
  2106. if (AllocElemType->isRecordType() && NewScope != AFS_Global)
  2107. LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
  2108. // We can see ambiguity here if the allocation function is found in
  2109. // multiple base classes.
  2110. if (R.isAmbiguous())
  2111. return true;
  2112. // If this lookup fails to find the name, or if the allocated type is not
  2113. // a class type, the allocation function's name is looked up in the
  2114. // global scope.
  2115. if (R.empty()) {
  2116. if (NewScope == AFS_Class)
  2117. return true;
  2118. LookupQualifiedName(R, Context.getTranslationUnitDecl());
  2119. }
  2120. if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
  2121. if (PlaceArgs.empty()) {
  2122. Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
  2123. } else {
  2124. Diag(StartLoc, diag::err_openclcxx_placement_new);
  2125. }
  2126. return true;
  2127. }
  2128. assert(!R.empty() && "implicitly declared allocation functions not found");
  2129. assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
  2130. // We do our own custom access checks below.
  2131. R.suppressDiagnostics();
  2132. if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
  2133. OperatorNew, /*Candidates=*/nullptr,
  2134. /*AlignArg=*/nullptr, Diagnose))
  2135. return true;
  2136. }
  2137. // We don't need an operator delete if we're running under -fno-exceptions.
  2138. if (!getLangOpts().Exceptions) {
  2139. OperatorDelete = nullptr;
  2140. return false;
  2141. }
  2142. // Note, the name of OperatorNew might have been changed from array to
  2143. // non-array by resolveAllocationOverload.
  2144. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  2145. OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
  2146. ? OO_Array_Delete
  2147. : OO_Delete);
  2148. // C++ [expr.new]p19:
  2149. //
  2150. // If the new-expression begins with a unary :: operator, the
  2151. // deallocation function's name is looked up in the global
  2152. // scope. Otherwise, if the allocated type is a class type T or an
  2153. // array thereof, the deallocation function's name is looked up in
  2154. // the scope of T. If this lookup fails to find the name, or if
  2155. // the allocated type is not a class type or array thereof, the
  2156. // deallocation function's name is looked up in the global scope.
  2157. LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
  2158. if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
  2159. auto *RD =
  2160. cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
  2161. LookupQualifiedName(FoundDelete, RD);
  2162. }
  2163. if (FoundDelete.isAmbiguous())
  2164. return true; // FIXME: clean up expressions?
  2165. bool FoundGlobalDelete = FoundDelete.empty();
  2166. if (FoundDelete.empty()) {
  2167. if (DeleteScope == AFS_Class)
  2168. return true;
  2169. DeclareGlobalNewDelete();
  2170. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  2171. }
  2172. FoundDelete.suppressDiagnostics();
  2173. SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
  2174. // Whether we're looking for a placement operator delete is dictated
  2175. // by whether we selected a placement operator new, not by whether
  2176. // we had explicit placement arguments. This matters for things like
  2177. // struct A { void *operator new(size_t, int = 0); ... };
  2178. // A *a = new A()
  2179. //
  2180. // We don't have any definition for what a "placement allocation function"
  2181. // is, but we assume it's any allocation function whose
  2182. // parameter-declaration-clause is anything other than (size_t).
  2183. //
  2184. // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
  2185. // This affects whether an exception from the constructor of an overaligned
  2186. // type uses the sized or non-sized form of aligned operator delete.
  2187. bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
  2188. OperatorNew->isVariadic();
  2189. if (isPlacementNew) {
  2190. // C++ [expr.new]p20:
  2191. // A declaration of a placement deallocation function matches the
  2192. // declaration of a placement allocation function if it has the
  2193. // same number of parameters and, after parameter transformations
  2194. // (8.3.5), all parameter types except the first are
  2195. // identical. [...]
  2196. //
  2197. // To perform this comparison, we compute the function type that
  2198. // the deallocation function should have, and use that type both
  2199. // for template argument deduction and for comparison purposes.
  2200. QualType ExpectedFunctionType;
  2201. {
  2202. const FunctionProtoType *Proto
  2203. = OperatorNew->getType()->getAs<FunctionProtoType>();
  2204. SmallVector<QualType, 4> ArgTypes;
  2205. ArgTypes.push_back(Context.VoidPtrTy);
  2206. for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
  2207. ArgTypes.push_back(Proto->getParamType(I));
  2208. FunctionProtoType::ExtProtoInfo EPI;
  2209. // FIXME: This is not part of the standard's rule.
  2210. EPI.Variadic = Proto->isVariadic();
  2211. ExpectedFunctionType
  2212. = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
  2213. }
  2214. for (LookupResult::iterator D = FoundDelete.begin(),
  2215. DEnd = FoundDelete.end();
  2216. D != DEnd; ++D) {
  2217. FunctionDecl *Fn = nullptr;
  2218. if (FunctionTemplateDecl *FnTmpl =
  2219. dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
  2220. // Perform template argument deduction to try to match the
  2221. // expected function type.
  2222. TemplateDeductionInfo Info(StartLoc);
  2223. if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
  2224. Info))
  2225. continue;
  2226. } else
  2227. Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
  2228. if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
  2229. ExpectedFunctionType,
  2230. /*AdjustExcpetionSpec*/true),
  2231. ExpectedFunctionType))
  2232. Matches.push_back(std::make_pair(D.getPair(), Fn));
  2233. }
  2234. if (getLangOpts().CUDA)
  2235. EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
  2236. } else {
  2237. // C++1y [expr.new]p22:
  2238. // For a non-placement allocation function, the normal deallocation
  2239. // function lookup is used
  2240. //
  2241. // Per [expr.delete]p10, this lookup prefers a member operator delete
  2242. // without a size_t argument, but prefers a non-member operator delete
  2243. // with a size_t where possible (which it always is in this case).
  2244. llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
  2245. UsualDeallocFnInfo Selected = resolveDeallocationOverload(
  2246. *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
  2247. /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
  2248. &BestDeallocFns);
  2249. if (Selected)
  2250. Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
  2251. else {
  2252. // If we failed to select an operator, all remaining functions are viable
  2253. // but ambiguous.
  2254. for (auto Fn : BestDeallocFns)
  2255. Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
  2256. }
  2257. }
  2258. // C++ [expr.new]p20:
  2259. // [...] If the lookup finds a single matching deallocation
  2260. // function, that function will be called; otherwise, no
  2261. // deallocation function will be called.
  2262. if (Matches.size() == 1) {
  2263. OperatorDelete = Matches[0].second;
  2264. // C++1z [expr.new]p23:
  2265. // If the lookup finds a usual deallocation function (3.7.4.2)
  2266. // with a parameter of type std::size_t and that function, considered
  2267. // as a placement deallocation function, would have been
  2268. // selected as a match for the allocation function, the program
  2269. // is ill-formed.
  2270. if (getLangOpts().CPlusPlus11 && isPlacementNew &&
  2271. isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
  2272. UsualDeallocFnInfo Info(*this,
  2273. DeclAccessPair::make(OperatorDelete, AS_public));
  2274. // Core issue, per mail to core reflector, 2016-10-09:
  2275. // If this is a member operator delete, and there is a corresponding
  2276. // non-sized member operator delete, this isn't /really/ a sized
  2277. // deallocation function, it just happens to have a size_t parameter.
  2278. bool IsSizedDelete = Info.HasSizeT;
  2279. if (IsSizedDelete && !FoundGlobalDelete) {
  2280. auto NonSizedDelete =
  2281. resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
  2282. /*WantAlign*/Info.HasAlignValT);
  2283. if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
  2284. NonSizedDelete.HasAlignValT == Info.HasAlignValT)
  2285. IsSizedDelete = false;
  2286. }
  2287. if (IsSizedDelete) {
  2288. SourceRange R = PlaceArgs.empty()
  2289. ? SourceRange()
  2290. : SourceRange(PlaceArgs.front()->getBeginLoc(),
  2291. PlaceArgs.back()->getEndLoc());
  2292. Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
  2293. if (!OperatorDelete->isImplicit())
  2294. Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
  2295. << DeleteName;
  2296. }
  2297. }
  2298. CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
  2299. Matches[0].first);
  2300. } else if (!Matches.empty()) {
  2301. // We found multiple suitable operators. Per [expr.new]p20, that means we
  2302. // call no 'operator delete' function, but we should at least warn the user.
  2303. // FIXME: Suppress this warning if the construction cannot throw.
  2304. Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
  2305. << DeleteName << AllocElemType;
  2306. for (auto &Match : Matches)
  2307. Diag(Match.second->getLocation(),
  2308. diag::note_member_declared_here) << DeleteName;
  2309. }
  2310. return false;
  2311. }
  2312. /// DeclareGlobalNewDelete - Declare the global forms of operator new and
  2313. /// delete. These are:
  2314. /// @code
  2315. /// // C++03:
  2316. /// void* operator new(std::size_t) throw(std::bad_alloc);
  2317. /// void* operator new[](std::size_t) throw(std::bad_alloc);
  2318. /// void operator delete(void *) throw();
  2319. /// void operator delete[](void *) throw();
  2320. /// // C++11:
  2321. /// void* operator new(std::size_t);
  2322. /// void* operator new[](std::size_t);
  2323. /// void operator delete(void *) noexcept;
  2324. /// void operator delete[](void *) noexcept;
  2325. /// // C++1y:
  2326. /// void* operator new(std::size_t);
  2327. /// void* operator new[](std::size_t);
  2328. /// void operator delete(void *) noexcept;
  2329. /// void operator delete[](void *) noexcept;
  2330. /// void operator delete(void *, std::size_t) noexcept;
  2331. /// void operator delete[](void *, std::size_t) noexcept;
  2332. /// @endcode
  2333. /// Note that the placement and nothrow forms of new are *not* implicitly
  2334. /// declared. Their use requires including \<new\>.
  2335. void Sema::DeclareGlobalNewDelete() {
  2336. if (GlobalNewDeleteDeclared)
  2337. return;
  2338. // The implicitly declared new and delete operators
  2339. // are not supported in OpenCL.
  2340. if (getLangOpts().OpenCLCPlusPlus)
  2341. return;
  2342. // C++ [basic.std.dynamic]p2:
  2343. // [...] The following allocation and deallocation functions (18.4) are
  2344. // implicitly declared in global scope in each translation unit of a
  2345. // program
  2346. //
  2347. // C++03:
  2348. // void* operator new(std::size_t) throw(std::bad_alloc);
  2349. // void* operator new[](std::size_t) throw(std::bad_alloc);
  2350. // void operator delete(void*) throw();
  2351. // void operator delete[](void*) throw();
  2352. // C++11:
  2353. // void* operator new(std::size_t);
  2354. // void* operator new[](std::size_t);
  2355. // void operator delete(void*) noexcept;
  2356. // void operator delete[](void*) noexcept;
  2357. // C++1y:
  2358. // void* operator new(std::size_t);
  2359. // void* operator new[](std::size_t);
  2360. // void operator delete(void*) noexcept;
  2361. // void operator delete[](void*) noexcept;
  2362. // void operator delete(void*, std::size_t) noexcept;
  2363. // void operator delete[](void*, std::size_t) noexcept;
  2364. //
  2365. // These implicit declarations introduce only the function names operator
  2366. // new, operator new[], operator delete, operator delete[].
  2367. //
  2368. // Here, we need to refer to std::bad_alloc, so we will implicitly declare
  2369. // "std" or "bad_alloc" as necessary to form the exception specification.
  2370. // However, we do not make these implicit declarations visible to name
  2371. // lookup.
  2372. if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
  2373. // The "std::bad_alloc" class has not yet been declared, so build it
  2374. // implicitly.
  2375. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
  2376. getOrCreateStdNamespace(),
  2377. SourceLocation(), SourceLocation(),
  2378. &PP.getIdentifierTable().get("bad_alloc"),
  2379. nullptr);
  2380. getStdBadAlloc()->setImplicit(true);
  2381. }
  2382. if (!StdAlignValT && getLangOpts().AlignedAllocation) {
  2383. // The "std::align_val_t" enum class has not yet been declared, so build it
  2384. // implicitly.
  2385. auto *AlignValT = EnumDecl::Create(
  2386. Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
  2387. &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
  2388. AlignValT->setIntegerType(Context.getSizeType());
  2389. AlignValT->setPromotionType(Context.getSizeType());
  2390. AlignValT->setImplicit(true);
  2391. StdAlignValT = AlignValT;
  2392. }
  2393. GlobalNewDeleteDeclared = true;
  2394. QualType VoidPtr = Context.getPointerType(Context.VoidTy);
  2395. QualType SizeT = Context.getSizeType();
  2396. auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
  2397. QualType Return, QualType Param) {
  2398. llvm::SmallVector<QualType, 3> Params;
  2399. Params.push_back(Param);
  2400. // Create up to four variants of the function (sized/aligned).
  2401. bool HasSizedVariant = getLangOpts().SizedDeallocation &&
  2402. (Kind == OO_Delete || Kind == OO_Array_Delete);
  2403. bool HasAlignedVariant = getLangOpts().AlignedAllocation;
  2404. int NumSizeVariants = (HasSizedVariant ? 2 : 1);
  2405. int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
  2406. for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
  2407. if (Sized)
  2408. Params.push_back(SizeT);
  2409. for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
  2410. if (Aligned)
  2411. Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
  2412. DeclareGlobalAllocationFunction(
  2413. Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
  2414. if (Aligned)
  2415. Params.pop_back();
  2416. }
  2417. }
  2418. };
  2419. DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
  2420. DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
  2421. DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
  2422. DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
  2423. }
  2424. /// DeclareGlobalAllocationFunction - Declares a single implicit global
  2425. /// allocation function if it doesn't already exist.
  2426. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
  2427. QualType Return,
  2428. ArrayRef<QualType> Params) {
  2429. DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
  2430. // Check if this function is already declared.
  2431. DeclContext::lookup_result R = GlobalCtx->lookup(Name);
  2432. for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
  2433. Alloc != AllocEnd; ++Alloc) {
  2434. // Only look at non-template functions, as it is the predefined,
  2435. // non-templated allocation function we are trying to declare here.
  2436. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
  2437. if (Func->getNumParams() == Params.size()) {
  2438. llvm::SmallVector<QualType, 3> FuncParams;
  2439. for (auto *P : Func->parameters())
  2440. FuncParams.push_back(
  2441. Context.getCanonicalType(P->getType().getUnqualifiedType()));
  2442. if (llvm::makeArrayRef(FuncParams) == Params) {
  2443. // Make the function visible to name lookup, even if we found it in
  2444. // an unimported module. It either is an implicitly-declared global
  2445. // allocation function, or is suppressing that function.
  2446. Func->setVisibleDespiteOwningModule();
  2447. return;
  2448. }
  2449. }
  2450. }
  2451. }
  2452. FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
  2453. /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
  2454. QualType BadAllocType;
  2455. bool HasBadAllocExceptionSpec
  2456. = (Name.getCXXOverloadedOperator() == OO_New ||
  2457. Name.getCXXOverloadedOperator() == OO_Array_New);
  2458. if (HasBadAllocExceptionSpec) {
  2459. if (!getLangOpts().CPlusPlus11) {
  2460. BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
  2461. assert(StdBadAlloc && "Must have std::bad_alloc declared");
  2462. EPI.ExceptionSpec.Type = EST_Dynamic;
  2463. EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
  2464. }
  2465. } else {
  2466. EPI.ExceptionSpec =
  2467. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  2468. }
  2469. auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
  2470. QualType FnType = Context.getFunctionType(Return, Params, EPI);
  2471. FunctionDecl *Alloc = FunctionDecl::Create(
  2472. Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
  2473. FnType, /*TInfo=*/nullptr, SC_None, false, true);
  2474. Alloc->setImplicit();
  2475. // Global allocation functions should always be visible.
  2476. Alloc->setVisibleDespiteOwningModule();
  2477. Alloc->addAttr(VisibilityAttr::CreateImplicit(
  2478. Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
  2479. ? VisibilityAttr::Hidden
  2480. : VisibilityAttr::Default));
  2481. llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
  2482. for (QualType T : Params) {
  2483. ParamDecls.push_back(ParmVarDecl::Create(
  2484. Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
  2485. /*TInfo=*/nullptr, SC_None, nullptr));
  2486. ParamDecls.back()->setImplicit();
  2487. }
  2488. Alloc->setParams(ParamDecls);
  2489. if (ExtraAttr)
  2490. Alloc->addAttr(ExtraAttr);
  2491. Context.getTranslationUnitDecl()->addDecl(Alloc);
  2492. IdResolver.tryAddTopLevelDecl(Alloc, Name);
  2493. };
  2494. if (!LangOpts.CUDA)
  2495. CreateAllocationFunctionDecl(nullptr);
  2496. else {
  2497. // Host and device get their own declaration so each can be
  2498. // defined or re-declared independently.
  2499. CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
  2500. CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
  2501. }
  2502. }
  2503. FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
  2504. bool CanProvideSize,
  2505. bool Overaligned,
  2506. DeclarationName Name) {
  2507. DeclareGlobalNewDelete();
  2508. LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
  2509. LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
  2510. // FIXME: It's possible for this to result in ambiguity, through a
  2511. // user-declared variadic operator delete or the enable_if attribute. We
  2512. // should probably not consider those cases to be usual deallocation
  2513. // functions. But for now we just make an arbitrary choice in that case.
  2514. auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
  2515. Overaligned);
  2516. assert(Result.FD && "operator delete missing from global scope?");
  2517. return Result.FD;
  2518. }
  2519. FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
  2520. CXXRecordDecl *RD) {
  2521. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  2522. FunctionDecl *OperatorDelete = nullptr;
  2523. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
  2524. return nullptr;
  2525. if (OperatorDelete)
  2526. return OperatorDelete;
  2527. // If there's no class-specific operator delete, look up the global
  2528. // non-array delete.
  2529. return FindUsualDeallocationFunction(
  2530. Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
  2531. Name);
  2532. }
  2533. bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
  2534. DeclarationName Name,
  2535. FunctionDecl *&Operator, bool Diagnose) {
  2536. LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
  2537. // Try to find operator delete/operator delete[] in class scope.
  2538. LookupQualifiedName(Found, RD);
  2539. if (Found.isAmbiguous())
  2540. return true;
  2541. Found.suppressDiagnostics();
  2542. bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
  2543. // C++17 [expr.delete]p10:
  2544. // If the deallocation functions have class scope, the one without a
  2545. // parameter of type std::size_t is selected.
  2546. llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
  2547. resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
  2548. /*WantAlign*/ Overaligned, &Matches);
  2549. // If we could find an overload, use it.
  2550. if (Matches.size() == 1) {
  2551. Operator = cast<CXXMethodDecl>(Matches[0].FD);
  2552. // FIXME: DiagnoseUseOfDecl?
  2553. if (Operator->isDeleted()) {
  2554. if (Diagnose) {
  2555. Diag(StartLoc, diag::err_deleted_function_use);
  2556. NoteDeletedFunction(Operator);
  2557. }
  2558. return true;
  2559. }
  2560. if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
  2561. Matches[0].Found, Diagnose) == AR_inaccessible)
  2562. return true;
  2563. return false;
  2564. }
  2565. // We found multiple suitable operators; complain about the ambiguity.
  2566. // FIXME: The standard doesn't say to do this; it appears that the intent
  2567. // is that this should never happen.
  2568. if (!Matches.empty()) {
  2569. if (Diagnose) {
  2570. Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
  2571. << Name << RD;
  2572. for (auto &Match : Matches)
  2573. Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
  2574. }
  2575. return true;
  2576. }
  2577. // We did find operator delete/operator delete[] declarations, but
  2578. // none of them were suitable.
  2579. if (!Found.empty()) {
  2580. if (Diagnose) {
  2581. Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
  2582. << Name << RD;
  2583. for (NamedDecl *D : Found)
  2584. Diag(D->getUnderlyingDecl()->getLocation(),
  2585. diag::note_member_declared_here) << Name;
  2586. }
  2587. return true;
  2588. }
  2589. Operator = nullptr;
  2590. return false;
  2591. }
  2592. namespace {
  2593. /// Checks whether delete-expression, and new-expression used for
  2594. /// initializing deletee have the same array form.
  2595. class MismatchingNewDeleteDetector {
  2596. public:
  2597. enum MismatchResult {
  2598. /// Indicates that there is no mismatch or a mismatch cannot be proven.
  2599. NoMismatch,
  2600. /// Indicates that variable is initialized with mismatching form of \a new.
  2601. VarInitMismatches,
  2602. /// Indicates that member is initialized with mismatching form of \a new.
  2603. MemberInitMismatches,
  2604. /// Indicates that 1 or more constructors' definitions could not been
  2605. /// analyzed, and they will be checked again at the end of translation unit.
  2606. AnalyzeLater
  2607. };
  2608. /// \param EndOfTU True, if this is the final analysis at the end of
  2609. /// translation unit. False, if this is the initial analysis at the point
  2610. /// delete-expression was encountered.
  2611. explicit MismatchingNewDeleteDetector(bool EndOfTU)
  2612. : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
  2613. HasUndefinedConstructors(false) {}
  2614. /// Checks whether pointee of a delete-expression is initialized with
  2615. /// matching form of new-expression.
  2616. ///
  2617. /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
  2618. /// point where delete-expression is encountered, then a warning will be
  2619. /// issued immediately. If return value is \c AnalyzeLater at the point where
  2620. /// delete-expression is seen, then member will be analyzed at the end of
  2621. /// translation unit. \c AnalyzeLater is returned iff at least one constructor
  2622. /// couldn't be analyzed. If at least one constructor initializes the member
  2623. /// with matching type of new, the return value is \c NoMismatch.
  2624. MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
  2625. /// Analyzes a class member.
  2626. /// \param Field Class member to analyze.
  2627. /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
  2628. /// for deleting the \p Field.
  2629. MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
  2630. FieldDecl *Field;
  2631. /// List of mismatching new-expressions used for initialization of the pointee
  2632. llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
  2633. /// Indicates whether delete-expression was in array form.
  2634. bool IsArrayForm;
  2635. private:
  2636. const bool EndOfTU;
  2637. /// Indicates that there is at least one constructor without body.
  2638. bool HasUndefinedConstructors;
  2639. /// Returns \c CXXNewExpr from given initialization expression.
  2640. /// \param E Expression used for initializing pointee in delete-expression.
  2641. /// E can be a single-element \c InitListExpr consisting of new-expression.
  2642. const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
  2643. /// Returns whether member is initialized with mismatching form of
  2644. /// \c new either by the member initializer or in-class initialization.
  2645. ///
  2646. /// If bodies of all constructors are not visible at the end of translation
  2647. /// unit or at least one constructor initializes member with the matching
  2648. /// form of \c new, mismatch cannot be proven, and this function will return
  2649. /// \c NoMismatch.
  2650. MismatchResult analyzeMemberExpr(const MemberExpr *ME);
  2651. /// Returns whether variable is initialized with mismatching form of
  2652. /// \c new.
  2653. ///
  2654. /// If variable is initialized with matching form of \c new or variable is not
  2655. /// initialized with a \c new expression, this function will return true.
  2656. /// If variable is initialized with mismatching form of \c new, returns false.
  2657. /// \param D Variable to analyze.
  2658. bool hasMatchingVarInit(const DeclRefExpr *D);
  2659. /// Checks whether the constructor initializes pointee with mismatching
  2660. /// form of \c new.
  2661. ///
  2662. /// Returns true, if member is initialized with matching form of \c new in
  2663. /// member initializer list. Returns false, if member is initialized with the
  2664. /// matching form of \c new in this constructor's initializer or given
  2665. /// constructor isn't defined at the point where delete-expression is seen, or
  2666. /// member isn't initialized by the constructor.
  2667. bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
  2668. /// Checks whether member is initialized with matching form of
  2669. /// \c new in member initializer list.
  2670. bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
  2671. /// Checks whether member is initialized with mismatching form of \c new by
  2672. /// in-class initializer.
  2673. MismatchResult analyzeInClassInitializer();
  2674. };
  2675. }
  2676. MismatchingNewDeleteDetector::MismatchResult
  2677. MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
  2678. NewExprs.clear();
  2679. assert(DE && "Expected delete-expression");
  2680. IsArrayForm = DE->isArrayForm();
  2681. const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
  2682. if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
  2683. return analyzeMemberExpr(ME);
  2684. } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
  2685. if (!hasMatchingVarInit(D))
  2686. return VarInitMismatches;
  2687. }
  2688. return NoMismatch;
  2689. }
  2690. const CXXNewExpr *
  2691. MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
  2692. assert(E != nullptr && "Expected a valid initializer expression");
  2693. E = E->IgnoreParenImpCasts();
  2694. if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
  2695. if (ILE->getNumInits() == 1)
  2696. E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
  2697. }
  2698. return dyn_cast_or_null<const CXXNewExpr>(E);
  2699. }
  2700. bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
  2701. const CXXCtorInitializer *CI) {
  2702. const CXXNewExpr *NE = nullptr;
  2703. if (Field == CI->getMember() &&
  2704. (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
  2705. if (NE->isArray() == IsArrayForm)
  2706. return true;
  2707. else
  2708. NewExprs.push_back(NE);
  2709. }
  2710. return false;
  2711. }
  2712. bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
  2713. const CXXConstructorDecl *CD) {
  2714. if (CD->isImplicit())
  2715. return false;
  2716. const FunctionDecl *Definition = CD;
  2717. if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
  2718. HasUndefinedConstructors = true;
  2719. return EndOfTU;
  2720. }
  2721. for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
  2722. if (hasMatchingNewInCtorInit(CI))
  2723. return true;
  2724. }
  2725. return false;
  2726. }
  2727. MismatchingNewDeleteDetector::MismatchResult
  2728. MismatchingNewDeleteDetector::analyzeInClassInitializer() {
  2729. assert(Field != nullptr && "This should be called only for members");
  2730. const Expr *InitExpr = Field->getInClassInitializer();
  2731. if (!InitExpr)
  2732. return EndOfTU ? NoMismatch : AnalyzeLater;
  2733. if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
  2734. if (NE->isArray() != IsArrayForm) {
  2735. NewExprs.push_back(NE);
  2736. return MemberInitMismatches;
  2737. }
  2738. }
  2739. return NoMismatch;
  2740. }
  2741. MismatchingNewDeleteDetector::MismatchResult
  2742. MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
  2743. bool DeleteWasArrayForm) {
  2744. assert(Field != nullptr && "Analysis requires a valid class member.");
  2745. this->Field = Field;
  2746. IsArrayForm = DeleteWasArrayForm;
  2747. const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
  2748. for (const auto *CD : RD->ctors()) {
  2749. if (hasMatchingNewInCtor(CD))
  2750. return NoMismatch;
  2751. }
  2752. if (HasUndefinedConstructors)
  2753. return EndOfTU ? NoMismatch : AnalyzeLater;
  2754. if (!NewExprs.empty())
  2755. return MemberInitMismatches;
  2756. return Field->hasInClassInitializer() ? analyzeInClassInitializer()
  2757. : NoMismatch;
  2758. }
  2759. MismatchingNewDeleteDetector::MismatchResult
  2760. MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
  2761. assert(ME != nullptr && "Expected a member expression");
  2762. if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  2763. return analyzeField(F, IsArrayForm);
  2764. return NoMismatch;
  2765. }
  2766. bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
  2767. const CXXNewExpr *NE = nullptr;
  2768. if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
  2769. if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
  2770. NE->isArray() != IsArrayForm) {
  2771. NewExprs.push_back(NE);
  2772. }
  2773. }
  2774. return NewExprs.empty();
  2775. }
  2776. static void
  2777. DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
  2778. const MismatchingNewDeleteDetector &Detector) {
  2779. SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
  2780. FixItHint H;
  2781. if (!Detector.IsArrayForm)
  2782. H = FixItHint::CreateInsertion(EndOfDelete, "[]");
  2783. else {
  2784. SourceLocation RSquare = Lexer::findLocationAfterToken(
  2785. DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
  2786. SemaRef.getLangOpts(), true);
  2787. if (RSquare.isValid())
  2788. H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
  2789. }
  2790. SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
  2791. << Detector.IsArrayForm << H;
  2792. for (const auto *NE : Detector.NewExprs)
  2793. SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
  2794. << Detector.IsArrayForm;
  2795. }
  2796. void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
  2797. if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
  2798. return;
  2799. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
  2800. switch (Detector.analyzeDeleteExpr(DE)) {
  2801. case MismatchingNewDeleteDetector::VarInitMismatches:
  2802. case MismatchingNewDeleteDetector::MemberInitMismatches: {
  2803. DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
  2804. break;
  2805. }
  2806. case MismatchingNewDeleteDetector::AnalyzeLater: {
  2807. DeleteExprs[Detector.Field].push_back(
  2808. std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
  2809. break;
  2810. }
  2811. case MismatchingNewDeleteDetector::NoMismatch:
  2812. break;
  2813. }
  2814. }
  2815. void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
  2816. bool DeleteWasArrayForm) {
  2817. MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
  2818. switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
  2819. case MismatchingNewDeleteDetector::VarInitMismatches:
  2820. llvm_unreachable("This analysis should have been done for class members.");
  2821. case MismatchingNewDeleteDetector::AnalyzeLater:
  2822. llvm_unreachable("Analysis cannot be postponed any point beyond end of "
  2823. "translation unit.");
  2824. case MismatchingNewDeleteDetector::MemberInitMismatches:
  2825. DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
  2826. break;
  2827. case MismatchingNewDeleteDetector::NoMismatch:
  2828. break;
  2829. }
  2830. }
  2831. /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
  2832. /// @code ::delete ptr; @endcode
  2833. /// or
  2834. /// @code delete [] ptr; @endcode
  2835. ExprResult
  2836. Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
  2837. bool ArrayForm, Expr *ExE) {
  2838. // C++ [expr.delete]p1:
  2839. // The operand shall have a pointer type, or a class type having a single
  2840. // non-explicit conversion function to a pointer type. The result has type
  2841. // void.
  2842. //
  2843. // DR599 amends "pointer type" to "pointer to object type" in both cases.
  2844. ExprResult Ex = ExE;
  2845. FunctionDecl *OperatorDelete = nullptr;
  2846. bool ArrayFormAsWritten = ArrayForm;
  2847. bool UsualArrayDeleteWantsSize = false;
  2848. if (!Ex.get()->isTypeDependent()) {
  2849. // Perform lvalue-to-rvalue cast, if needed.
  2850. Ex = DefaultLvalueConversion(Ex.get());
  2851. if (Ex.isInvalid())
  2852. return ExprError();
  2853. QualType Type = Ex.get()->getType();
  2854. class DeleteConverter : public ContextualImplicitConverter {
  2855. public:
  2856. DeleteConverter() : ContextualImplicitConverter(false, true) {}
  2857. bool match(QualType ConvType) override {
  2858. // FIXME: If we have an operator T* and an operator void*, we must pick
  2859. // the operator T*.
  2860. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  2861. if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
  2862. return true;
  2863. return false;
  2864. }
  2865. SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
  2866. QualType T) override {
  2867. return S.Diag(Loc, diag::err_delete_operand) << T;
  2868. }
  2869. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  2870. QualType T) override {
  2871. return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
  2872. }
  2873. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  2874. QualType T,
  2875. QualType ConvTy) override {
  2876. return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
  2877. }
  2878. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  2879. QualType ConvTy) override {
  2880. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  2881. << ConvTy;
  2882. }
  2883. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  2884. QualType T) override {
  2885. return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
  2886. }
  2887. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  2888. QualType ConvTy) override {
  2889. return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
  2890. << ConvTy;
  2891. }
  2892. SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
  2893. QualType T,
  2894. QualType ConvTy) override {
  2895. llvm_unreachable("conversion functions are permitted");
  2896. }
  2897. } Converter;
  2898. Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
  2899. if (Ex.isInvalid())
  2900. return ExprError();
  2901. Type = Ex.get()->getType();
  2902. if (!Converter.match(Type))
  2903. // FIXME: PerformContextualImplicitConversion should return ExprError
  2904. // itself in this case.
  2905. return ExprError();
  2906. QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
  2907. QualType PointeeElem = Context.getBaseElementType(Pointee);
  2908. if (Pointee.getAddressSpace() != LangAS::Default &&
  2909. !getLangOpts().OpenCLCPlusPlus)
  2910. return Diag(Ex.get()->getBeginLoc(),
  2911. diag::err_address_space_qualified_delete)
  2912. << Pointee.getUnqualifiedType()
  2913. << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
  2914. CXXRecordDecl *PointeeRD = nullptr;
  2915. if (Pointee->isVoidType() && !isSFINAEContext()) {
  2916. // The C++ standard bans deleting a pointer to a non-object type, which
  2917. // effectively bans deletion of "void*". However, most compilers support
  2918. // this, so we treat it as a warning unless we're in a SFINAE context.
  2919. Diag(StartLoc, diag::ext_delete_void_ptr_operand)
  2920. << Type << Ex.get()->getSourceRange();
  2921. } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
  2922. return ExprError(Diag(StartLoc, diag::err_delete_operand)
  2923. << Type << Ex.get()->getSourceRange());
  2924. } else if (!Pointee->isDependentType()) {
  2925. // FIXME: This can result in errors if the definition was imported from a
  2926. // module but is hidden.
  2927. if (!RequireCompleteType(StartLoc, Pointee,
  2928. diag::warn_delete_incomplete, Ex.get())) {
  2929. if (const RecordType *RT = PointeeElem->getAs<RecordType>())
  2930. PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
  2931. }
  2932. }
  2933. if (Pointee->isArrayType() && !ArrayForm) {
  2934. Diag(StartLoc, diag::warn_delete_array_type)
  2935. << Type << Ex.get()->getSourceRange()
  2936. << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
  2937. ArrayForm = true;
  2938. }
  2939. DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
  2940. ArrayForm ? OO_Array_Delete : OO_Delete);
  2941. if (PointeeRD) {
  2942. if (!UseGlobal &&
  2943. FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
  2944. OperatorDelete))
  2945. return ExprError();
  2946. // If we're allocating an array of records, check whether the
  2947. // usual operator delete[] has a size_t parameter.
  2948. if (ArrayForm) {
  2949. // If the user specifically asked to use the global allocator,
  2950. // we'll need to do the lookup into the class.
  2951. if (UseGlobal)
  2952. UsualArrayDeleteWantsSize =
  2953. doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
  2954. // Otherwise, the usual operator delete[] should be the
  2955. // function we just found.
  2956. else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
  2957. UsualArrayDeleteWantsSize =
  2958. UsualDeallocFnInfo(*this,
  2959. DeclAccessPair::make(OperatorDelete, AS_public))
  2960. .HasSizeT;
  2961. }
  2962. if (!PointeeRD->hasIrrelevantDestructor())
  2963. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  2964. MarkFunctionReferenced(StartLoc,
  2965. const_cast<CXXDestructorDecl*>(Dtor));
  2966. if (DiagnoseUseOfDecl(Dtor, StartLoc))
  2967. return ExprError();
  2968. }
  2969. CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
  2970. /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
  2971. /*WarnOnNonAbstractTypes=*/!ArrayForm,
  2972. SourceLocation());
  2973. }
  2974. if (!OperatorDelete) {
  2975. if (getLangOpts().OpenCLCPlusPlus) {
  2976. Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
  2977. return ExprError();
  2978. }
  2979. bool IsComplete = isCompleteType(StartLoc, Pointee);
  2980. bool CanProvideSize =
  2981. IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
  2982. Pointee.isDestructedType());
  2983. bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
  2984. // Look for a global declaration.
  2985. OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
  2986. Overaligned, DeleteName);
  2987. }
  2988. MarkFunctionReferenced(StartLoc, OperatorDelete);
  2989. // Check access and ambiguity of destructor if we're going to call it.
  2990. // Note that this is required even for a virtual delete.
  2991. bool IsVirtualDelete = false;
  2992. if (PointeeRD) {
  2993. if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
  2994. CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
  2995. PDiag(diag::err_access_dtor) << PointeeElem);
  2996. IsVirtualDelete = Dtor->isVirtual();
  2997. }
  2998. }
  2999. DiagnoseUseOfDecl(OperatorDelete, StartLoc);
  3000. // Convert the operand to the type of the first parameter of operator
  3001. // delete. This is only necessary if we selected a destroying operator
  3002. // delete that we are going to call (non-virtually); converting to void*
  3003. // is trivial and left to AST consumers to handle.
  3004. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  3005. if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
  3006. Qualifiers Qs = Pointee.getQualifiers();
  3007. if (Qs.hasCVRQualifiers()) {
  3008. // Qualifiers are irrelevant to this conversion; we're only looking
  3009. // for access and ambiguity.
  3010. Qs.removeCVRQualifiers();
  3011. QualType Unqual = Context.getPointerType(
  3012. Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
  3013. Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
  3014. }
  3015. Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
  3016. if (Ex.isInvalid())
  3017. return ExprError();
  3018. }
  3019. }
  3020. CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
  3021. Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
  3022. UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
  3023. AnalyzeDeleteExprMismatch(Result);
  3024. return Result;
  3025. }
  3026. static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
  3027. bool IsDelete,
  3028. FunctionDecl *&Operator) {
  3029. DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
  3030. IsDelete ? OO_Delete : OO_New);
  3031. LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
  3032. S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
  3033. assert(!R.empty() && "implicitly declared allocation functions not found");
  3034. assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
  3035. // We do our own custom access checks below.
  3036. R.suppressDiagnostics();
  3037. SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
  3038. OverloadCandidateSet Candidates(R.getNameLoc(),
  3039. OverloadCandidateSet::CSK_Normal);
  3040. for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
  3041. FnOvl != FnOvlEnd; ++FnOvl) {
  3042. // Even member operator new/delete are implicitly treated as
  3043. // static, so don't use AddMemberCandidate.
  3044. NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
  3045. if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
  3046. S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
  3047. /*ExplicitTemplateArgs=*/nullptr, Args,
  3048. Candidates,
  3049. /*SuppressUserConversions=*/false);
  3050. continue;
  3051. }
  3052. FunctionDecl *Fn = cast<FunctionDecl>(D);
  3053. S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
  3054. /*SuppressUserConversions=*/false);
  3055. }
  3056. SourceRange Range = TheCall->getSourceRange();
  3057. // Do the resolution.
  3058. OverloadCandidateSet::iterator Best;
  3059. switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
  3060. case OR_Success: {
  3061. // Got one!
  3062. FunctionDecl *FnDecl = Best->Function;
  3063. assert(R.getNamingClass() == nullptr &&
  3064. "class members should not be considered");
  3065. if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
  3066. S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
  3067. << (IsDelete ? 1 : 0) << Range;
  3068. S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
  3069. << R.getLookupName() << FnDecl->getSourceRange();
  3070. return true;
  3071. }
  3072. Operator = FnDecl;
  3073. return false;
  3074. }
  3075. case OR_No_Viable_Function:
  3076. Candidates.NoteCandidates(
  3077. PartialDiagnosticAt(R.getNameLoc(),
  3078. S.PDiag(diag::err_ovl_no_viable_function_in_call)
  3079. << R.getLookupName() << Range),
  3080. S, OCD_AllCandidates, Args);
  3081. return true;
  3082. case OR_Ambiguous:
  3083. Candidates.NoteCandidates(
  3084. PartialDiagnosticAt(R.getNameLoc(),
  3085. S.PDiag(diag::err_ovl_ambiguous_call)
  3086. << R.getLookupName() << Range),
  3087. S, OCD_ViableCandidates, Args);
  3088. return true;
  3089. case OR_Deleted: {
  3090. Candidates.NoteCandidates(
  3091. PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
  3092. << R.getLookupName() << Range),
  3093. S, OCD_AllCandidates, Args);
  3094. return true;
  3095. }
  3096. }
  3097. llvm_unreachable("Unreachable, bad result from BestViableFunction");
  3098. }
  3099. ExprResult
  3100. Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
  3101. bool IsDelete) {
  3102. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  3103. if (!getLangOpts().CPlusPlus) {
  3104. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  3105. << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
  3106. << "C++";
  3107. return ExprError();
  3108. }
  3109. // CodeGen assumes it can find the global new and delete to call,
  3110. // so ensure that they are declared.
  3111. DeclareGlobalNewDelete();
  3112. FunctionDecl *OperatorNewOrDelete = nullptr;
  3113. if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
  3114. OperatorNewOrDelete))
  3115. return ExprError();
  3116. assert(OperatorNewOrDelete && "should be found");
  3117. DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
  3118. MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
  3119. TheCall->setType(OperatorNewOrDelete->getReturnType());
  3120. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  3121. QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
  3122. InitializedEntity Entity =
  3123. InitializedEntity::InitializeParameter(Context, ParamTy, false);
  3124. ExprResult Arg = PerformCopyInitialization(
  3125. Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
  3126. if (Arg.isInvalid())
  3127. return ExprError();
  3128. TheCall->setArg(i, Arg.get());
  3129. }
  3130. auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
  3131. assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
  3132. "Callee expected to be implicit cast to a builtin function pointer");
  3133. Callee->setType(OperatorNewOrDelete->getType());
  3134. return TheCallResult;
  3135. }
  3136. void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
  3137. bool IsDelete, bool CallCanBeVirtual,
  3138. bool WarnOnNonAbstractTypes,
  3139. SourceLocation DtorLoc) {
  3140. if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
  3141. return;
  3142. // C++ [expr.delete]p3:
  3143. // In the first alternative (delete object), if the static type of the
  3144. // object to be deleted is different from its dynamic type, the static
  3145. // type shall be a base class of the dynamic type of the object to be
  3146. // deleted and the static type shall have a virtual destructor or the
  3147. // behavior is undefined.
  3148. //
  3149. const CXXRecordDecl *PointeeRD = dtor->getParent();
  3150. // Note: a final class cannot be derived from, no issue there
  3151. if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
  3152. return;
  3153. // If the superclass is in a system header, there's nothing that can be done.
  3154. // The `delete` (where we emit the warning) can be in a system header,
  3155. // what matters for this warning is where the deleted type is defined.
  3156. if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
  3157. return;
  3158. QualType ClassType = dtor->getThisType()->getPointeeType();
  3159. if (PointeeRD->isAbstract()) {
  3160. // If the class is abstract, we warn by default, because we're
  3161. // sure the code has undefined behavior.
  3162. Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
  3163. << ClassType;
  3164. } else if (WarnOnNonAbstractTypes) {
  3165. // Otherwise, if this is not an array delete, it's a bit suspect,
  3166. // but not necessarily wrong.
  3167. Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
  3168. << ClassType;
  3169. }
  3170. if (!IsDelete) {
  3171. std::string TypeStr;
  3172. ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
  3173. Diag(DtorLoc, diag::note_delete_non_virtual)
  3174. << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
  3175. }
  3176. }
  3177. Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
  3178. SourceLocation StmtLoc,
  3179. ConditionKind CK) {
  3180. ExprResult E =
  3181. CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
  3182. if (E.isInvalid())
  3183. return ConditionError();
  3184. return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
  3185. CK == ConditionKind::ConstexprIf);
  3186. }
  3187. /// Check the use of the given variable as a C++ condition in an if,
  3188. /// while, do-while, or switch statement.
  3189. ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
  3190. SourceLocation StmtLoc,
  3191. ConditionKind CK) {
  3192. if (ConditionVar->isInvalidDecl())
  3193. return ExprError();
  3194. QualType T = ConditionVar->getType();
  3195. // C++ [stmt.select]p2:
  3196. // The declarator shall not specify a function or an array.
  3197. if (T->isFunctionType())
  3198. return ExprError(Diag(ConditionVar->getLocation(),
  3199. diag::err_invalid_use_of_function_type)
  3200. << ConditionVar->getSourceRange());
  3201. else if (T->isArrayType())
  3202. return ExprError(Diag(ConditionVar->getLocation(),
  3203. diag::err_invalid_use_of_array_type)
  3204. << ConditionVar->getSourceRange());
  3205. ExprResult Condition = BuildDeclRefExpr(
  3206. ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
  3207. ConditionVar->getLocation());
  3208. switch (CK) {
  3209. case ConditionKind::Boolean:
  3210. return CheckBooleanCondition(StmtLoc, Condition.get());
  3211. case ConditionKind::ConstexprIf:
  3212. return CheckBooleanCondition(StmtLoc, Condition.get(), true);
  3213. case ConditionKind::Switch:
  3214. return CheckSwitchCondition(StmtLoc, Condition.get());
  3215. }
  3216. llvm_unreachable("unexpected condition kind");
  3217. }
  3218. /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
  3219. ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
  3220. // C++ 6.4p4:
  3221. // The value of a condition that is an initialized declaration in a statement
  3222. // other than a switch statement is the value of the declared variable
  3223. // implicitly converted to type bool. If that conversion is ill-formed, the
  3224. // program is ill-formed.
  3225. // The value of a condition that is an expression is the value of the
  3226. // expression, implicitly converted to bool.
  3227. //
  3228. // FIXME: Return this value to the caller so they don't need to recompute it.
  3229. llvm::APSInt Value(/*BitWidth*/1);
  3230. return (IsConstexpr && !CondExpr->isValueDependent())
  3231. ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
  3232. CCEK_ConstexprIf)
  3233. : PerformContextuallyConvertToBool(CondExpr);
  3234. }
  3235. /// Helper function to determine whether this is the (deprecated) C++
  3236. /// conversion from a string literal to a pointer to non-const char or
  3237. /// non-const wchar_t (for narrow and wide string literals,
  3238. /// respectively).
  3239. bool
  3240. Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
  3241. // Look inside the implicit cast, if it exists.
  3242. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
  3243. From = Cast->getSubExpr();
  3244. // A string literal (2.13.4) that is not a wide string literal can
  3245. // be converted to an rvalue of type "pointer to char"; a wide
  3246. // string literal can be converted to an rvalue of type "pointer
  3247. // to wchar_t" (C++ 4.2p2).
  3248. if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
  3249. if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
  3250. if (const BuiltinType *ToPointeeType
  3251. = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
  3252. // This conversion is considered only when there is an
  3253. // explicit appropriate pointer target type (C++ 4.2p2).
  3254. if (!ToPtrType->getPointeeType().hasQualifiers()) {
  3255. switch (StrLit->getKind()) {
  3256. case StringLiteral::UTF8:
  3257. case StringLiteral::UTF16:
  3258. case StringLiteral::UTF32:
  3259. // We don't allow UTF literals to be implicitly converted
  3260. break;
  3261. case StringLiteral::Ascii:
  3262. return (ToPointeeType->getKind() == BuiltinType::Char_U ||
  3263. ToPointeeType->getKind() == BuiltinType::Char_S);
  3264. case StringLiteral::Wide:
  3265. return Context.typesAreCompatible(Context.getWideCharType(),
  3266. QualType(ToPointeeType, 0));
  3267. }
  3268. }
  3269. }
  3270. return false;
  3271. }
  3272. static ExprResult BuildCXXCastArgument(Sema &S,
  3273. SourceLocation CastLoc,
  3274. QualType Ty,
  3275. CastKind Kind,
  3276. CXXMethodDecl *Method,
  3277. DeclAccessPair FoundDecl,
  3278. bool HadMultipleCandidates,
  3279. Expr *From) {
  3280. switch (Kind) {
  3281. default: llvm_unreachable("Unhandled cast kind!");
  3282. case CK_ConstructorConversion: {
  3283. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
  3284. SmallVector<Expr*, 8> ConstructorArgs;
  3285. if (S.RequireNonAbstractType(CastLoc, Ty,
  3286. diag::err_allocation_of_abstract_type))
  3287. return ExprError();
  3288. if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
  3289. return ExprError();
  3290. S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
  3291. InitializedEntity::InitializeTemporary(Ty));
  3292. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  3293. return ExprError();
  3294. ExprResult Result = S.BuildCXXConstructExpr(
  3295. CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
  3296. ConstructorArgs, HadMultipleCandidates,
  3297. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3298. CXXConstructExpr::CK_Complete, SourceRange());
  3299. if (Result.isInvalid())
  3300. return ExprError();
  3301. return S.MaybeBindToTemporary(Result.getAs<Expr>());
  3302. }
  3303. case CK_UserDefinedConversion: {
  3304. assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
  3305. S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
  3306. if (S.DiagnoseUseOfDecl(Method, CastLoc))
  3307. return ExprError();
  3308. // Create an implicit call expr that calls it.
  3309. CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
  3310. ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
  3311. HadMultipleCandidates);
  3312. if (Result.isInvalid())
  3313. return ExprError();
  3314. // Record usage of conversion in an implicit cast.
  3315. Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
  3316. CK_UserDefinedConversion, Result.get(),
  3317. nullptr, Result.get()->getValueKind());
  3318. return S.MaybeBindToTemporary(Result.get());
  3319. }
  3320. }
  3321. }
  3322. /// PerformImplicitConversion - Perform an implicit conversion of the
  3323. /// expression From to the type ToType using the pre-computed implicit
  3324. /// conversion sequence ICS. Returns the converted
  3325. /// expression. Action is the kind of conversion we're performing,
  3326. /// used in the error message.
  3327. ExprResult
  3328. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  3329. const ImplicitConversionSequence &ICS,
  3330. AssignmentAction Action,
  3331. CheckedConversionKind CCK) {
  3332. // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
  3333. if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
  3334. return From;
  3335. switch (ICS.getKind()) {
  3336. case ImplicitConversionSequence::StandardConversion: {
  3337. ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
  3338. Action, CCK);
  3339. if (Res.isInvalid())
  3340. return ExprError();
  3341. From = Res.get();
  3342. break;
  3343. }
  3344. case ImplicitConversionSequence::UserDefinedConversion: {
  3345. FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
  3346. CastKind CastKind;
  3347. QualType BeforeToType;
  3348. assert(FD && "no conversion function for user-defined conversion seq");
  3349. if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
  3350. CastKind = CK_UserDefinedConversion;
  3351. // If the user-defined conversion is specified by a conversion function,
  3352. // the initial standard conversion sequence converts the source type to
  3353. // the implicit object parameter of the conversion function.
  3354. BeforeToType = Context.getTagDeclType(Conv->getParent());
  3355. } else {
  3356. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
  3357. CastKind = CK_ConstructorConversion;
  3358. // Do no conversion if dealing with ... for the first conversion.
  3359. if (!ICS.UserDefined.EllipsisConversion) {
  3360. // If the user-defined conversion is specified by a constructor, the
  3361. // initial standard conversion sequence converts the source type to
  3362. // the type required by the argument of the constructor
  3363. BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
  3364. }
  3365. }
  3366. // Watch out for ellipsis conversion.
  3367. if (!ICS.UserDefined.EllipsisConversion) {
  3368. ExprResult Res =
  3369. PerformImplicitConversion(From, BeforeToType,
  3370. ICS.UserDefined.Before, AA_Converting,
  3371. CCK);
  3372. if (Res.isInvalid())
  3373. return ExprError();
  3374. From = Res.get();
  3375. }
  3376. ExprResult CastArg = BuildCXXCastArgument(
  3377. *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
  3378. cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
  3379. ICS.UserDefined.HadMultipleCandidates, From);
  3380. if (CastArg.isInvalid())
  3381. return ExprError();
  3382. From = CastArg.get();
  3383. // C++ [over.match.oper]p7:
  3384. // [...] the second standard conversion sequence of a user-defined
  3385. // conversion sequence is not applied.
  3386. if (CCK == CCK_ForBuiltinOverloadedOp)
  3387. return From;
  3388. return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
  3389. AA_Converting, CCK);
  3390. }
  3391. case ImplicitConversionSequence::AmbiguousConversion:
  3392. ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
  3393. PDiag(diag::err_typecheck_ambiguous_condition)
  3394. << From->getSourceRange());
  3395. return ExprError();
  3396. case ImplicitConversionSequence::EllipsisConversion:
  3397. llvm_unreachable("Cannot perform an ellipsis conversion");
  3398. case ImplicitConversionSequence::BadConversion:
  3399. bool Diagnosed =
  3400. DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
  3401. From->getType(), From, Action);
  3402. assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
  3403. return ExprError();
  3404. }
  3405. // Everything went well.
  3406. return From;
  3407. }
  3408. /// PerformImplicitConversion - Perform an implicit conversion of the
  3409. /// expression From to the type ToType by following the standard
  3410. /// conversion sequence SCS. Returns the converted
  3411. /// expression. Flavor is the context in which we're performing this
  3412. /// conversion, for use in error messages.
  3413. ExprResult
  3414. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  3415. const StandardConversionSequence& SCS,
  3416. AssignmentAction Action,
  3417. CheckedConversionKind CCK) {
  3418. bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
  3419. // Overall FIXME: we are recomputing too many types here and doing far too
  3420. // much extra work. What this means is that we need to keep track of more
  3421. // information that is computed when we try the implicit conversion initially,
  3422. // so that we don't need to recompute anything here.
  3423. QualType FromType = From->getType();
  3424. if (SCS.CopyConstructor) {
  3425. // FIXME: When can ToType be a reference type?
  3426. assert(!ToType->isReferenceType());
  3427. if (SCS.Second == ICK_Derived_To_Base) {
  3428. SmallVector<Expr*, 8> ConstructorArgs;
  3429. if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
  3430. From, /*FIXME:ConstructLoc*/SourceLocation(),
  3431. ConstructorArgs))
  3432. return ExprError();
  3433. return BuildCXXConstructExpr(
  3434. /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
  3435. SCS.FoundCopyConstructor, SCS.CopyConstructor,
  3436. ConstructorArgs, /*HadMultipleCandidates*/ false,
  3437. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3438. CXXConstructExpr::CK_Complete, SourceRange());
  3439. }
  3440. return BuildCXXConstructExpr(
  3441. /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
  3442. SCS.FoundCopyConstructor, SCS.CopyConstructor,
  3443. From, /*HadMultipleCandidates*/ false,
  3444. /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
  3445. CXXConstructExpr::CK_Complete, SourceRange());
  3446. }
  3447. // Resolve overloaded function references.
  3448. if (Context.hasSameType(FromType, Context.OverloadTy)) {
  3449. DeclAccessPair Found;
  3450. FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
  3451. true, Found);
  3452. if (!Fn)
  3453. return ExprError();
  3454. if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
  3455. return ExprError();
  3456. From = FixOverloadedFunctionReference(From, Found, Fn);
  3457. FromType = From->getType();
  3458. }
  3459. // If we're converting to an atomic type, first convert to the corresponding
  3460. // non-atomic type.
  3461. QualType ToAtomicType;
  3462. if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
  3463. ToAtomicType = ToType;
  3464. ToType = ToAtomic->getValueType();
  3465. }
  3466. QualType InitialFromType = FromType;
  3467. // Perform the first implicit conversion.
  3468. switch (SCS.First) {
  3469. case ICK_Identity:
  3470. if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
  3471. FromType = FromAtomic->getValueType().getUnqualifiedType();
  3472. From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
  3473. From, /*BasePath=*/nullptr, VK_RValue);
  3474. }
  3475. break;
  3476. case ICK_Lvalue_To_Rvalue: {
  3477. assert(From->getObjectKind() != OK_ObjCProperty);
  3478. ExprResult FromRes = DefaultLvalueConversion(From);
  3479. assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
  3480. From = FromRes.get();
  3481. FromType = From->getType();
  3482. break;
  3483. }
  3484. case ICK_Array_To_Pointer:
  3485. FromType = Context.getArrayDecayedType(FromType);
  3486. From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
  3487. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3488. break;
  3489. case ICK_Function_To_Pointer:
  3490. FromType = Context.getPointerType(FromType);
  3491. From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
  3492. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3493. break;
  3494. default:
  3495. llvm_unreachable("Improper first standard conversion");
  3496. }
  3497. // Perform the second implicit conversion
  3498. switch (SCS.Second) {
  3499. case ICK_Identity:
  3500. // C++ [except.spec]p5:
  3501. // [For] assignment to and initialization of pointers to functions,
  3502. // pointers to member functions, and references to functions: the
  3503. // target entity shall allow at least the exceptions allowed by the
  3504. // source value in the assignment or initialization.
  3505. switch (Action) {
  3506. case AA_Assigning:
  3507. case AA_Initializing:
  3508. // Note, function argument passing and returning are initialization.
  3509. case AA_Passing:
  3510. case AA_Returning:
  3511. case AA_Sending:
  3512. case AA_Passing_CFAudited:
  3513. if (CheckExceptionSpecCompatibility(From, ToType))
  3514. return ExprError();
  3515. break;
  3516. case AA_Casting:
  3517. case AA_Converting:
  3518. // Casts and implicit conversions are not initialization, so are not
  3519. // checked for exception specification mismatches.
  3520. break;
  3521. }
  3522. // Nothing else to do.
  3523. break;
  3524. case ICK_Integral_Promotion:
  3525. case ICK_Integral_Conversion:
  3526. if (ToType->isBooleanType()) {
  3527. assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
  3528. SCS.Second == ICK_Integral_Promotion &&
  3529. "only enums with fixed underlying type can promote to bool");
  3530. From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
  3531. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3532. } else {
  3533. From = ImpCastExprToType(From, ToType, CK_IntegralCast,
  3534. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3535. }
  3536. break;
  3537. case ICK_Floating_Promotion:
  3538. case ICK_Floating_Conversion:
  3539. From = ImpCastExprToType(From, ToType, CK_FloatingCast,
  3540. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3541. break;
  3542. case ICK_Complex_Promotion:
  3543. case ICK_Complex_Conversion: {
  3544. QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
  3545. QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
  3546. CastKind CK;
  3547. if (FromEl->isRealFloatingType()) {
  3548. if (ToEl->isRealFloatingType())
  3549. CK = CK_FloatingComplexCast;
  3550. else
  3551. CK = CK_FloatingComplexToIntegralComplex;
  3552. } else if (ToEl->isRealFloatingType()) {
  3553. CK = CK_IntegralComplexToFloatingComplex;
  3554. } else {
  3555. CK = CK_IntegralComplexCast;
  3556. }
  3557. From = ImpCastExprToType(From, ToType, CK,
  3558. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3559. break;
  3560. }
  3561. case ICK_Floating_Integral:
  3562. if (ToType->isRealFloatingType())
  3563. From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
  3564. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3565. else
  3566. From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
  3567. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3568. break;
  3569. case ICK_Compatible_Conversion:
  3570. From = ImpCastExprToType(From, ToType, CK_NoOp,
  3571. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3572. break;
  3573. case ICK_Writeback_Conversion:
  3574. case ICK_Pointer_Conversion: {
  3575. if (SCS.IncompatibleObjC && Action != AA_Casting) {
  3576. // Diagnose incompatible Objective-C conversions
  3577. if (Action == AA_Initializing || Action == AA_Assigning)
  3578. Diag(From->getBeginLoc(),
  3579. diag::ext_typecheck_convert_incompatible_pointer)
  3580. << ToType << From->getType() << Action << From->getSourceRange()
  3581. << 0;
  3582. else
  3583. Diag(From->getBeginLoc(),
  3584. diag::ext_typecheck_convert_incompatible_pointer)
  3585. << From->getType() << ToType << Action << From->getSourceRange()
  3586. << 0;
  3587. if (From->getType()->isObjCObjectPointerType() &&
  3588. ToType->isObjCObjectPointerType())
  3589. EmitRelatedResultTypeNote(From);
  3590. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  3591. !CheckObjCARCUnavailableWeakConversion(ToType,
  3592. From->getType())) {
  3593. if (Action == AA_Initializing)
  3594. Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
  3595. else
  3596. Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
  3597. << (Action == AA_Casting) << From->getType() << ToType
  3598. << From->getSourceRange();
  3599. }
  3600. CastKind Kind;
  3601. CXXCastPath BasePath;
  3602. if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
  3603. return ExprError();
  3604. // Make sure we extend blocks if necessary.
  3605. // FIXME: doing this here is really ugly.
  3606. if (Kind == CK_BlockPointerToObjCPointerCast) {
  3607. ExprResult E = From;
  3608. (void) PrepareCastToObjCObjectPointer(E);
  3609. From = E.get();
  3610. }
  3611. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  3612. CheckObjCConversion(SourceRange(), ToType, From, CCK);
  3613. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  3614. .get();
  3615. break;
  3616. }
  3617. case ICK_Pointer_Member: {
  3618. CastKind Kind;
  3619. CXXCastPath BasePath;
  3620. if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
  3621. return ExprError();
  3622. if (CheckExceptionSpecCompatibility(From, ToType))
  3623. return ExprError();
  3624. // We may not have been able to figure out what this member pointer resolved
  3625. // to up until this exact point. Attempt to lock-in it's inheritance model.
  3626. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3627. (void)isCompleteType(From->getExprLoc(), From->getType());
  3628. (void)isCompleteType(From->getExprLoc(), ToType);
  3629. }
  3630. From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
  3631. .get();
  3632. break;
  3633. }
  3634. case ICK_Boolean_Conversion:
  3635. // Perform half-to-boolean conversion via float.
  3636. if (From->getType()->isHalfType()) {
  3637. From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
  3638. FromType = Context.FloatTy;
  3639. }
  3640. From = ImpCastExprToType(From, Context.BoolTy,
  3641. ScalarTypeToBooleanCastKind(FromType),
  3642. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3643. break;
  3644. case ICK_Derived_To_Base: {
  3645. CXXCastPath BasePath;
  3646. if (CheckDerivedToBaseConversion(
  3647. From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
  3648. From->getSourceRange(), &BasePath, CStyle))
  3649. return ExprError();
  3650. From = ImpCastExprToType(From, ToType.getNonReferenceType(),
  3651. CK_DerivedToBase, From->getValueKind(),
  3652. &BasePath, CCK).get();
  3653. break;
  3654. }
  3655. case ICK_Vector_Conversion:
  3656. From = ImpCastExprToType(From, ToType, CK_BitCast,
  3657. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3658. break;
  3659. case ICK_Vector_Splat: {
  3660. // Vector splat from any arithmetic type to a vector.
  3661. Expr *Elem = prepareVectorSplat(ToType, From).get();
  3662. From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
  3663. /*BasePath=*/nullptr, CCK).get();
  3664. break;
  3665. }
  3666. case ICK_Complex_Real:
  3667. // Case 1. x -> _Complex y
  3668. if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
  3669. QualType ElType = ToComplex->getElementType();
  3670. bool isFloatingComplex = ElType->isRealFloatingType();
  3671. // x -> y
  3672. if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
  3673. // do nothing
  3674. } else if (From->getType()->isRealFloatingType()) {
  3675. From = ImpCastExprToType(From, ElType,
  3676. isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
  3677. } else {
  3678. assert(From->getType()->isIntegerType());
  3679. From = ImpCastExprToType(From, ElType,
  3680. isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
  3681. }
  3682. // y -> _Complex y
  3683. From = ImpCastExprToType(From, ToType,
  3684. isFloatingComplex ? CK_FloatingRealToComplex
  3685. : CK_IntegralRealToComplex).get();
  3686. // Case 2. _Complex x -> y
  3687. } else {
  3688. const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
  3689. assert(FromComplex);
  3690. QualType ElType = FromComplex->getElementType();
  3691. bool isFloatingComplex = ElType->isRealFloatingType();
  3692. // _Complex x -> x
  3693. From = ImpCastExprToType(From, ElType,
  3694. isFloatingComplex ? CK_FloatingComplexToReal
  3695. : CK_IntegralComplexToReal,
  3696. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3697. // x -> y
  3698. if (Context.hasSameUnqualifiedType(ElType, ToType)) {
  3699. // do nothing
  3700. } else if (ToType->isRealFloatingType()) {
  3701. From = ImpCastExprToType(From, ToType,
  3702. isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
  3703. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3704. } else {
  3705. assert(ToType->isIntegerType());
  3706. From = ImpCastExprToType(From, ToType,
  3707. isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
  3708. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3709. }
  3710. }
  3711. break;
  3712. case ICK_Block_Pointer_Conversion: {
  3713. LangAS AddrSpaceL =
  3714. ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
  3715. LangAS AddrSpaceR =
  3716. FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
  3717. assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
  3718. "Invalid cast");
  3719. CastKind Kind =
  3720. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  3721. From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
  3722. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3723. break;
  3724. }
  3725. case ICK_TransparentUnionConversion: {
  3726. ExprResult FromRes = From;
  3727. Sema::AssignConvertType ConvTy =
  3728. CheckTransparentUnionArgumentConstraints(ToType, FromRes);
  3729. if (FromRes.isInvalid())
  3730. return ExprError();
  3731. From = FromRes.get();
  3732. assert ((ConvTy == Sema::Compatible) &&
  3733. "Improper transparent union conversion");
  3734. (void)ConvTy;
  3735. break;
  3736. }
  3737. case ICK_Zero_Event_Conversion:
  3738. case ICK_Zero_Queue_Conversion:
  3739. From = ImpCastExprToType(From, ToType,
  3740. CK_ZeroToOCLOpaqueType,
  3741. From->getValueKind()).get();
  3742. break;
  3743. case ICK_Lvalue_To_Rvalue:
  3744. case ICK_Array_To_Pointer:
  3745. case ICK_Function_To_Pointer:
  3746. case ICK_Function_Conversion:
  3747. case ICK_Qualification:
  3748. case ICK_Num_Conversion_Kinds:
  3749. case ICK_C_Only_Conversion:
  3750. case ICK_Incompatible_Pointer_Conversion:
  3751. llvm_unreachable("Improper second standard conversion");
  3752. }
  3753. switch (SCS.Third) {
  3754. case ICK_Identity:
  3755. // Nothing to do.
  3756. break;
  3757. case ICK_Function_Conversion:
  3758. // If both sides are functions (or pointers/references to them), there could
  3759. // be incompatible exception declarations.
  3760. if (CheckExceptionSpecCompatibility(From, ToType))
  3761. return ExprError();
  3762. From = ImpCastExprToType(From, ToType, CK_NoOp,
  3763. VK_RValue, /*BasePath=*/nullptr, CCK).get();
  3764. break;
  3765. case ICK_Qualification: {
  3766. // The qualification keeps the category of the inner expression, unless the
  3767. // target type isn't a reference.
  3768. ExprValueKind VK =
  3769. ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
  3770. CastKind CK = CK_NoOp;
  3771. if (ToType->isReferenceType() &&
  3772. ToType->getPointeeType().getAddressSpace() !=
  3773. From->getType().getAddressSpace())
  3774. CK = CK_AddressSpaceConversion;
  3775. if (ToType->isPointerType() &&
  3776. ToType->getPointeeType().getAddressSpace() !=
  3777. From->getType()->getPointeeType().getAddressSpace())
  3778. CK = CK_AddressSpaceConversion;
  3779. From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
  3780. /*BasePath=*/nullptr, CCK)
  3781. .get();
  3782. if (SCS.DeprecatedStringLiteralToCharPtr &&
  3783. !getLangOpts().WritableStrings) {
  3784. Diag(From->getBeginLoc(),
  3785. getLangOpts().CPlusPlus11
  3786. ? diag::ext_deprecated_string_literal_conversion
  3787. : diag::warn_deprecated_string_literal_conversion)
  3788. << ToType.getNonReferenceType();
  3789. }
  3790. break;
  3791. }
  3792. default:
  3793. llvm_unreachable("Improper third standard conversion");
  3794. }
  3795. // If this conversion sequence involved a scalar -> atomic conversion, perform
  3796. // that conversion now.
  3797. if (!ToAtomicType.isNull()) {
  3798. assert(Context.hasSameType(
  3799. ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
  3800. From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
  3801. VK_RValue, nullptr, CCK).get();
  3802. }
  3803. // If this conversion sequence succeeded and involved implicitly converting a
  3804. // _Nullable type to a _Nonnull one, complain.
  3805. if (!isCast(CCK))
  3806. diagnoseNullableToNonnullConversion(ToType, InitialFromType,
  3807. From->getBeginLoc());
  3808. return From;
  3809. }
  3810. /// Check the completeness of a type in a unary type trait.
  3811. ///
  3812. /// If the particular type trait requires a complete type, tries to complete
  3813. /// it. If completing the type fails, a diagnostic is emitted and false
  3814. /// returned. If completing the type succeeds or no completion was required,
  3815. /// returns true.
  3816. static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
  3817. SourceLocation Loc,
  3818. QualType ArgTy) {
  3819. // C++0x [meta.unary.prop]p3:
  3820. // For all of the class templates X declared in this Clause, instantiating
  3821. // that template with a template argument that is a class template
  3822. // specialization may result in the implicit instantiation of the template
  3823. // argument if and only if the semantics of X require that the argument
  3824. // must be a complete type.
  3825. // We apply this rule to all the type trait expressions used to implement
  3826. // these class templates. We also try to follow any GCC documented behavior
  3827. // in these expressions to ensure portability of standard libraries.
  3828. switch (UTT) {
  3829. default: llvm_unreachable("not a UTT");
  3830. // is_complete_type somewhat obviously cannot require a complete type.
  3831. case UTT_IsCompleteType:
  3832. // Fall-through
  3833. // These traits are modeled on the type predicates in C++0x
  3834. // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
  3835. // requiring a complete type, as whether or not they return true cannot be
  3836. // impacted by the completeness of the type.
  3837. case UTT_IsVoid:
  3838. case UTT_IsIntegral:
  3839. case UTT_IsFloatingPoint:
  3840. case UTT_IsArray:
  3841. case UTT_IsPointer:
  3842. case UTT_IsLvalueReference:
  3843. case UTT_IsRvalueReference:
  3844. case UTT_IsMemberFunctionPointer:
  3845. case UTT_IsMemberObjectPointer:
  3846. case UTT_IsEnum:
  3847. case UTT_IsUnion:
  3848. case UTT_IsClass:
  3849. case UTT_IsFunction:
  3850. case UTT_IsReference:
  3851. case UTT_IsArithmetic:
  3852. case UTT_IsFundamental:
  3853. case UTT_IsObject:
  3854. case UTT_IsScalar:
  3855. case UTT_IsCompound:
  3856. case UTT_IsMemberPointer:
  3857. // Fall-through
  3858. // These traits are modeled on type predicates in C++0x [meta.unary.prop]
  3859. // which requires some of its traits to have the complete type. However,
  3860. // the completeness of the type cannot impact these traits' semantics, and
  3861. // so they don't require it. This matches the comments on these traits in
  3862. // Table 49.
  3863. case UTT_IsConst:
  3864. case UTT_IsVolatile:
  3865. case UTT_IsSigned:
  3866. case UTT_IsUnsigned:
  3867. // This type trait always returns false, checking the type is moot.
  3868. case UTT_IsInterfaceClass:
  3869. return true;
  3870. // C++14 [meta.unary.prop]:
  3871. // If T is a non-union class type, T shall be a complete type.
  3872. case UTT_IsEmpty:
  3873. case UTT_IsPolymorphic:
  3874. case UTT_IsAbstract:
  3875. if (const auto *RD = ArgTy->getAsCXXRecordDecl())
  3876. if (!RD->isUnion())
  3877. return !S.RequireCompleteType(
  3878. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  3879. return true;
  3880. // C++14 [meta.unary.prop]:
  3881. // If T is a class type, T shall be a complete type.
  3882. case UTT_IsFinal:
  3883. case UTT_IsSealed:
  3884. if (ArgTy->getAsCXXRecordDecl())
  3885. return !S.RequireCompleteType(
  3886. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  3887. return true;
  3888. // C++1z [meta.unary.prop]:
  3889. // remove_all_extents_t<T> shall be a complete type or cv void.
  3890. case UTT_IsAggregate:
  3891. case UTT_IsTrivial:
  3892. case UTT_IsTriviallyCopyable:
  3893. case UTT_IsStandardLayout:
  3894. case UTT_IsPOD:
  3895. case UTT_IsLiteral:
  3896. // Per the GCC type traits documentation, T shall be a complete type, cv void,
  3897. // or an array of unknown bound. But GCC actually imposes the same constraints
  3898. // as above.
  3899. case UTT_HasNothrowAssign:
  3900. case UTT_HasNothrowMoveAssign:
  3901. case UTT_HasNothrowConstructor:
  3902. case UTT_HasNothrowCopy:
  3903. case UTT_HasTrivialAssign:
  3904. case UTT_HasTrivialMoveAssign:
  3905. case UTT_HasTrivialDefaultConstructor:
  3906. case UTT_HasTrivialMoveConstructor:
  3907. case UTT_HasTrivialCopy:
  3908. case UTT_HasTrivialDestructor:
  3909. case UTT_HasVirtualDestructor:
  3910. ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
  3911. LLVM_FALLTHROUGH;
  3912. // C++1z [meta.unary.prop]:
  3913. // T shall be a complete type, cv void, or an array of unknown bound.
  3914. case UTT_IsDestructible:
  3915. case UTT_IsNothrowDestructible:
  3916. case UTT_IsTriviallyDestructible:
  3917. case UTT_HasUniqueObjectRepresentations:
  3918. if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
  3919. return true;
  3920. return !S.RequireCompleteType(
  3921. Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
  3922. }
  3923. }
  3924. static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
  3925. Sema &Self, SourceLocation KeyLoc, ASTContext &C,
  3926. bool (CXXRecordDecl::*HasTrivial)() const,
  3927. bool (CXXRecordDecl::*HasNonTrivial)() const,
  3928. bool (CXXMethodDecl::*IsDesiredOp)() const)
  3929. {
  3930. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3931. if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
  3932. return true;
  3933. DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
  3934. DeclarationNameInfo NameInfo(Name, KeyLoc);
  3935. LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
  3936. if (Self.LookupQualifiedName(Res, RD)) {
  3937. bool FoundOperator = false;
  3938. Res.suppressDiagnostics();
  3939. for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
  3940. Op != OpEnd; ++Op) {
  3941. if (isa<FunctionTemplateDecl>(*Op))
  3942. continue;
  3943. CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
  3944. if((Operator->*IsDesiredOp)()) {
  3945. FoundOperator = true;
  3946. const FunctionProtoType *CPT =
  3947. Operator->getType()->getAs<FunctionProtoType>();
  3948. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  3949. if (!CPT || !CPT->isNothrow())
  3950. return false;
  3951. }
  3952. }
  3953. return FoundOperator;
  3954. }
  3955. return false;
  3956. }
  3957. static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
  3958. SourceLocation KeyLoc, QualType T) {
  3959. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  3960. ASTContext &C = Self.Context;
  3961. switch(UTT) {
  3962. default: llvm_unreachable("not a UTT");
  3963. // Type trait expressions corresponding to the primary type category
  3964. // predicates in C++0x [meta.unary.cat].
  3965. case UTT_IsVoid:
  3966. return T->isVoidType();
  3967. case UTT_IsIntegral:
  3968. return T->isIntegralType(C);
  3969. case UTT_IsFloatingPoint:
  3970. return T->isFloatingType();
  3971. case UTT_IsArray:
  3972. return T->isArrayType();
  3973. case UTT_IsPointer:
  3974. return T->isPointerType();
  3975. case UTT_IsLvalueReference:
  3976. return T->isLValueReferenceType();
  3977. case UTT_IsRvalueReference:
  3978. return T->isRValueReferenceType();
  3979. case UTT_IsMemberFunctionPointer:
  3980. return T->isMemberFunctionPointerType();
  3981. case UTT_IsMemberObjectPointer:
  3982. return T->isMemberDataPointerType();
  3983. case UTT_IsEnum:
  3984. return T->isEnumeralType();
  3985. case UTT_IsUnion:
  3986. return T->isUnionType();
  3987. case UTT_IsClass:
  3988. return T->isClassType() || T->isStructureType() || T->isInterfaceType();
  3989. case UTT_IsFunction:
  3990. return T->isFunctionType();
  3991. // Type trait expressions which correspond to the convenient composition
  3992. // predicates in C++0x [meta.unary.comp].
  3993. case UTT_IsReference:
  3994. return T->isReferenceType();
  3995. case UTT_IsArithmetic:
  3996. return T->isArithmeticType() && !T->isEnumeralType();
  3997. case UTT_IsFundamental:
  3998. return T->isFundamentalType();
  3999. case UTT_IsObject:
  4000. return T->isObjectType();
  4001. case UTT_IsScalar:
  4002. // Note: semantic analysis depends on Objective-C lifetime types to be
  4003. // considered scalar types. However, such types do not actually behave
  4004. // like scalar types at run time (since they may require retain/release
  4005. // operations), so we report them as non-scalar.
  4006. if (T->isObjCLifetimeType()) {
  4007. switch (T.getObjCLifetime()) {
  4008. case Qualifiers::OCL_None:
  4009. case Qualifiers::OCL_ExplicitNone:
  4010. return true;
  4011. case Qualifiers::OCL_Strong:
  4012. case Qualifiers::OCL_Weak:
  4013. case Qualifiers::OCL_Autoreleasing:
  4014. return false;
  4015. }
  4016. }
  4017. return T->isScalarType();
  4018. case UTT_IsCompound:
  4019. return T->isCompoundType();
  4020. case UTT_IsMemberPointer:
  4021. return T->isMemberPointerType();
  4022. // Type trait expressions which correspond to the type property predicates
  4023. // in C++0x [meta.unary.prop].
  4024. case UTT_IsConst:
  4025. return T.isConstQualified();
  4026. case UTT_IsVolatile:
  4027. return T.isVolatileQualified();
  4028. case UTT_IsTrivial:
  4029. return T.isTrivialType(C);
  4030. case UTT_IsTriviallyCopyable:
  4031. return T.isTriviallyCopyableType(C);
  4032. case UTT_IsStandardLayout:
  4033. return T->isStandardLayoutType();
  4034. case UTT_IsPOD:
  4035. return T.isPODType(C);
  4036. case UTT_IsLiteral:
  4037. return T->isLiteralType(C);
  4038. case UTT_IsEmpty:
  4039. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4040. return !RD->isUnion() && RD->isEmpty();
  4041. return false;
  4042. case UTT_IsPolymorphic:
  4043. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4044. return !RD->isUnion() && RD->isPolymorphic();
  4045. return false;
  4046. case UTT_IsAbstract:
  4047. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4048. return !RD->isUnion() && RD->isAbstract();
  4049. return false;
  4050. case UTT_IsAggregate:
  4051. // Report vector extensions and complex types as aggregates because they
  4052. // support aggregate initialization. GCC mirrors this behavior for vectors
  4053. // but not _Complex.
  4054. return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
  4055. T->isAnyComplexType();
  4056. // __is_interface_class only returns true when CL is invoked in /CLR mode and
  4057. // even then only when it is used with the 'interface struct ...' syntax
  4058. // Clang doesn't support /CLR which makes this type trait moot.
  4059. case UTT_IsInterfaceClass:
  4060. return false;
  4061. case UTT_IsFinal:
  4062. case UTT_IsSealed:
  4063. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4064. return RD->hasAttr<FinalAttr>();
  4065. return false;
  4066. case UTT_IsSigned:
  4067. // Enum types should always return false.
  4068. // Floating points should always return true.
  4069. return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
  4070. case UTT_IsUnsigned:
  4071. return T->isUnsignedIntegerType();
  4072. // Type trait expressions which query classes regarding their construction,
  4073. // destruction, and copying. Rather than being based directly on the
  4074. // related type predicates in the standard, they are specified by both
  4075. // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
  4076. // specifications.
  4077. //
  4078. // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
  4079. // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  4080. //
  4081. // Note that these builtins do not behave as documented in g++: if a class
  4082. // has both a trivial and a non-trivial special member of a particular kind,
  4083. // they return false! For now, we emulate this behavior.
  4084. // FIXME: This appears to be a g++ bug: more complex cases reveal that it
  4085. // does not correctly compute triviality in the presence of multiple special
  4086. // members of the same kind. Revisit this once the g++ bug is fixed.
  4087. case UTT_HasTrivialDefaultConstructor:
  4088. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4089. // If __is_pod (type) is true then the trait is true, else if type is
  4090. // a cv class or union type (or array thereof) with a trivial default
  4091. // constructor ([class.ctor]) then the trait is true, else it is false.
  4092. if (T.isPODType(C))
  4093. return true;
  4094. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4095. return RD->hasTrivialDefaultConstructor() &&
  4096. !RD->hasNonTrivialDefaultConstructor();
  4097. return false;
  4098. case UTT_HasTrivialMoveConstructor:
  4099. // This trait is implemented by MSVC 2012 and needed to parse the
  4100. // standard library headers. Specifically this is used as the logic
  4101. // behind std::is_trivially_move_constructible (20.9.4.3).
  4102. if (T.isPODType(C))
  4103. return true;
  4104. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4105. return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
  4106. return false;
  4107. case UTT_HasTrivialCopy:
  4108. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4109. // If __is_pod (type) is true or type is a reference type then
  4110. // the trait is true, else if type is a cv class or union type
  4111. // with a trivial copy constructor ([class.copy]) then the trait
  4112. // is true, else it is false.
  4113. if (T.isPODType(C) || T->isReferenceType())
  4114. return true;
  4115. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4116. return RD->hasTrivialCopyConstructor() &&
  4117. !RD->hasNonTrivialCopyConstructor();
  4118. return false;
  4119. case UTT_HasTrivialMoveAssign:
  4120. // This trait is implemented by MSVC 2012 and needed to parse the
  4121. // standard library headers. Specifically it is used as the logic
  4122. // behind std::is_trivially_move_assignable (20.9.4.3)
  4123. if (T.isPODType(C))
  4124. return true;
  4125. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4126. return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
  4127. return false;
  4128. case UTT_HasTrivialAssign:
  4129. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4130. // If type is const qualified or is a reference type then the
  4131. // trait is false. Otherwise if __is_pod (type) is true then the
  4132. // trait is true, else if type is a cv class or union type with
  4133. // a trivial copy assignment ([class.copy]) then the trait is
  4134. // true, else it is false.
  4135. // Note: the const and reference restrictions are interesting,
  4136. // given that const and reference members don't prevent a class
  4137. // from having a trivial copy assignment operator (but do cause
  4138. // errors if the copy assignment operator is actually used, q.v.
  4139. // [class.copy]p12).
  4140. if (T.isConstQualified())
  4141. return false;
  4142. if (T.isPODType(C))
  4143. return true;
  4144. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4145. return RD->hasTrivialCopyAssignment() &&
  4146. !RD->hasNonTrivialCopyAssignment();
  4147. return false;
  4148. case UTT_IsDestructible:
  4149. case UTT_IsTriviallyDestructible:
  4150. case UTT_IsNothrowDestructible:
  4151. // C++14 [meta.unary.prop]:
  4152. // For reference types, is_destructible<T>::value is true.
  4153. if (T->isReferenceType())
  4154. return true;
  4155. // Objective-C++ ARC: autorelease types don't require destruction.
  4156. if (T->isObjCLifetimeType() &&
  4157. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  4158. return true;
  4159. // C++14 [meta.unary.prop]:
  4160. // For incomplete types and function types, is_destructible<T>::value is
  4161. // false.
  4162. if (T->isIncompleteType() || T->isFunctionType())
  4163. return false;
  4164. // A type that requires destruction (via a non-trivial destructor or ARC
  4165. // lifetime semantics) is not trivially-destructible.
  4166. if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
  4167. return false;
  4168. // C++14 [meta.unary.prop]:
  4169. // For object types and given U equal to remove_all_extents_t<T>, if the
  4170. // expression std::declval<U&>().~U() is well-formed when treated as an
  4171. // unevaluated operand (Clause 5), then is_destructible<T>::value is true
  4172. if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  4173. CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
  4174. if (!Destructor)
  4175. return false;
  4176. // C++14 [dcl.fct.def.delete]p2:
  4177. // A program that refers to a deleted function implicitly or
  4178. // explicitly, other than to declare it, is ill-formed.
  4179. if (Destructor->isDeleted())
  4180. return false;
  4181. if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
  4182. return false;
  4183. if (UTT == UTT_IsNothrowDestructible) {
  4184. const FunctionProtoType *CPT =
  4185. Destructor->getType()->getAs<FunctionProtoType>();
  4186. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4187. if (!CPT || !CPT->isNothrow())
  4188. return false;
  4189. }
  4190. }
  4191. return true;
  4192. case UTT_HasTrivialDestructor:
  4193. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  4194. // If __is_pod (type) is true or type is a reference type
  4195. // then the trait is true, else if type is a cv class or union
  4196. // type (or array thereof) with a trivial destructor
  4197. // ([class.dtor]) then the trait is true, else it is
  4198. // false.
  4199. if (T.isPODType(C) || T->isReferenceType())
  4200. return true;
  4201. // Objective-C++ ARC: autorelease types don't require destruction.
  4202. if (T->isObjCLifetimeType() &&
  4203. T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
  4204. return true;
  4205. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
  4206. return RD->hasTrivialDestructor();
  4207. return false;
  4208. // TODO: Propagate nothrowness for implicitly declared special members.
  4209. case UTT_HasNothrowAssign:
  4210. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4211. // If type is const qualified or is a reference type then the
  4212. // trait is false. Otherwise if __has_trivial_assign (type)
  4213. // is true then the trait is true, else if type is a cv class
  4214. // or union type with copy assignment operators that are known
  4215. // not to throw an exception then the trait is true, else it is
  4216. // false.
  4217. if (C.getBaseElementType(T).isConstQualified())
  4218. return false;
  4219. if (T->isReferenceType())
  4220. return false;
  4221. if (T.isPODType(C) || T->isObjCLifetimeType())
  4222. return true;
  4223. if (const RecordType *RT = T->getAs<RecordType>())
  4224. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  4225. &CXXRecordDecl::hasTrivialCopyAssignment,
  4226. &CXXRecordDecl::hasNonTrivialCopyAssignment,
  4227. &CXXMethodDecl::isCopyAssignmentOperator);
  4228. return false;
  4229. case UTT_HasNothrowMoveAssign:
  4230. // This trait is implemented by MSVC 2012 and needed to parse the
  4231. // standard library headers. Specifically this is used as the logic
  4232. // behind std::is_nothrow_move_assignable (20.9.4.3).
  4233. if (T.isPODType(C))
  4234. return true;
  4235. if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
  4236. return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
  4237. &CXXRecordDecl::hasTrivialMoveAssignment,
  4238. &CXXRecordDecl::hasNonTrivialMoveAssignment,
  4239. &CXXMethodDecl::isMoveAssignmentOperator);
  4240. return false;
  4241. case UTT_HasNothrowCopy:
  4242. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4243. // If __has_trivial_copy (type) is true then the trait is true, else
  4244. // if type is a cv class or union type with copy constructors that are
  4245. // known not to throw an exception then the trait is true, else it is
  4246. // false.
  4247. if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
  4248. return true;
  4249. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  4250. if (RD->hasTrivialCopyConstructor() &&
  4251. !RD->hasNonTrivialCopyConstructor())
  4252. return true;
  4253. bool FoundConstructor = false;
  4254. unsigned FoundTQs;
  4255. for (const auto *ND : Self.LookupConstructors(RD)) {
  4256. // A template constructor is never a copy constructor.
  4257. // FIXME: However, it may actually be selected at the actual overload
  4258. // resolution point.
  4259. if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
  4260. continue;
  4261. // UsingDecl itself is not a constructor
  4262. if (isa<UsingDecl>(ND))
  4263. continue;
  4264. auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
  4265. if (Constructor->isCopyConstructor(FoundTQs)) {
  4266. FoundConstructor = true;
  4267. const FunctionProtoType *CPT
  4268. = Constructor->getType()->getAs<FunctionProtoType>();
  4269. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4270. if (!CPT)
  4271. return false;
  4272. // TODO: check whether evaluating default arguments can throw.
  4273. // For now, we'll be conservative and assume that they can throw.
  4274. if (!CPT->isNothrow() || CPT->getNumParams() > 1)
  4275. return false;
  4276. }
  4277. }
  4278. return FoundConstructor;
  4279. }
  4280. return false;
  4281. case UTT_HasNothrowConstructor:
  4282. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
  4283. // If __has_trivial_constructor (type) is true then the trait is
  4284. // true, else if type is a cv class or union type (or array
  4285. // thereof) with a default constructor that is known not to
  4286. // throw an exception then the trait is true, else it is false.
  4287. if (T.isPODType(C) || T->isObjCLifetimeType())
  4288. return true;
  4289. if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
  4290. if (RD->hasTrivialDefaultConstructor() &&
  4291. !RD->hasNonTrivialDefaultConstructor())
  4292. return true;
  4293. bool FoundConstructor = false;
  4294. for (const auto *ND : Self.LookupConstructors(RD)) {
  4295. // FIXME: In C++0x, a constructor template can be a default constructor.
  4296. if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
  4297. continue;
  4298. // UsingDecl itself is not a constructor
  4299. if (isa<UsingDecl>(ND))
  4300. continue;
  4301. auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
  4302. if (Constructor->isDefaultConstructor()) {
  4303. FoundConstructor = true;
  4304. const FunctionProtoType *CPT
  4305. = Constructor->getType()->getAs<FunctionProtoType>();
  4306. CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
  4307. if (!CPT)
  4308. return false;
  4309. // FIXME: check whether evaluating default arguments can throw.
  4310. // For now, we'll be conservative and assume that they can throw.
  4311. if (!CPT->isNothrow() || CPT->getNumParams() > 0)
  4312. return false;
  4313. }
  4314. }
  4315. return FoundConstructor;
  4316. }
  4317. return false;
  4318. case UTT_HasVirtualDestructor:
  4319. // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
  4320. // If type is a class type with a virtual destructor ([class.dtor])
  4321. // then the trait is true, else it is false.
  4322. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  4323. if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
  4324. return Destructor->isVirtual();
  4325. return false;
  4326. // These type trait expressions are modeled on the specifications for the
  4327. // Embarcadero C++0x type trait functions:
  4328. // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
  4329. case UTT_IsCompleteType:
  4330. // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
  4331. // Returns True if and only if T is a complete type at the point of the
  4332. // function call.
  4333. return !T->isIncompleteType();
  4334. case UTT_HasUniqueObjectRepresentations:
  4335. return C.hasUniqueObjectRepresentations(T);
  4336. }
  4337. }
  4338. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  4339. QualType RhsT, SourceLocation KeyLoc);
  4340. static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
  4341. ArrayRef<TypeSourceInfo *> Args,
  4342. SourceLocation RParenLoc) {
  4343. if (Kind <= UTT_Last)
  4344. return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
  4345. // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
  4346. // traits to avoid duplication.
  4347. if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
  4348. return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
  4349. Args[1]->getType(), RParenLoc);
  4350. switch (Kind) {
  4351. case clang::BTT_ReferenceBindsToTemporary:
  4352. case clang::TT_IsConstructible:
  4353. case clang::TT_IsNothrowConstructible:
  4354. case clang::TT_IsTriviallyConstructible: {
  4355. // C++11 [meta.unary.prop]:
  4356. // is_trivially_constructible is defined as:
  4357. //
  4358. // is_constructible<T, Args...>::value is true and the variable
  4359. // definition for is_constructible, as defined below, is known to call
  4360. // no operation that is not trivial.
  4361. //
  4362. // The predicate condition for a template specialization
  4363. // is_constructible<T, Args...> shall be satisfied if and only if the
  4364. // following variable definition would be well-formed for some invented
  4365. // variable t:
  4366. //
  4367. // T t(create<Args>()...);
  4368. assert(!Args.empty());
  4369. // Precondition: T and all types in the parameter pack Args shall be
  4370. // complete types, (possibly cv-qualified) void, or arrays of
  4371. // unknown bound.
  4372. for (const auto *TSI : Args) {
  4373. QualType ArgTy = TSI->getType();
  4374. if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
  4375. continue;
  4376. if (S.RequireCompleteType(KWLoc, ArgTy,
  4377. diag::err_incomplete_type_used_in_type_trait_expr))
  4378. return false;
  4379. }
  4380. // Make sure the first argument is not incomplete nor a function type.
  4381. QualType T = Args[0]->getType();
  4382. if (T->isIncompleteType() || T->isFunctionType())
  4383. return false;
  4384. // Make sure the first argument is not an abstract type.
  4385. CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4386. if (RD && RD->isAbstract())
  4387. return false;
  4388. SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
  4389. SmallVector<Expr *, 2> ArgExprs;
  4390. ArgExprs.reserve(Args.size() - 1);
  4391. for (unsigned I = 1, N = Args.size(); I != N; ++I) {
  4392. QualType ArgTy = Args[I]->getType();
  4393. if (ArgTy->isObjectType() || ArgTy->isFunctionType())
  4394. ArgTy = S.Context.getRValueReferenceType(ArgTy);
  4395. OpaqueArgExprs.push_back(
  4396. OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
  4397. ArgTy.getNonLValueExprType(S.Context),
  4398. Expr::getValueKindForType(ArgTy)));
  4399. }
  4400. for (Expr &E : OpaqueArgExprs)
  4401. ArgExprs.push_back(&E);
  4402. // Perform the initialization in an unevaluated context within a SFINAE
  4403. // trap at translation unit scope.
  4404. EnterExpressionEvaluationContext Unevaluated(
  4405. S, Sema::ExpressionEvaluationContext::Unevaluated);
  4406. Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
  4407. Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
  4408. InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
  4409. InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
  4410. RParenLoc));
  4411. InitializationSequence Init(S, To, InitKind, ArgExprs);
  4412. if (Init.Failed())
  4413. return false;
  4414. ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
  4415. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  4416. return false;
  4417. if (Kind == clang::TT_IsConstructible)
  4418. return true;
  4419. if (Kind == clang::BTT_ReferenceBindsToTemporary) {
  4420. if (!T->isReferenceType())
  4421. return false;
  4422. return !Init.isDirectReferenceBinding();
  4423. }
  4424. if (Kind == clang::TT_IsNothrowConstructible)
  4425. return S.canThrow(Result.get()) == CT_Cannot;
  4426. if (Kind == clang::TT_IsTriviallyConstructible) {
  4427. // Under Objective-C ARC and Weak, if the destination has non-trivial
  4428. // Objective-C lifetime, this is a non-trivial construction.
  4429. if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
  4430. return false;
  4431. // The initialization succeeded; now make sure there are no non-trivial
  4432. // calls.
  4433. return !Result.get()->hasNonTrivialCall(S.Context);
  4434. }
  4435. llvm_unreachable("unhandled type trait");
  4436. return false;
  4437. }
  4438. default: llvm_unreachable("not a TT");
  4439. }
  4440. return false;
  4441. }
  4442. ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  4443. ArrayRef<TypeSourceInfo *> Args,
  4444. SourceLocation RParenLoc) {
  4445. QualType ResultType = Context.getLogicalOperationType();
  4446. if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
  4447. *this, Kind, KWLoc, Args[0]->getType()))
  4448. return ExprError();
  4449. bool Dependent = false;
  4450. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  4451. if (Args[I]->getType()->isDependentType()) {
  4452. Dependent = true;
  4453. break;
  4454. }
  4455. }
  4456. bool Result = false;
  4457. if (!Dependent)
  4458. Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
  4459. return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
  4460. RParenLoc, Result);
  4461. }
  4462. ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
  4463. ArrayRef<ParsedType> Args,
  4464. SourceLocation RParenLoc) {
  4465. SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
  4466. ConvertedArgs.reserve(Args.size());
  4467. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  4468. TypeSourceInfo *TInfo;
  4469. QualType T = GetTypeFromParser(Args[I], &TInfo);
  4470. if (!TInfo)
  4471. TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
  4472. ConvertedArgs.push_back(TInfo);
  4473. }
  4474. return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
  4475. }
  4476. static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
  4477. QualType RhsT, SourceLocation KeyLoc) {
  4478. assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
  4479. "Cannot evaluate traits of dependent types");
  4480. switch(BTT) {
  4481. case BTT_IsBaseOf: {
  4482. // C++0x [meta.rel]p2
  4483. // Base is a base class of Derived without regard to cv-qualifiers or
  4484. // Base and Derived are not unions and name the same class type without
  4485. // regard to cv-qualifiers.
  4486. const RecordType *lhsRecord = LhsT->getAs<RecordType>();
  4487. const RecordType *rhsRecord = RhsT->getAs<RecordType>();
  4488. if (!rhsRecord || !lhsRecord) {
  4489. const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
  4490. const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
  4491. if (!LHSObjTy || !RHSObjTy)
  4492. return false;
  4493. ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
  4494. ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
  4495. if (!BaseInterface || !DerivedInterface)
  4496. return false;
  4497. if (Self.RequireCompleteType(
  4498. KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
  4499. return false;
  4500. return BaseInterface->isSuperClassOf(DerivedInterface);
  4501. }
  4502. assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
  4503. == (lhsRecord == rhsRecord));
  4504. // Unions are never base classes, and never have base classes.
  4505. // It doesn't matter if they are complete or not. See PR#41843
  4506. if (lhsRecord && lhsRecord->getDecl()->isUnion())
  4507. return false;
  4508. if (rhsRecord && rhsRecord->getDecl()->isUnion())
  4509. return false;
  4510. if (lhsRecord == rhsRecord)
  4511. return true;
  4512. // C++0x [meta.rel]p2:
  4513. // If Base and Derived are class types and are different types
  4514. // (ignoring possible cv-qualifiers) then Derived shall be a
  4515. // complete type.
  4516. if (Self.RequireCompleteType(KeyLoc, RhsT,
  4517. diag::err_incomplete_type_used_in_type_trait_expr))
  4518. return false;
  4519. return cast<CXXRecordDecl>(rhsRecord->getDecl())
  4520. ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
  4521. }
  4522. case BTT_IsSame:
  4523. return Self.Context.hasSameType(LhsT, RhsT);
  4524. case BTT_TypeCompatible: {
  4525. // GCC ignores cv-qualifiers on arrays for this builtin.
  4526. Qualifiers LhsQuals, RhsQuals;
  4527. QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
  4528. QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
  4529. return Self.Context.typesAreCompatible(Lhs, Rhs);
  4530. }
  4531. case BTT_IsConvertible:
  4532. case BTT_IsConvertibleTo: {
  4533. // C++0x [meta.rel]p4:
  4534. // Given the following function prototype:
  4535. //
  4536. // template <class T>
  4537. // typename add_rvalue_reference<T>::type create();
  4538. //
  4539. // the predicate condition for a template specialization
  4540. // is_convertible<From, To> shall be satisfied if and only if
  4541. // the return expression in the following code would be
  4542. // well-formed, including any implicit conversions to the return
  4543. // type of the function:
  4544. //
  4545. // To test() {
  4546. // return create<From>();
  4547. // }
  4548. //
  4549. // Access checking is performed as if in a context unrelated to To and
  4550. // From. Only the validity of the immediate context of the expression
  4551. // of the return-statement (including conversions to the return type)
  4552. // is considered.
  4553. //
  4554. // We model the initialization as a copy-initialization of a temporary
  4555. // of the appropriate type, which for this expression is identical to the
  4556. // return statement (since NRVO doesn't apply).
  4557. // Functions aren't allowed to return function or array types.
  4558. if (RhsT->isFunctionType() || RhsT->isArrayType())
  4559. return false;
  4560. // A return statement in a void function must have void type.
  4561. if (RhsT->isVoidType())
  4562. return LhsT->isVoidType();
  4563. // A function definition requires a complete, non-abstract return type.
  4564. if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
  4565. return false;
  4566. // Compute the result of add_rvalue_reference.
  4567. if (LhsT->isObjectType() || LhsT->isFunctionType())
  4568. LhsT = Self.Context.getRValueReferenceType(LhsT);
  4569. // Build a fake source and destination for initialization.
  4570. InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
  4571. OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  4572. Expr::getValueKindForType(LhsT));
  4573. Expr *FromPtr = &From;
  4574. InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
  4575. SourceLocation()));
  4576. // Perform the initialization in an unevaluated context within a SFINAE
  4577. // trap at translation unit scope.
  4578. EnterExpressionEvaluationContext Unevaluated(
  4579. Self, Sema::ExpressionEvaluationContext::Unevaluated);
  4580. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  4581. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  4582. InitializationSequence Init(Self, To, Kind, FromPtr);
  4583. if (Init.Failed())
  4584. return false;
  4585. ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
  4586. return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
  4587. }
  4588. case BTT_IsAssignable:
  4589. case BTT_IsNothrowAssignable:
  4590. case BTT_IsTriviallyAssignable: {
  4591. // C++11 [meta.unary.prop]p3:
  4592. // is_trivially_assignable is defined as:
  4593. // is_assignable<T, U>::value is true and the assignment, as defined by
  4594. // is_assignable, is known to call no operation that is not trivial
  4595. //
  4596. // is_assignable is defined as:
  4597. // The expression declval<T>() = declval<U>() is well-formed when
  4598. // treated as an unevaluated operand (Clause 5).
  4599. //
  4600. // For both, T and U shall be complete types, (possibly cv-qualified)
  4601. // void, or arrays of unknown bound.
  4602. if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
  4603. Self.RequireCompleteType(KeyLoc, LhsT,
  4604. diag::err_incomplete_type_used_in_type_trait_expr))
  4605. return false;
  4606. if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
  4607. Self.RequireCompleteType(KeyLoc, RhsT,
  4608. diag::err_incomplete_type_used_in_type_trait_expr))
  4609. return false;
  4610. // cv void is never assignable.
  4611. if (LhsT->isVoidType() || RhsT->isVoidType())
  4612. return false;
  4613. // Build expressions that emulate the effect of declval<T>() and
  4614. // declval<U>().
  4615. if (LhsT->isObjectType() || LhsT->isFunctionType())
  4616. LhsT = Self.Context.getRValueReferenceType(LhsT);
  4617. if (RhsT->isObjectType() || RhsT->isFunctionType())
  4618. RhsT = Self.Context.getRValueReferenceType(RhsT);
  4619. OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
  4620. Expr::getValueKindForType(LhsT));
  4621. OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
  4622. Expr::getValueKindForType(RhsT));
  4623. // Attempt the assignment in an unevaluated context within a SFINAE
  4624. // trap at translation unit scope.
  4625. EnterExpressionEvaluationContext Unevaluated(
  4626. Self, Sema::ExpressionEvaluationContext::Unevaluated);
  4627. Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
  4628. Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
  4629. ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
  4630. &Rhs);
  4631. if (Result.isInvalid() || SFINAE.hasErrorOccurred())
  4632. return false;
  4633. if (BTT == BTT_IsAssignable)
  4634. return true;
  4635. if (BTT == BTT_IsNothrowAssignable)
  4636. return Self.canThrow(Result.get()) == CT_Cannot;
  4637. if (BTT == BTT_IsTriviallyAssignable) {
  4638. // Under Objective-C ARC and Weak, if the destination has non-trivial
  4639. // Objective-C lifetime, this is a non-trivial assignment.
  4640. if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
  4641. return false;
  4642. return !Result.get()->hasNonTrivialCall(Self.Context);
  4643. }
  4644. llvm_unreachable("unhandled type trait");
  4645. return false;
  4646. }
  4647. default: llvm_unreachable("not a BTT");
  4648. }
  4649. llvm_unreachable("Unknown type trait or not implemented");
  4650. }
  4651. ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
  4652. SourceLocation KWLoc,
  4653. ParsedType Ty,
  4654. Expr* DimExpr,
  4655. SourceLocation RParen) {
  4656. TypeSourceInfo *TSInfo;
  4657. QualType T = GetTypeFromParser(Ty, &TSInfo);
  4658. if (!TSInfo)
  4659. TSInfo = Context.getTrivialTypeSourceInfo(T);
  4660. return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
  4661. }
  4662. static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
  4663. QualType T, Expr *DimExpr,
  4664. SourceLocation KeyLoc) {
  4665. assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
  4666. switch(ATT) {
  4667. case ATT_ArrayRank:
  4668. if (T->isArrayType()) {
  4669. unsigned Dim = 0;
  4670. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  4671. ++Dim;
  4672. T = AT->getElementType();
  4673. }
  4674. return Dim;
  4675. }
  4676. return 0;
  4677. case ATT_ArrayExtent: {
  4678. llvm::APSInt Value;
  4679. uint64_t Dim;
  4680. if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
  4681. diag::err_dimension_expr_not_constant_integer,
  4682. false).isInvalid())
  4683. return 0;
  4684. if (Value.isSigned() && Value.isNegative()) {
  4685. Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
  4686. << DimExpr->getSourceRange();
  4687. return 0;
  4688. }
  4689. Dim = Value.getLimitedValue();
  4690. if (T->isArrayType()) {
  4691. unsigned D = 0;
  4692. bool Matched = false;
  4693. while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
  4694. if (Dim == D) {
  4695. Matched = true;
  4696. break;
  4697. }
  4698. ++D;
  4699. T = AT->getElementType();
  4700. }
  4701. if (Matched && T->isArrayType()) {
  4702. if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
  4703. return CAT->getSize().getLimitedValue();
  4704. }
  4705. }
  4706. return 0;
  4707. }
  4708. }
  4709. llvm_unreachable("Unknown type trait or not implemented");
  4710. }
  4711. ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
  4712. SourceLocation KWLoc,
  4713. TypeSourceInfo *TSInfo,
  4714. Expr* DimExpr,
  4715. SourceLocation RParen) {
  4716. QualType T = TSInfo->getType();
  4717. // FIXME: This should likely be tracked as an APInt to remove any host
  4718. // assumptions about the width of size_t on the target.
  4719. uint64_t Value = 0;
  4720. if (!T->isDependentType())
  4721. Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
  4722. // While the specification for these traits from the Embarcadero C++
  4723. // compiler's documentation says the return type is 'unsigned int', Clang
  4724. // returns 'size_t'. On Windows, the primary platform for the Embarcadero
  4725. // compiler, there is no difference. On several other platforms this is an
  4726. // important distinction.
  4727. return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
  4728. RParen, Context.getSizeType());
  4729. }
  4730. ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
  4731. SourceLocation KWLoc,
  4732. Expr *Queried,
  4733. SourceLocation RParen) {
  4734. // If error parsing the expression, ignore.
  4735. if (!Queried)
  4736. return ExprError();
  4737. ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
  4738. return Result;
  4739. }
  4740. static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
  4741. switch (ET) {
  4742. case ET_IsLValueExpr: return E->isLValue();
  4743. case ET_IsRValueExpr: return E->isRValue();
  4744. }
  4745. llvm_unreachable("Expression trait not covered by switch");
  4746. }
  4747. ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
  4748. SourceLocation KWLoc,
  4749. Expr *Queried,
  4750. SourceLocation RParen) {
  4751. if (Queried->isTypeDependent()) {
  4752. // Delay type-checking for type-dependent expressions.
  4753. } else if (Queried->getType()->isPlaceholderType()) {
  4754. ExprResult PE = CheckPlaceholderExpr(Queried);
  4755. if (PE.isInvalid()) return ExprError();
  4756. return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
  4757. }
  4758. bool Value = EvaluateExpressionTrait(ET, Queried);
  4759. return new (Context)
  4760. ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
  4761. }
  4762. QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
  4763. ExprValueKind &VK,
  4764. SourceLocation Loc,
  4765. bool isIndirect) {
  4766. assert(!LHS.get()->getType()->isPlaceholderType() &&
  4767. !RHS.get()->getType()->isPlaceholderType() &&
  4768. "placeholders should have been weeded out by now");
  4769. // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
  4770. // temporary materialization conversion otherwise.
  4771. if (isIndirect)
  4772. LHS = DefaultLvalueConversion(LHS.get());
  4773. else if (LHS.get()->isRValue())
  4774. LHS = TemporaryMaterializationConversion(LHS.get());
  4775. if (LHS.isInvalid())
  4776. return QualType();
  4777. // The RHS always undergoes lvalue conversions.
  4778. RHS = DefaultLvalueConversion(RHS.get());
  4779. if (RHS.isInvalid()) return QualType();
  4780. const char *OpSpelling = isIndirect ? "->*" : ".*";
  4781. // C++ 5.5p2
  4782. // The binary operator .* [p3: ->*] binds its second operand, which shall
  4783. // be of type "pointer to member of T" (where T is a completely-defined
  4784. // class type) [...]
  4785. QualType RHSType = RHS.get()->getType();
  4786. const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
  4787. if (!MemPtr) {
  4788. Diag(Loc, diag::err_bad_memptr_rhs)
  4789. << OpSpelling << RHSType << RHS.get()->getSourceRange();
  4790. return QualType();
  4791. }
  4792. QualType Class(MemPtr->getClass(), 0);
  4793. // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
  4794. // member pointer points must be completely-defined. However, there is no
  4795. // reason for this semantic distinction, and the rule is not enforced by
  4796. // other compilers. Therefore, we do not check this property, as it is
  4797. // likely to be considered a defect.
  4798. // C++ 5.5p2
  4799. // [...] to its first operand, which shall be of class T or of a class of
  4800. // which T is an unambiguous and accessible base class. [p3: a pointer to
  4801. // such a class]
  4802. QualType LHSType = LHS.get()->getType();
  4803. if (isIndirect) {
  4804. if (const PointerType *Ptr = LHSType->getAs<PointerType>())
  4805. LHSType = Ptr->getPointeeType();
  4806. else {
  4807. Diag(Loc, diag::err_bad_memptr_lhs)
  4808. << OpSpelling << 1 << LHSType
  4809. << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
  4810. return QualType();
  4811. }
  4812. }
  4813. if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
  4814. // If we want to check the hierarchy, we need a complete type.
  4815. if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
  4816. OpSpelling, (int)isIndirect)) {
  4817. return QualType();
  4818. }
  4819. if (!IsDerivedFrom(Loc, LHSType, Class)) {
  4820. Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
  4821. << (int)isIndirect << LHS.get()->getType();
  4822. return QualType();
  4823. }
  4824. CXXCastPath BasePath;
  4825. if (CheckDerivedToBaseConversion(
  4826. LHSType, Class, Loc,
  4827. SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
  4828. &BasePath))
  4829. return QualType();
  4830. // Cast LHS to type of use.
  4831. QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
  4832. if (isIndirect)
  4833. UseType = Context.getPointerType(UseType);
  4834. ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
  4835. LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
  4836. &BasePath);
  4837. }
  4838. if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
  4839. // Diagnose use of pointer-to-member type which when used as
  4840. // the functional cast in a pointer-to-member expression.
  4841. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
  4842. return QualType();
  4843. }
  4844. // C++ 5.5p2
  4845. // The result is an object or a function of the type specified by the
  4846. // second operand.
  4847. // The cv qualifiers are the union of those in the pointer and the left side,
  4848. // in accordance with 5.5p5 and 5.2.5.
  4849. QualType Result = MemPtr->getPointeeType();
  4850. Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
  4851. // C++0x [expr.mptr.oper]p6:
  4852. // In a .* expression whose object expression is an rvalue, the program is
  4853. // ill-formed if the second operand is a pointer to member function with
  4854. // ref-qualifier &. In a ->* expression or in a .* expression whose object
  4855. // expression is an lvalue, the program is ill-formed if the second operand
  4856. // is a pointer to member function with ref-qualifier &&.
  4857. if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
  4858. switch (Proto->getRefQualifier()) {
  4859. case RQ_None:
  4860. // Do nothing
  4861. break;
  4862. case RQ_LValue:
  4863. if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
  4864. // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
  4865. // is (exactly) 'const'.
  4866. if (Proto->isConst() && !Proto->isVolatile())
  4867. Diag(Loc, getLangOpts().CPlusPlus2a
  4868. ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
  4869. : diag::ext_pointer_to_const_ref_member_on_rvalue);
  4870. else
  4871. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4872. << RHSType << 1 << LHS.get()->getSourceRange();
  4873. }
  4874. break;
  4875. case RQ_RValue:
  4876. if (isIndirect || !LHS.get()->Classify(Context).isRValue())
  4877. Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
  4878. << RHSType << 0 << LHS.get()->getSourceRange();
  4879. break;
  4880. }
  4881. }
  4882. // C++ [expr.mptr.oper]p6:
  4883. // The result of a .* expression whose second operand is a pointer
  4884. // to a data member is of the same value category as its
  4885. // first operand. The result of a .* expression whose second
  4886. // operand is a pointer to a member function is a prvalue. The
  4887. // result of an ->* expression is an lvalue if its second operand
  4888. // is a pointer to data member and a prvalue otherwise.
  4889. if (Result->isFunctionType()) {
  4890. VK = VK_RValue;
  4891. return Context.BoundMemberTy;
  4892. } else if (isIndirect) {
  4893. VK = VK_LValue;
  4894. } else {
  4895. VK = LHS.get()->getValueKind();
  4896. }
  4897. return Result;
  4898. }
  4899. /// Try to convert a type to another according to C++11 5.16p3.
  4900. ///
  4901. /// This is part of the parameter validation for the ? operator. If either
  4902. /// value operand is a class type, the two operands are attempted to be
  4903. /// converted to each other. This function does the conversion in one direction.
  4904. /// It returns true if the program is ill-formed and has already been diagnosed
  4905. /// as such.
  4906. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
  4907. SourceLocation QuestionLoc,
  4908. bool &HaveConversion,
  4909. QualType &ToType) {
  4910. HaveConversion = false;
  4911. ToType = To->getType();
  4912. InitializationKind Kind =
  4913. InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
  4914. // C++11 5.16p3
  4915. // The process for determining whether an operand expression E1 of type T1
  4916. // can be converted to match an operand expression E2 of type T2 is defined
  4917. // as follows:
  4918. // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
  4919. // implicitly converted to type "lvalue reference to T2", subject to the
  4920. // constraint that in the conversion the reference must bind directly to
  4921. // an lvalue.
  4922. // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
  4923. // implicitly converted to the type "rvalue reference to R2", subject to
  4924. // the constraint that the reference must bind directly.
  4925. if (To->isLValue() || To->isXValue()) {
  4926. QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
  4927. : Self.Context.getRValueReferenceType(ToType);
  4928. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  4929. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4930. if (InitSeq.isDirectReferenceBinding()) {
  4931. ToType = T;
  4932. HaveConversion = true;
  4933. return false;
  4934. }
  4935. if (InitSeq.isAmbiguous())
  4936. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4937. }
  4938. // -- If E2 is an rvalue, or if the conversion above cannot be done:
  4939. // -- if E1 and E2 have class type, and the underlying class types are
  4940. // the same or one is a base class of the other:
  4941. QualType FTy = From->getType();
  4942. QualType TTy = To->getType();
  4943. const RecordType *FRec = FTy->getAs<RecordType>();
  4944. const RecordType *TRec = TTy->getAs<RecordType>();
  4945. bool FDerivedFromT = FRec && TRec && FRec != TRec &&
  4946. Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
  4947. if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
  4948. Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
  4949. // E1 can be converted to match E2 if the class of T2 is the
  4950. // same type as, or a base class of, the class of T1, and
  4951. // [cv2 > cv1].
  4952. if (FRec == TRec || FDerivedFromT) {
  4953. if (TTy.isAtLeastAsQualifiedAs(FTy)) {
  4954. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4955. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4956. if (InitSeq) {
  4957. HaveConversion = true;
  4958. return false;
  4959. }
  4960. if (InitSeq.isAmbiguous())
  4961. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4962. }
  4963. }
  4964. return false;
  4965. }
  4966. // -- Otherwise: E1 can be converted to match E2 if E1 can be
  4967. // implicitly converted to the type that expression E2 would have
  4968. // if E2 were converted to an rvalue (or the type it has, if E2 is
  4969. // an rvalue).
  4970. //
  4971. // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
  4972. // to the array-to-pointer or function-to-pointer conversions.
  4973. TTy = TTy.getNonLValueExprType(Self.Context);
  4974. InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
  4975. InitializationSequence InitSeq(Self, Entity, Kind, From);
  4976. HaveConversion = !InitSeq.Failed();
  4977. ToType = TTy;
  4978. if (InitSeq.isAmbiguous())
  4979. return InitSeq.Diagnose(Self, Entity, Kind, From);
  4980. return false;
  4981. }
  4982. /// Try to find a common type for two according to C++0x 5.16p5.
  4983. ///
  4984. /// This is part of the parameter validation for the ? operator. If either
  4985. /// value operand is a class type, overload resolution is used to find a
  4986. /// conversion to a common type.
  4987. static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
  4988. SourceLocation QuestionLoc) {
  4989. Expr *Args[2] = { LHS.get(), RHS.get() };
  4990. OverloadCandidateSet CandidateSet(QuestionLoc,
  4991. OverloadCandidateSet::CSK_Operator);
  4992. Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
  4993. CandidateSet);
  4994. OverloadCandidateSet::iterator Best;
  4995. switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
  4996. case OR_Success: {
  4997. // We found a match. Perform the conversions on the arguments and move on.
  4998. ExprResult LHSRes = Self.PerformImplicitConversion(
  4999. LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
  5000. Sema::AA_Converting);
  5001. if (LHSRes.isInvalid())
  5002. break;
  5003. LHS = LHSRes;
  5004. ExprResult RHSRes = Self.PerformImplicitConversion(
  5005. RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
  5006. Sema::AA_Converting);
  5007. if (RHSRes.isInvalid())
  5008. break;
  5009. RHS = RHSRes;
  5010. if (Best->Function)
  5011. Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
  5012. return false;
  5013. }
  5014. case OR_No_Viable_Function:
  5015. // Emit a better diagnostic if one of the expressions is a null pointer
  5016. // constant and the other is a pointer type. In this case, the user most
  5017. // likely forgot to take the address of the other expression.
  5018. if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5019. return true;
  5020. Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5021. << LHS.get()->getType() << RHS.get()->getType()
  5022. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5023. return true;
  5024. case OR_Ambiguous:
  5025. Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
  5026. << LHS.get()->getType() << RHS.get()->getType()
  5027. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5028. // FIXME: Print the possible common types by printing the return types of
  5029. // the viable candidates.
  5030. break;
  5031. case OR_Deleted:
  5032. llvm_unreachable("Conditional operator has only built-in overloads");
  5033. }
  5034. return true;
  5035. }
  5036. /// Perform an "extended" implicit conversion as returned by
  5037. /// TryClassUnification.
  5038. static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
  5039. InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
  5040. InitializationKind Kind =
  5041. InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
  5042. Expr *Arg = E.get();
  5043. InitializationSequence InitSeq(Self, Entity, Kind, Arg);
  5044. ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
  5045. if (Result.isInvalid())
  5046. return true;
  5047. E = Result;
  5048. return false;
  5049. }
  5050. /// Check the operands of ?: under C++ semantics.
  5051. ///
  5052. /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
  5053. /// extension. In this case, LHS == Cond. (But they're not aliases.)
  5054. QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5055. ExprResult &RHS, ExprValueKind &VK,
  5056. ExprObjectKind &OK,
  5057. SourceLocation QuestionLoc) {
  5058. // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
  5059. // interface pointers.
  5060. // C++11 [expr.cond]p1
  5061. // The first expression is contextually converted to bool.
  5062. //
  5063. // FIXME; GCC's vector extension permits the use of a?b:c where the type of
  5064. // a is that of a integer vector with the same number of elements and
  5065. // size as the vectors of b and c. If one of either b or c is a scalar
  5066. // it is implicitly converted to match the type of the vector.
  5067. // Otherwise the expression is ill-formed. If both b and c are scalars,
  5068. // then b and c are checked and converted to the type of a if possible.
  5069. // Unlike the OpenCL ?: operator, the expression is evaluated as
  5070. // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
  5071. if (!Cond.get()->isTypeDependent()) {
  5072. ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
  5073. if (CondRes.isInvalid())
  5074. return QualType();
  5075. Cond = CondRes;
  5076. }
  5077. // Assume r-value.
  5078. VK = VK_RValue;
  5079. OK = OK_Ordinary;
  5080. // Either of the arguments dependent?
  5081. if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
  5082. return Context.DependentTy;
  5083. // C++11 [expr.cond]p2
  5084. // If either the second or the third operand has type (cv) void, ...
  5085. QualType LTy = LHS.get()->getType();
  5086. QualType RTy = RHS.get()->getType();
  5087. bool LVoid = LTy->isVoidType();
  5088. bool RVoid = RTy->isVoidType();
  5089. if (LVoid || RVoid) {
  5090. // ... one of the following shall hold:
  5091. // -- The second or the third operand (but not both) is a (possibly
  5092. // parenthesized) throw-expression; the result is of the type
  5093. // and value category of the other.
  5094. bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
  5095. bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
  5096. if (LThrow != RThrow) {
  5097. Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
  5098. VK = NonThrow->getValueKind();
  5099. // DR (no number yet): the result is a bit-field if the
  5100. // non-throw-expression operand is a bit-field.
  5101. OK = NonThrow->getObjectKind();
  5102. return NonThrow->getType();
  5103. }
  5104. // -- Both the second and third operands have type void; the result is of
  5105. // type void and is a prvalue.
  5106. if (LVoid && RVoid)
  5107. return Context.VoidTy;
  5108. // Neither holds, error.
  5109. Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
  5110. << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
  5111. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5112. return QualType();
  5113. }
  5114. // Neither is void.
  5115. // C++11 [expr.cond]p3
  5116. // Otherwise, if the second and third operand have different types, and
  5117. // either has (cv) class type [...] an attempt is made to convert each of
  5118. // those operands to the type of the other.
  5119. if (!Context.hasSameType(LTy, RTy) &&
  5120. (LTy->isRecordType() || RTy->isRecordType())) {
  5121. // These return true if a single direction is already ambiguous.
  5122. QualType L2RType, R2LType;
  5123. bool HaveL2R, HaveR2L;
  5124. if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
  5125. return QualType();
  5126. if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
  5127. return QualType();
  5128. // If both can be converted, [...] the program is ill-formed.
  5129. if (HaveL2R && HaveR2L) {
  5130. Diag(QuestionLoc, diag::err_conditional_ambiguous)
  5131. << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5132. return QualType();
  5133. }
  5134. // If exactly one conversion is possible, that conversion is applied to
  5135. // the chosen operand and the converted operands are used in place of the
  5136. // original operands for the remainder of this section.
  5137. if (HaveL2R) {
  5138. if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
  5139. return QualType();
  5140. LTy = LHS.get()->getType();
  5141. } else if (HaveR2L) {
  5142. if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
  5143. return QualType();
  5144. RTy = RHS.get()->getType();
  5145. }
  5146. }
  5147. // C++11 [expr.cond]p3
  5148. // if both are glvalues of the same value category and the same type except
  5149. // for cv-qualification, an attempt is made to convert each of those
  5150. // operands to the type of the other.
  5151. // FIXME:
  5152. // Resolving a defect in P0012R1: we extend this to cover all cases where
  5153. // one of the operands is reference-compatible with the other, in order
  5154. // to support conditionals between functions differing in noexcept.
  5155. ExprValueKind LVK = LHS.get()->getValueKind();
  5156. ExprValueKind RVK = RHS.get()->getValueKind();
  5157. if (!Context.hasSameType(LTy, RTy) &&
  5158. LVK == RVK && LVK != VK_RValue) {
  5159. // DerivedToBase was already handled by the class-specific case above.
  5160. // FIXME: Should we allow ObjC conversions here?
  5161. bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
  5162. if (CompareReferenceRelationship(
  5163. QuestionLoc, LTy, RTy, DerivedToBase,
  5164. ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
  5165. !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
  5166. // [...] subject to the constraint that the reference must bind
  5167. // directly [...]
  5168. !RHS.get()->refersToBitField() &&
  5169. !RHS.get()->refersToVectorElement()) {
  5170. RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
  5171. RTy = RHS.get()->getType();
  5172. } else if (CompareReferenceRelationship(
  5173. QuestionLoc, RTy, LTy, DerivedToBase,
  5174. ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
  5175. !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
  5176. !LHS.get()->refersToBitField() &&
  5177. !LHS.get()->refersToVectorElement()) {
  5178. LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
  5179. LTy = LHS.get()->getType();
  5180. }
  5181. }
  5182. // C++11 [expr.cond]p4
  5183. // If the second and third operands are glvalues of the same value
  5184. // category and have the same type, the result is of that type and
  5185. // value category and it is a bit-field if the second or the third
  5186. // operand is a bit-field, or if both are bit-fields.
  5187. // We only extend this to bitfields, not to the crazy other kinds of
  5188. // l-values.
  5189. bool Same = Context.hasSameType(LTy, RTy);
  5190. if (Same && LVK == RVK && LVK != VK_RValue &&
  5191. LHS.get()->isOrdinaryOrBitFieldObject() &&
  5192. RHS.get()->isOrdinaryOrBitFieldObject()) {
  5193. VK = LHS.get()->getValueKind();
  5194. if (LHS.get()->getObjectKind() == OK_BitField ||
  5195. RHS.get()->getObjectKind() == OK_BitField)
  5196. OK = OK_BitField;
  5197. // If we have function pointer types, unify them anyway to unify their
  5198. // exception specifications, if any.
  5199. if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
  5200. Qualifiers Qs = LTy.getQualifiers();
  5201. LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
  5202. /*ConvertArgs*/false);
  5203. LTy = Context.getQualifiedType(LTy, Qs);
  5204. assert(!LTy.isNull() && "failed to find composite pointer type for "
  5205. "canonically equivalent function ptr types");
  5206. assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
  5207. }
  5208. return LTy;
  5209. }
  5210. // C++11 [expr.cond]p5
  5211. // Otherwise, the result is a prvalue. If the second and third operands
  5212. // do not have the same type, and either has (cv) class type, ...
  5213. if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
  5214. // ... overload resolution is used to determine the conversions (if any)
  5215. // to be applied to the operands. If the overload resolution fails, the
  5216. // program is ill-formed.
  5217. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
  5218. return QualType();
  5219. }
  5220. // C++11 [expr.cond]p6
  5221. // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
  5222. // conversions are performed on the second and third operands.
  5223. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  5224. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  5225. if (LHS.isInvalid() || RHS.isInvalid())
  5226. return QualType();
  5227. LTy = LHS.get()->getType();
  5228. RTy = RHS.get()->getType();
  5229. // After those conversions, one of the following shall hold:
  5230. // -- The second and third operands have the same type; the result
  5231. // is of that type. If the operands have class type, the result
  5232. // is a prvalue temporary of the result type, which is
  5233. // copy-initialized from either the second operand or the third
  5234. // operand depending on the value of the first operand.
  5235. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
  5236. if (LTy->isRecordType()) {
  5237. // The operands have class type. Make a temporary copy.
  5238. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
  5239. ExprResult LHSCopy = PerformCopyInitialization(Entity,
  5240. SourceLocation(),
  5241. LHS);
  5242. if (LHSCopy.isInvalid())
  5243. return QualType();
  5244. ExprResult RHSCopy = PerformCopyInitialization(Entity,
  5245. SourceLocation(),
  5246. RHS);
  5247. if (RHSCopy.isInvalid())
  5248. return QualType();
  5249. LHS = LHSCopy;
  5250. RHS = RHSCopy;
  5251. }
  5252. // If we have function pointer types, unify them anyway to unify their
  5253. // exception specifications, if any.
  5254. if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
  5255. LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
  5256. assert(!LTy.isNull() && "failed to find composite pointer type for "
  5257. "canonically equivalent function ptr types");
  5258. }
  5259. return LTy;
  5260. }
  5261. // Extension: conditional operator involving vector types.
  5262. if (LTy->isVectorType() || RTy->isVectorType())
  5263. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5264. /*AllowBothBool*/true,
  5265. /*AllowBoolConversions*/false);
  5266. // -- The second and third operands have arithmetic or enumeration type;
  5267. // the usual arithmetic conversions are performed to bring them to a
  5268. // common type, and the result is of that type.
  5269. if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
  5270. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5271. if (LHS.isInvalid() || RHS.isInvalid())
  5272. return QualType();
  5273. if (ResTy.isNull()) {
  5274. Diag(QuestionLoc,
  5275. diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
  5276. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5277. return QualType();
  5278. }
  5279. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5280. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5281. return ResTy;
  5282. }
  5283. // -- The second and third operands have pointer type, or one has pointer
  5284. // type and the other is a null pointer constant, or both are null
  5285. // pointer constants, at least one of which is non-integral; pointer
  5286. // conversions and qualification conversions are performed to bring them
  5287. // to their composite pointer type. The result is of the composite
  5288. // pointer type.
  5289. // -- The second and third operands have pointer to member type, or one has
  5290. // pointer to member type and the other is a null pointer constant;
  5291. // pointer to member conversions and qualification conversions are
  5292. // performed to bring them to a common type, whose cv-qualification
  5293. // shall match the cv-qualification of either the second or the third
  5294. // operand. The result is of the common type.
  5295. QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
  5296. if (!Composite.isNull())
  5297. return Composite;
  5298. // Similarly, attempt to find composite type of two objective-c pointers.
  5299. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
  5300. if (!Composite.isNull())
  5301. return Composite;
  5302. // Check if we are using a null with a non-pointer type.
  5303. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5304. return QualType();
  5305. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5306. << LHS.get()->getType() << RHS.get()->getType()
  5307. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5308. return QualType();
  5309. }
  5310. static FunctionProtoType::ExceptionSpecInfo
  5311. mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
  5312. FunctionProtoType::ExceptionSpecInfo ESI2,
  5313. SmallVectorImpl<QualType> &ExceptionTypeStorage) {
  5314. ExceptionSpecificationType EST1 = ESI1.Type;
  5315. ExceptionSpecificationType EST2 = ESI2.Type;
  5316. // If either of them can throw anything, that is the result.
  5317. if (EST1 == EST_None) return ESI1;
  5318. if (EST2 == EST_None) return ESI2;
  5319. if (EST1 == EST_MSAny) return ESI1;
  5320. if (EST2 == EST_MSAny) return ESI2;
  5321. if (EST1 == EST_NoexceptFalse) return ESI1;
  5322. if (EST2 == EST_NoexceptFalse) return ESI2;
  5323. // If either of them is non-throwing, the result is the other.
  5324. if (EST1 == EST_NoThrow) return ESI2;
  5325. if (EST2 == EST_NoThrow) return ESI1;
  5326. if (EST1 == EST_DynamicNone) return ESI2;
  5327. if (EST2 == EST_DynamicNone) return ESI1;
  5328. if (EST1 == EST_BasicNoexcept) return ESI2;
  5329. if (EST2 == EST_BasicNoexcept) return ESI1;
  5330. if (EST1 == EST_NoexceptTrue) return ESI2;
  5331. if (EST2 == EST_NoexceptTrue) return ESI1;
  5332. // If we're left with value-dependent computed noexcept expressions, we're
  5333. // stuck. Before C++17, we can just drop the exception specification entirely,
  5334. // since it's not actually part of the canonical type. And this should never
  5335. // happen in C++17, because it would mean we were computing the composite
  5336. // pointer type of dependent types, which should never happen.
  5337. if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
  5338. assert(!S.getLangOpts().CPlusPlus17 &&
  5339. "computing composite pointer type of dependent types");
  5340. return FunctionProtoType::ExceptionSpecInfo();
  5341. }
  5342. // Switch over the possibilities so that people adding new values know to
  5343. // update this function.
  5344. switch (EST1) {
  5345. case EST_None:
  5346. case EST_DynamicNone:
  5347. case EST_MSAny:
  5348. case EST_BasicNoexcept:
  5349. case EST_DependentNoexcept:
  5350. case EST_NoexceptFalse:
  5351. case EST_NoexceptTrue:
  5352. case EST_NoThrow:
  5353. llvm_unreachable("handled above");
  5354. case EST_Dynamic: {
  5355. // This is the fun case: both exception specifications are dynamic. Form
  5356. // the union of the two lists.
  5357. assert(EST2 == EST_Dynamic && "other cases should already be handled");
  5358. llvm::SmallPtrSet<QualType, 8> Found;
  5359. for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
  5360. for (QualType E : Exceptions)
  5361. if (Found.insert(S.Context.getCanonicalType(E)).second)
  5362. ExceptionTypeStorage.push_back(E);
  5363. FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
  5364. Result.Exceptions = ExceptionTypeStorage;
  5365. return Result;
  5366. }
  5367. case EST_Unevaluated:
  5368. case EST_Uninstantiated:
  5369. case EST_Unparsed:
  5370. llvm_unreachable("shouldn't see unresolved exception specifications here");
  5371. }
  5372. llvm_unreachable("invalid ExceptionSpecificationType");
  5373. }
  5374. /// Find a merged pointer type and convert the two expressions to it.
  5375. ///
  5376. /// This finds the composite pointer type (or member pointer type) for @p E1
  5377. /// and @p E2 according to C++1z 5p14. It converts both expressions to this
  5378. /// type and returns it.
  5379. /// It does not emit diagnostics.
  5380. ///
  5381. /// \param Loc The location of the operator requiring these two expressions to
  5382. /// be converted to the composite pointer type.
  5383. ///
  5384. /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
  5385. QualType Sema::FindCompositePointerType(SourceLocation Loc,
  5386. Expr *&E1, Expr *&E2,
  5387. bool ConvertArgs) {
  5388. assert(getLangOpts().CPlusPlus && "This function assumes C++");
  5389. // C++1z [expr]p14:
  5390. // The composite pointer type of two operands p1 and p2 having types T1
  5391. // and T2
  5392. QualType T1 = E1->getType(), T2 = E2->getType();
  5393. // where at least one is a pointer or pointer to member type or
  5394. // std::nullptr_t is:
  5395. bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
  5396. T1->isNullPtrType();
  5397. bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
  5398. T2->isNullPtrType();
  5399. if (!T1IsPointerLike && !T2IsPointerLike)
  5400. return QualType();
  5401. // - if both p1 and p2 are null pointer constants, std::nullptr_t;
  5402. // This can't actually happen, following the standard, but we also use this
  5403. // to implement the end of [expr.conv], which hits this case.
  5404. //
  5405. // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
  5406. if (T1IsPointerLike &&
  5407. E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  5408. if (ConvertArgs)
  5409. E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
  5410. ? CK_NullToMemberPointer
  5411. : CK_NullToPointer).get();
  5412. return T1;
  5413. }
  5414. if (T2IsPointerLike &&
  5415. E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
  5416. if (ConvertArgs)
  5417. E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
  5418. ? CK_NullToMemberPointer
  5419. : CK_NullToPointer).get();
  5420. return T2;
  5421. }
  5422. // Now both have to be pointers or member pointers.
  5423. if (!T1IsPointerLike || !T2IsPointerLike)
  5424. return QualType();
  5425. assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
  5426. "nullptr_t should be a null pointer constant");
  5427. // - if T1 or T2 is "pointer to cv1 void" and the other type is
  5428. // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
  5429. // the union of cv1 and cv2;
  5430. // - if T1 or T2 is "pointer to noexcept function" and the other type is
  5431. // "pointer to function", where the function types are otherwise the same,
  5432. // "pointer to function";
  5433. // FIXME: This rule is defective: it should also permit removing noexcept
  5434. // from a pointer to member function. As a Clang extension, we also
  5435. // permit removing 'noreturn', so we generalize this rule to;
  5436. // - [Clang] If T1 and T2 are both of type "pointer to function" or
  5437. // "pointer to member function" and the pointee types can be unified
  5438. // by a function pointer conversion, that conversion is applied
  5439. // before checking the following rules.
  5440. // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
  5441. // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
  5442. // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
  5443. // respectively;
  5444. // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
  5445. // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
  5446. // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
  5447. // T1 or the cv-combined type of T1 and T2, respectively;
  5448. // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
  5449. // T2;
  5450. //
  5451. // If looked at in the right way, these bullets all do the same thing.
  5452. // What we do here is, we build the two possible cv-combined types, and try
  5453. // the conversions in both directions. If only one works, or if the two
  5454. // composite types are the same, we have succeeded.
  5455. // FIXME: extended qualifiers?
  5456. //
  5457. // Note that this will fail to find a composite pointer type for "pointer
  5458. // to void" and "pointer to function". We can't actually perform the final
  5459. // conversion in this case, even though a composite pointer type formally
  5460. // exists.
  5461. SmallVector<unsigned, 4> QualifierUnion;
  5462. SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
  5463. QualType Composite1 = T1;
  5464. QualType Composite2 = T2;
  5465. unsigned NeedConstBefore = 0;
  5466. while (true) {
  5467. const PointerType *Ptr1, *Ptr2;
  5468. if ((Ptr1 = Composite1->getAs<PointerType>()) &&
  5469. (Ptr2 = Composite2->getAs<PointerType>())) {
  5470. Composite1 = Ptr1->getPointeeType();
  5471. Composite2 = Ptr2->getPointeeType();
  5472. // If we're allowed to create a non-standard composite type, keep track
  5473. // of where we need to fill in additional 'const' qualifiers.
  5474. if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  5475. NeedConstBefore = QualifierUnion.size();
  5476. QualifierUnion.push_back(
  5477. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  5478. MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
  5479. continue;
  5480. }
  5481. const MemberPointerType *MemPtr1, *MemPtr2;
  5482. if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
  5483. (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
  5484. Composite1 = MemPtr1->getPointeeType();
  5485. Composite2 = MemPtr2->getPointeeType();
  5486. // If we're allowed to create a non-standard composite type, keep track
  5487. // of where we need to fill in additional 'const' qualifiers.
  5488. if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
  5489. NeedConstBefore = QualifierUnion.size();
  5490. QualifierUnion.push_back(
  5491. Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
  5492. MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
  5493. MemPtr2->getClass()));
  5494. continue;
  5495. }
  5496. // FIXME: block pointer types?
  5497. // Cannot unwrap any more types.
  5498. break;
  5499. }
  5500. // Apply the function pointer conversion to unify the types. We've already
  5501. // unwrapped down to the function types, and we want to merge rather than
  5502. // just convert, so do this ourselves rather than calling
  5503. // IsFunctionConversion.
  5504. //
  5505. // FIXME: In order to match the standard wording as closely as possible, we
  5506. // currently only do this under a single level of pointers. Ideally, we would
  5507. // allow this in general, and set NeedConstBefore to the relevant depth on
  5508. // the side(s) where we changed anything.
  5509. if (QualifierUnion.size() == 1) {
  5510. if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
  5511. if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
  5512. FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
  5513. FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
  5514. // The result is noreturn if both operands are.
  5515. bool Noreturn =
  5516. EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
  5517. EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
  5518. EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
  5519. // The result is nothrow if both operands are.
  5520. SmallVector<QualType, 8> ExceptionTypeStorage;
  5521. EPI1.ExceptionSpec = EPI2.ExceptionSpec =
  5522. mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
  5523. ExceptionTypeStorage);
  5524. Composite1 = Context.getFunctionType(FPT1->getReturnType(),
  5525. FPT1->getParamTypes(), EPI1);
  5526. Composite2 = Context.getFunctionType(FPT2->getReturnType(),
  5527. FPT2->getParamTypes(), EPI2);
  5528. }
  5529. }
  5530. }
  5531. if (NeedConstBefore) {
  5532. // Extension: Add 'const' to qualifiers that come before the first qualifier
  5533. // mismatch, so that our (non-standard!) composite type meets the
  5534. // requirements of C++ [conv.qual]p4 bullet 3.
  5535. for (unsigned I = 0; I != NeedConstBefore; ++I)
  5536. if ((QualifierUnion[I] & Qualifiers::Const) == 0)
  5537. QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
  5538. }
  5539. // Rewrap the composites as pointers or member pointers with the union CVRs.
  5540. auto MOC = MemberOfClass.rbegin();
  5541. for (unsigned CVR : llvm::reverse(QualifierUnion)) {
  5542. Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
  5543. auto Classes = *MOC++;
  5544. if (Classes.first && Classes.second) {
  5545. // Rebuild member pointer type
  5546. Composite1 = Context.getMemberPointerType(
  5547. Context.getQualifiedType(Composite1, Quals), Classes.first);
  5548. Composite2 = Context.getMemberPointerType(
  5549. Context.getQualifiedType(Composite2, Quals), Classes.second);
  5550. } else {
  5551. // Rebuild pointer type
  5552. Composite1 =
  5553. Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
  5554. Composite2 =
  5555. Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
  5556. }
  5557. }
  5558. struct Conversion {
  5559. Sema &S;
  5560. Expr *&E1, *&E2;
  5561. QualType Composite;
  5562. InitializedEntity Entity;
  5563. InitializationKind Kind;
  5564. InitializationSequence E1ToC, E2ToC;
  5565. bool Viable;
  5566. Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
  5567. QualType Composite)
  5568. : S(S), E1(E1), E2(E2), Composite(Composite),
  5569. Entity(InitializedEntity::InitializeTemporary(Composite)),
  5570. Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
  5571. E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
  5572. Viable(E1ToC && E2ToC) {}
  5573. bool perform() {
  5574. ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
  5575. if (E1Result.isInvalid())
  5576. return true;
  5577. E1 = E1Result.getAs<Expr>();
  5578. ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
  5579. if (E2Result.isInvalid())
  5580. return true;
  5581. E2 = E2Result.getAs<Expr>();
  5582. return false;
  5583. }
  5584. };
  5585. // Try to convert to each composite pointer type.
  5586. Conversion C1(*this, Loc, E1, E2, Composite1);
  5587. if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
  5588. if (ConvertArgs && C1.perform())
  5589. return QualType();
  5590. return C1.Composite;
  5591. }
  5592. Conversion C2(*this, Loc, E1, E2, Composite2);
  5593. if (C1.Viable == C2.Viable) {
  5594. // Either Composite1 and Composite2 are viable and are different, or
  5595. // neither is viable.
  5596. // FIXME: How both be viable and different?
  5597. return QualType();
  5598. }
  5599. // Convert to the chosen type.
  5600. if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
  5601. return QualType();
  5602. return C1.Viable ? C1.Composite : C2.Composite;
  5603. }
  5604. ExprResult Sema::MaybeBindToTemporary(Expr *E) {
  5605. if (!E)
  5606. return ExprError();
  5607. assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
  5608. // If the result is a glvalue, we shouldn't bind it.
  5609. if (!E->isRValue())
  5610. return E;
  5611. // In ARC, calls that return a retainable type can return retained,
  5612. // in which case we have to insert a consuming cast.
  5613. if (getLangOpts().ObjCAutoRefCount &&
  5614. E->getType()->isObjCRetainableType()) {
  5615. bool ReturnsRetained;
  5616. // For actual calls, we compute this by examining the type of the
  5617. // called value.
  5618. if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
  5619. Expr *Callee = Call->getCallee()->IgnoreParens();
  5620. QualType T = Callee->getType();
  5621. if (T == Context.BoundMemberTy) {
  5622. // Handle pointer-to-members.
  5623. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
  5624. T = BinOp->getRHS()->getType();
  5625. else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
  5626. T = Mem->getMemberDecl()->getType();
  5627. }
  5628. if (const PointerType *Ptr = T->getAs<PointerType>())
  5629. T = Ptr->getPointeeType();
  5630. else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
  5631. T = Ptr->getPointeeType();
  5632. else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
  5633. T = MemPtr->getPointeeType();
  5634. const FunctionType *FTy = T->getAs<FunctionType>();
  5635. assert(FTy && "call to value not of function type?");
  5636. ReturnsRetained = FTy->getExtInfo().getProducesResult();
  5637. // ActOnStmtExpr arranges things so that StmtExprs of retainable
  5638. // type always produce a +1 object.
  5639. } else if (isa<StmtExpr>(E)) {
  5640. ReturnsRetained = true;
  5641. // We hit this case with the lambda conversion-to-block optimization;
  5642. // we don't want any extra casts here.
  5643. } else if (isa<CastExpr>(E) &&
  5644. isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
  5645. return E;
  5646. // For message sends and property references, we try to find an
  5647. // actual method. FIXME: we should infer retention by selector in
  5648. // cases where we don't have an actual method.
  5649. } else {
  5650. ObjCMethodDecl *D = nullptr;
  5651. if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
  5652. D = Send->getMethodDecl();
  5653. } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
  5654. D = BoxedExpr->getBoxingMethod();
  5655. } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
  5656. // Don't do reclaims if we're using the zero-element array
  5657. // constant.
  5658. if (ArrayLit->getNumElements() == 0 &&
  5659. Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
  5660. return E;
  5661. D = ArrayLit->getArrayWithObjectsMethod();
  5662. } else if (ObjCDictionaryLiteral *DictLit
  5663. = dyn_cast<ObjCDictionaryLiteral>(E)) {
  5664. // Don't do reclaims if we're using the zero-element dictionary
  5665. // constant.
  5666. if (DictLit->getNumElements() == 0 &&
  5667. Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
  5668. return E;
  5669. D = DictLit->getDictWithObjectsMethod();
  5670. }
  5671. ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
  5672. // Don't do reclaims on performSelector calls; despite their
  5673. // return type, the invoked method doesn't necessarily actually
  5674. // return an object.
  5675. if (!ReturnsRetained &&
  5676. D && D->getMethodFamily() == OMF_performSelector)
  5677. return E;
  5678. }
  5679. // Don't reclaim an object of Class type.
  5680. if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
  5681. return E;
  5682. Cleanup.setExprNeedsCleanups(true);
  5683. CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
  5684. : CK_ARCReclaimReturnedObject);
  5685. return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
  5686. VK_RValue);
  5687. }
  5688. if (!getLangOpts().CPlusPlus)
  5689. return E;
  5690. // Search for the base element type (cf. ASTContext::getBaseElementType) with
  5691. // a fast path for the common case that the type is directly a RecordType.
  5692. const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
  5693. const RecordType *RT = nullptr;
  5694. while (!RT) {
  5695. switch (T->getTypeClass()) {
  5696. case Type::Record:
  5697. RT = cast<RecordType>(T);
  5698. break;
  5699. case Type::ConstantArray:
  5700. case Type::IncompleteArray:
  5701. case Type::VariableArray:
  5702. case Type::DependentSizedArray:
  5703. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  5704. break;
  5705. default:
  5706. return E;
  5707. }
  5708. }
  5709. // That should be enough to guarantee that this type is complete, if we're
  5710. // not processing a decltype expression.
  5711. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  5712. if (RD->isInvalidDecl() || RD->isDependentContext())
  5713. return E;
  5714. bool IsDecltype = ExprEvalContexts.back().ExprContext ==
  5715. ExpressionEvaluationContextRecord::EK_Decltype;
  5716. CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
  5717. if (Destructor) {
  5718. MarkFunctionReferenced(E->getExprLoc(), Destructor);
  5719. CheckDestructorAccess(E->getExprLoc(), Destructor,
  5720. PDiag(diag::err_access_dtor_temp)
  5721. << E->getType());
  5722. if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
  5723. return ExprError();
  5724. // If destructor is trivial, we can avoid the extra copy.
  5725. if (Destructor->isTrivial())
  5726. return E;
  5727. // We need a cleanup, but we don't need to remember the temporary.
  5728. Cleanup.setExprNeedsCleanups(true);
  5729. }
  5730. CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
  5731. CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
  5732. if (IsDecltype)
  5733. ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
  5734. return Bind;
  5735. }
  5736. ExprResult
  5737. Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
  5738. if (SubExpr.isInvalid())
  5739. return ExprError();
  5740. return MaybeCreateExprWithCleanups(SubExpr.get());
  5741. }
  5742. Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
  5743. assert(SubExpr && "subexpression can't be null!");
  5744. CleanupVarDeclMarking();
  5745. unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
  5746. assert(ExprCleanupObjects.size() >= FirstCleanup);
  5747. assert(Cleanup.exprNeedsCleanups() ||
  5748. ExprCleanupObjects.size() == FirstCleanup);
  5749. if (!Cleanup.exprNeedsCleanups())
  5750. return SubExpr;
  5751. auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
  5752. ExprCleanupObjects.size() - FirstCleanup);
  5753. auto *E = ExprWithCleanups::Create(
  5754. Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
  5755. DiscardCleanupsInEvaluationContext();
  5756. return E;
  5757. }
  5758. Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
  5759. assert(SubStmt && "sub-statement can't be null!");
  5760. CleanupVarDeclMarking();
  5761. if (!Cleanup.exprNeedsCleanups())
  5762. return SubStmt;
  5763. // FIXME: In order to attach the temporaries, wrap the statement into
  5764. // a StmtExpr; currently this is only used for asm statements.
  5765. // This is hacky, either create a new CXXStmtWithTemporaries statement or
  5766. // a new AsmStmtWithTemporaries.
  5767. CompoundStmt *CompStmt = CompoundStmt::Create(
  5768. Context, SubStmt, SourceLocation(), SourceLocation());
  5769. Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
  5770. SourceLocation());
  5771. return MaybeCreateExprWithCleanups(E);
  5772. }
  5773. /// Process the expression contained within a decltype. For such expressions,
  5774. /// certain semantic checks on temporaries are delayed until this point, and
  5775. /// are omitted for the 'topmost' call in the decltype expression. If the
  5776. /// topmost call bound a temporary, strip that temporary off the expression.
  5777. ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
  5778. assert(ExprEvalContexts.back().ExprContext ==
  5779. ExpressionEvaluationContextRecord::EK_Decltype &&
  5780. "not in a decltype expression");
  5781. ExprResult Result = CheckPlaceholderExpr(E);
  5782. if (Result.isInvalid())
  5783. return ExprError();
  5784. E = Result.get();
  5785. // C++11 [expr.call]p11:
  5786. // If a function call is a prvalue of object type,
  5787. // -- if the function call is either
  5788. // -- the operand of a decltype-specifier, or
  5789. // -- the right operand of a comma operator that is the operand of a
  5790. // decltype-specifier,
  5791. // a temporary object is not introduced for the prvalue.
  5792. // Recursively rebuild ParenExprs and comma expressions to strip out the
  5793. // outermost CXXBindTemporaryExpr, if any.
  5794. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  5795. ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
  5796. if (SubExpr.isInvalid())
  5797. return ExprError();
  5798. if (SubExpr.get() == PE->getSubExpr())
  5799. return E;
  5800. return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
  5801. }
  5802. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5803. if (BO->getOpcode() == BO_Comma) {
  5804. ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
  5805. if (RHS.isInvalid())
  5806. return ExprError();
  5807. if (RHS.get() == BO->getRHS())
  5808. return E;
  5809. return new (Context) BinaryOperator(
  5810. BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
  5811. BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
  5812. }
  5813. }
  5814. CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
  5815. CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
  5816. : nullptr;
  5817. if (TopCall)
  5818. E = TopCall;
  5819. else
  5820. TopBind = nullptr;
  5821. // Disable the special decltype handling now.
  5822. ExprEvalContexts.back().ExprContext =
  5823. ExpressionEvaluationContextRecord::EK_Other;
  5824. // In MS mode, don't perform any extra checking of call return types within a
  5825. // decltype expression.
  5826. if (getLangOpts().MSVCCompat)
  5827. return E;
  5828. // Perform the semantic checks we delayed until this point.
  5829. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
  5830. I != N; ++I) {
  5831. CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
  5832. if (Call == TopCall)
  5833. continue;
  5834. if (CheckCallReturnType(Call->getCallReturnType(Context),
  5835. Call->getBeginLoc(), Call, Call->getDirectCallee()))
  5836. return ExprError();
  5837. }
  5838. // Now all relevant types are complete, check the destructors are accessible
  5839. // and non-deleted, and annotate them on the temporaries.
  5840. for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
  5841. I != N; ++I) {
  5842. CXXBindTemporaryExpr *Bind =
  5843. ExprEvalContexts.back().DelayedDecltypeBinds[I];
  5844. if (Bind == TopBind)
  5845. continue;
  5846. CXXTemporary *Temp = Bind->getTemporary();
  5847. CXXRecordDecl *RD =
  5848. Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  5849. CXXDestructorDecl *Destructor = LookupDestructor(RD);
  5850. Temp->setDestructor(Destructor);
  5851. MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
  5852. CheckDestructorAccess(Bind->getExprLoc(), Destructor,
  5853. PDiag(diag::err_access_dtor_temp)
  5854. << Bind->getType());
  5855. if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
  5856. return ExprError();
  5857. // We need a cleanup, but we don't need to remember the temporary.
  5858. Cleanup.setExprNeedsCleanups(true);
  5859. }
  5860. // Possibly strip off the top CXXBindTemporaryExpr.
  5861. return E;
  5862. }
  5863. /// Note a set of 'operator->' functions that were used for a member access.
  5864. static void noteOperatorArrows(Sema &S,
  5865. ArrayRef<FunctionDecl *> OperatorArrows) {
  5866. unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
  5867. // FIXME: Make this configurable?
  5868. unsigned Limit = 9;
  5869. if (OperatorArrows.size() > Limit) {
  5870. // Produce Limit-1 normal notes and one 'skipping' note.
  5871. SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
  5872. SkipCount = OperatorArrows.size() - (Limit - 1);
  5873. }
  5874. for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
  5875. if (I == SkipStart) {
  5876. S.Diag(OperatorArrows[I]->getLocation(),
  5877. diag::note_operator_arrows_suppressed)
  5878. << SkipCount;
  5879. I += SkipCount;
  5880. } else {
  5881. S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
  5882. << OperatorArrows[I]->getCallResultType();
  5883. ++I;
  5884. }
  5885. }
  5886. }
  5887. ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
  5888. SourceLocation OpLoc,
  5889. tok::TokenKind OpKind,
  5890. ParsedType &ObjectType,
  5891. bool &MayBePseudoDestructor) {
  5892. // Since this might be a postfix expression, get rid of ParenListExprs.
  5893. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  5894. if (Result.isInvalid()) return ExprError();
  5895. Base = Result.get();
  5896. Result = CheckPlaceholderExpr(Base);
  5897. if (Result.isInvalid()) return ExprError();
  5898. Base = Result.get();
  5899. QualType BaseType = Base->getType();
  5900. MayBePseudoDestructor = false;
  5901. if (BaseType->isDependentType()) {
  5902. // If we have a pointer to a dependent type and are using the -> operator,
  5903. // the object type is the type that the pointer points to. We might still
  5904. // have enough information about that type to do something useful.
  5905. if (OpKind == tok::arrow)
  5906. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  5907. BaseType = Ptr->getPointeeType();
  5908. ObjectType = ParsedType::make(BaseType);
  5909. MayBePseudoDestructor = true;
  5910. return Base;
  5911. }
  5912. // C++ [over.match.oper]p8:
  5913. // [...] When operator->returns, the operator-> is applied to the value
  5914. // returned, with the original second operand.
  5915. if (OpKind == tok::arrow) {
  5916. QualType StartingType = BaseType;
  5917. bool NoArrowOperatorFound = false;
  5918. bool FirstIteration = true;
  5919. FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
  5920. // The set of types we've considered so far.
  5921. llvm::SmallPtrSet<CanQualType,8> CTypes;
  5922. SmallVector<FunctionDecl*, 8> OperatorArrows;
  5923. CTypes.insert(Context.getCanonicalType(BaseType));
  5924. while (BaseType->isRecordType()) {
  5925. if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
  5926. Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
  5927. << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
  5928. noteOperatorArrows(*this, OperatorArrows);
  5929. Diag(OpLoc, diag::note_operator_arrow_depth)
  5930. << getLangOpts().ArrowDepth;
  5931. return ExprError();
  5932. }
  5933. Result = BuildOverloadedArrowExpr(
  5934. S, Base, OpLoc,
  5935. // When in a template specialization and on the first loop iteration,
  5936. // potentially give the default diagnostic (with the fixit in a
  5937. // separate note) instead of having the error reported back to here
  5938. // and giving a diagnostic with a fixit attached to the error itself.
  5939. (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
  5940. ? nullptr
  5941. : &NoArrowOperatorFound);
  5942. if (Result.isInvalid()) {
  5943. if (NoArrowOperatorFound) {
  5944. if (FirstIteration) {
  5945. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  5946. << BaseType << 1 << Base->getSourceRange()
  5947. << FixItHint::CreateReplacement(OpLoc, ".");
  5948. OpKind = tok::period;
  5949. break;
  5950. }
  5951. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  5952. << BaseType << Base->getSourceRange();
  5953. CallExpr *CE = dyn_cast<CallExpr>(Base);
  5954. if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
  5955. Diag(CD->getBeginLoc(),
  5956. diag::note_member_reference_arrow_from_operator_arrow);
  5957. }
  5958. }
  5959. return ExprError();
  5960. }
  5961. Base = Result.get();
  5962. if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
  5963. OperatorArrows.push_back(OpCall->getDirectCallee());
  5964. BaseType = Base->getType();
  5965. CanQualType CBaseType = Context.getCanonicalType(BaseType);
  5966. if (!CTypes.insert(CBaseType).second) {
  5967. Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
  5968. noteOperatorArrows(*this, OperatorArrows);
  5969. return ExprError();
  5970. }
  5971. FirstIteration = false;
  5972. }
  5973. if (OpKind == tok::arrow) {
  5974. if (BaseType->isPointerType())
  5975. BaseType = BaseType->getPointeeType();
  5976. else if (auto *AT = Context.getAsArrayType(BaseType))
  5977. BaseType = AT->getElementType();
  5978. }
  5979. }
  5980. // Objective-C properties allow "." access on Objective-C pointer types,
  5981. // so adjust the base type to the object type itself.
  5982. if (BaseType->isObjCObjectPointerType())
  5983. BaseType = BaseType->getPointeeType();
  5984. // C++ [basic.lookup.classref]p2:
  5985. // [...] If the type of the object expression is of pointer to scalar
  5986. // type, the unqualified-id is looked up in the context of the complete
  5987. // postfix-expression.
  5988. //
  5989. // This also indicates that we could be parsing a pseudo-destructor-name.
  5990. // Note that Objective-C class and object types can be pseudo-destructor
  5991. // expressions or normal member (ivar or property) access expressions, and
  5992. // it's legal for the type to be incomplete if this is a pseudo-destructor
  5993. // call. We'll do more incomplete-type checks later in the lookup process,
  5994. // so just skip this check for ObjC types.
  5995. if (!BaseType->isRecordType()) {
  5996. ObjectType = ParsedType::make(BaseType);
  5997. MayBePseudoDestructor = true;
  5998. return Base;
  5999. }
  6000. // The object type must be complete (or dependent), or
  6001. // C++11 [expr.prim.general]p3:
  6002. // Unlike the object expression in other contexts, *this is not required to
  6003. // be of complete type for purposes of class member access (5.2.5) outside
  6004. // the member function body.
  6005. if (!BaseType->isDependentType() &&
  6006. !isThisOutsideMemberFunctionBody(BaseType) &&
  6007. RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
  6008. return ExprError();
  6009. // C++ [basic.lookup.classref]p2:
  6010. // If the id-expression in a class member access (5.2.5) is an
  6011. // unqualified-id, and the type of the object expression is of a class
  6012. // type C (or of pointer to a class type C), the unqualified-id is looked
  6013. // up in the scope of class C. [...]
  6014. ObjectType = ParsedType::make(BaseType);
  6015. return Base;
  6016. }
  6017. static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
  6018. tok::TokenKind& OpKind, SourceLocation OpLoc) {
  6019. if (Base->hasPlaceholderType()) {
  6020. ExprResult result = S.CheckPlaceholderExpr(Base);
  6021. if (result.isInvalid()) return true;
  6022. Base = result.get();
  6023. }
  6024. ObjectType = Base->getType();
  6025. // C++ [expr.pseudo]p2:
  6026. // The left-hand side of the dot operator shall be of scalar type. The
  6027. // left-hand side of the arrow operator shall be of pointer to scalar type.
  6028. // This scalar type is the object type.
  6029. // Note that this is rather different from the normal handling for the
  6030. // arrow operator.
  6031. if (OpKind == tok::arrow) {
  6032. if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
  6033. ObjectType = Ptr->getPointeeType();
  6034. } else if (!Base->isTypeDependent()) {
  6035. // The user wrote "p->" when they probably meant "p."; fix it.
  6036. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  6037. << ObjectType << true
  6038. << FixItHint::CreateReplacement(OpLoc, ".");
  6039. if (S.isSFINAEContext())
  6040. return true;
  6041. OpKind = tok::period;
  6042. }
  6043. }
  6044. return false;
  6045. }
  6046. /// Check if it's ok to try and recover dot pseudo destructor calls on
  6047. /// pointer objects.
  6048. static bool
  6049. canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
  6050. QualType DestructedType) {
  6051. // If this is a record type, check if its destructor is callable.
  6052. if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
  6053. if (RD->hasDefinition())
  6054. if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
  6055. return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
  6056. return false;
  6057. }
  6058. // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
  6059. return DestructedType->isDependentType() || DestructedType->isScalarType() ||
  6060. DestructedType->isVectorType();
  6061. }
  6062. ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
  6063. SourceLocation OpLoc,
  6064. tok::TokenKind OpKind,
  6065. const CXXScopeSpec &SS,
  6066. TypeSourceInfo *ScopeTypeInfo,
  6067. SourceLocation CCLoc,
  6068. SourceLocation TildeLoc,
  6069. PseudoDestructorTypeStorage Destructed) {
  6070. TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
  6071. QualType ObjectType;
  6072. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6073. return ExprError();
  6074. if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
  6075. !ObjectType->isVectorType()) {
  6076. if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
  6077. Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
  6078. else {
  6079. Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
  6080. << ObjectType << Base->getSourceRange();
  6081. return ExprError();
  6082. }
  6083. }
  6084. // C++ [expr.pseudo]p2:
  6085. // [...] The cv-unqualified versions of the object type and of the type
  6086. // designated by the pseudo-destructor-name shall be the same type.
  6087. if (DestructedTypeInfo) {
  6088. QualType DestructedType = DestructedTypeInfo->getType();
  6089. SourceLocation DestructedTypeStart
  6090. = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
  6091. if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
  6092. if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
  6093. // Detect dot pseudo destructor calls on pointer objects, e.g.:
  6094. // Foo *foo;
  6095. // foo.~Foo();
  6096. if (OpKind == tok::period && ObjectType->isPointerType() &&
  6097. Context.hasSameUnqualifiedType(DestructedType,
  6098. ObjectType->getPointeeType())) {
  6099. auto Diagnostic =
  6100. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  6101. << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
  6102. // Issue a fixit only when the destructor is valid.
  6103. if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
  6104. *this, DestructedType))
  6105. Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
  6106. // Recover by setting the object type to the destructed type and the
  6107. // operator to '->'.
  6108. ObjectType = DestructedType;
  6109. OpKind = tok::arrow;
  6110. } else {
  6111. Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
  6112. << ObjectType << DestructedType << Base->getSourceRange()
  6113. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  6114. // Recover by setting the destructed type to the object type.
  6115. DestructedType = ObjectType;
  6116. DestructedTypeInfo =
  6117. Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
  6118. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6119. }
  6120. } else if (DestructedType.getObjCLifetime() !=
  6121. ObjectType.getObjCLifetime()) {
  6122. if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
  6123. // Okay: just pretend that the user provided the correctly-qualified
  6124. // type.
  6125. } else {
  6126. Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
  6127. << ObjectType << DestructedType << Base->getSourceRange()
  6128. << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
  6129. }
  6130. // Recover by setting the destructed type to the object type.
  6131. DestructedType = ObjectType;
  6132. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
  6133. DestructedTypeStart);
  6134. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6135. }
  6136. }
  6137. }
  6138. // C++ [expr.pseudo]p2:
  6139. // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
  6140. // form
  6141. //
  6142. // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
  6143. //
  6144. // shall designate the same scalar type.
  6145. if (ScopeTypeInfo) {
  6146. QualType ScopeType = ScopeTypeInfo->getType();
  6147. if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
  6148. !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
  6149. Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
  6150. diag::err_pseudo_dtor_type_mismatch)
  6151. << ObjectType << ScopeType << Base->getSourceRange()
  6152. << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
  6153. ScopeType = QualType();
  6154. ScopeTypeInfo = nullptr;
  6155. }
  6156. }
  6157. Expr *Result
  6158. = new (Context) CXXPseudoDestructorExpr(Context, Base,
  6159. OpKind == tok::arrow, OpLoc,
  6160. SS.getWithLocInContext(Context),
  6161. ScopeTypeInfo,
  6162. CCLoc,
  6163. TildeLoc,
  6164. Destructed);
  6165. return Result;
  6166. }
  6167. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  6168. SourceLocation OpLoc,
  6169. tok::TokenKind OpKind,
  6170. CXXScopeSpec &SS,
  6171. UnqualifiedId &FirstTypeName,
  6172. SourceLocation CCLoc,
  6173. SourceLocation TildeLoc,
  6174. UnqualifiedId &SecondTypeName) {
  6175. assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6176. FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
  6177. "Invalid first type name in pseudo-destructor");
  6178. assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6179. SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
  6180. "Invalid second type name in pseudo-destructor");
  6181. QualType ObjectType;
  6182. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6183. return ExprError();
  6184. // Compute the object type that we should use for name lookup purposes. Only
  6185. // record types and dependent types matter.
  6186. ParsedType ObjectTypePtrForLookup;
  6187. if (!SS.isSet()) {
  6188. if (ObjectType->isRecordType())
  6189. ObjectTypePtrForLookup = ParsedType::make(ObjectType);
  6190. else if (ObjectType->isDependentType())
  6191. ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
  6192. }
  6193. // Convert the name of the type being destructed (following the ~) into a
  6194. // type (with source-location information).
  6195. QualType DestructedType;
  6196. TypeSourceInfo *DestructedTypeInfo = nullptr;
  6197. PseudoDestructorTypeStorage Destructed;
  6198. if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
  6199. ParsedType T = getTypeName(*SecondTypeName.Identifier,
  6200. SecondTypeName.StartLocation,
  6201. S, &SS, true, false, ObjectTypePtrForLookup,
  6202. /*IsCtorOrDtorName*/true);
  6203. if (!T &&
  6204. ((SS.isSet() && !computeDeclContext(SS, false)) ||
  6205. (!SS.isSet() && ObjectType->isDependentType()))) {
  6206. // The name of the type being destroyed is a dependent name, and we
  6207. // couldn't find anything useful in scope. Just store the identifier and
  6208. // it's location, and we'll perform (qualified) name lookup again at
  6209. // template instantiation time.
  6210. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
  6211. SecondTypeName.StartLocation);
  6212. } else if (!T) {
  6213. Diag(SecondTypeName.StartLocation,
  6214. diag::err_pseudo_dtor_destructor_non_type)
  6215. << SecondTypeName.Identifier << ObjectType;
  6216. if (isSFINAEContext())
  6217. return ExprError();
  6218. // Recover by assuming we had the right type all along.
  6219. DestructedType = ObjectType;
  6220. } else
  6221. DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
  6222. } else {
  6223. // Resolve the template-id to a type.
  6224. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
  6225. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6226. TemplateId->NumArgs);
  6227. TypeResult T = ActOnTemplateIdType(S,
  6228. TemplateId->SS,
  6229. TemplateId->TemplateKWLoc,
  6230. TemplateId->Template,
  6231. TemplateId->Name,
  6232. TemplateId->TemplateNameLoc,
  6233. TemplateId->LAngleLoc,
  6234. TemplateArgsPtr,
  6235. TemplateId->RAngleLoc,
  6236. /*IsCtorOrDtorName*/true);
  6237. if (T.isInvalid() || !T.get()) {
  6238. // Recover by assuming we had the right type all along.
  6239. DestructedType = ObjectType;
  6240. } else
  6241. DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
  6242. }
  6243. // If we've performed some kind of recovery, (re-)build the type source
  6244. // information.
  6245. if (!DestructedType.isNull()) {
  6246. if (!DestructedTypeInfo)
  6247. DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
  6248. SecondTypeName.StartLocation);
  6249. Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
  6250. }
  6251. // Convert the name of the scope type (the type prior to '::') into a type.
  6252. TypeSourceInfo *ScopeTypeInfo = nullptr;
  6253. QualType ScopeType;
  6254. if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
  6255. FirstTypeName.Identifier) {
  6256. if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
  6257. ParsedType T = getTypeName(*FirstTypeName.Identifier,
  6258. FirstTypeName.StartLocation,
  6259. S, &SS, true, false, ObjectTypePtrForLookup,
  6260. /*IsCtorOrDtorName*/true);
  6261. if (!T) {
  6262. Diag(FirstTypeName.StartLocation,
  6263. diag::err_pseudo_dtor_destructor_non_type)
  6264. << FirstTypeName.Identifier << ObjectType;
  6265. if (isSFINAEContext())
  6266. return ExprError();
  6267. // Just drop this type. It's unnecessary anyway.
  6268. ScopeType = QualType();
  6269. } else
  6270. ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
  6271. } else {
  6272. // Resolve the template-id to a type.
  6273. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
  6274. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6275. TemplateId->NumArgs);
  6276. TypeResult T = ActOnTemplateIdType(S,
  6277. TemplateId->SS,
  6278. TemplateId->TemplateKWLoc,
  6279. TemplateId->Template,
  6280. TemplateId->Name,
  6281. TemplateId->TemplateNameLoc,
  6282. TemplateId->LAngleLoc,
  6283. TemplateArgsPtr,
  6284. TemplateId->RAngleLoc,
  6285. /*IsCtorOrDtorName*/true);
  6286. if (T.isInvalid() || !T.get()) {
  6287. // Recover by dropping this type.
  6288. ScopeType = QualType();
  6289. } else
  6290. ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
  6291. }
  6292. }
  6293. if (!ScopeType.isNull() && !ScopeTypeInfo)
  6294. ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
  6295. FirstTypeName.StartLocation);
  6296. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
  6297. ScopeTypeInfo, CCLoc, TildeLoc,
  6298. Destructed);
  6299. }
  6300. ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
  6301. SourceLocation OpLoc,
  6302. tok::TokenKind OpKind,
  6303. SourceLocation TildeLoc,
  6304. const DeclSpec& DS) {
  6305. QualType ObjectType;
  6306. if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
  6307. return ExprError();
  6308. QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
  6309. false);
  6310. TypeLocBuilder TLB;
  6311. DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
  6312. DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
  6313. TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
  6314. PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
  6315. return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
  6316. nullptr, SourceLocation(), TildeLoc,
  6317. Destructed);
  6318. }
  6319. ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
  6320. CXXConversionDecl *Method,
  6321. bool HadMultipleCandidates) {
  6322. // Convert the expression to match the conversion function's implicit object
  6323. // parameter.
  6324. ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
  6325. FoundDecl, Method);
  6326. if (Exp.isInvalid())
  6327. return true;
  6328. if (Method->getParent()->isLambda() &&
  6329. Method->getConversionType()->isBlockPointerType()) {
  6330. // This is a lambda conversion to block pointer; check if the argument
  6331. // was a LambdaExpr.
  6332. Expr *SubE = E;
  6333. CastExpr *CE = dyn_cast<CastExpr>(SubE);
  6334. if (CE && CE->getCastKind() == CK_NoOp)
  6335. SubE = CE->getSubExpr();
  6336. SubE = SubE->IgnoreParens();
  6337. if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
  6338. SubE = BE->getSubExpr();
  6339. if (isa<LambdaExpr>(SubE)) {
  6340. // For the conversion to block pointer on a lambda expression, we
  6341. // construct a special BlockLiteral instead; this doesn't really make
  6342. // a difference in ARC, but outside of ARC the resulting block literal
  6343. // follows the normal lifetime rules for block literals instead of being
  6344. // autoreleased.
  6345. DiagnosticErrorTrap Trap(Diags);
  6346. PushExpressionEvaluationContext(
  6347. ExpressionEvaluationContext::PotentiallyEvaluated);
  6348. ExprResult BlockExp = BuildBlockForLambdaConversion(
  6349. Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
  6350. PopExpressionEvaluationContext();
  6351. if (BlockExp.isInvalid())
  6352. Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
  6353. return BlockExp;
  6354. }
  6355. }
  6356. MemberExpr *ME =
  6357. BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
  6358. NestedNameSpecifierLoc(), SourceLocation(), Method,
  6359. DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
  6360. HadMultipleCandidates, DeclarationNameInfo(),
  6361. Context.BoundMemberTy, VK_RValue, OK_Ordinary);
  6362. QualType ResultType = Method->getReturnType();
  6363. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  6364. ResultType = ResultType.getNonLValueExprType(Context);
  6365. CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
  6366. Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
  6367. if (CheckFunctionCall(Method, CE,
  6368. Method->getType()->castAs<FunctionProtoType>()))
  6369. return ExprError();
  6370. return CE;
  6371. }
  6372. ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
  6373. SourceLocation RParen) {
  6374. // If the operand is an unresolved lookup expression, the expression is ill-
  6375. // formed per [over.over]p1, because overloaded function names cannot be used
  6376. // without arguments except in explicit contexts.
  6377. ExprResult R = CheckPlaceholderExpr(Operand);
  6378. if (R.isInvalid())
  6379. return R;
  6380. // The operand may have been modified when checking the placeholder type.
  6381. Operand = R.get();
  6382. if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
  6383. // The expression operand for noexcept is in an unevaluated expression
  6384. // context, so side effects could result in unintended consequences.
  6385. Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  6386. }
  6387. CanThrowResult CanThrow = canThrow(Operand);
  6388. return new (Context)
  6389. CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
  6390. }
  6391. ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
  6392. Expr *Operand, SourceLocation RParen) {
  6393. return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
  6394. }
  6395. static bool IsSpecialDiscardedValue(Expr *E) {
  6396. // In C++11, discarded-value expressions of a certain form are special,
  6397. // according to [expr]p10:
  6398. // The lvalue-to-rvalue conversion (4.1) is applied only if the
  6399. // expression is an lvalue of volatile-qualified type and it has
  6400. // one of the following forms:
  6401. E = E->IgnoreParens();
  6402. // - id-expression (5.1.1),
  6403. if (isa<DeclRefExpr>(E))
  6404. return true;
  6405. // - subscripting (5.2.1),
  6406. if (isa<ArraySubscriptExpr>(E))
  6407. return true;
  6408. // - class member access (5.2.5),
  6409. if (isa<MemberExpr>(E))
  6410. return true;
  6411. // - indirection (5.3.1),
  6412. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
  6413. if (UO->getOpcode() == UO_Deref)
  6414. return true;
  6415. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6416. // - pointer-to-member operation (5.5),
  6417. if (BO->isPtrMemOp())
  6418. return true;
  6419. // - comma expression (5.18) where the right operand is one of the above.
  6420. if (BO->getOpcode() == BO_Comma)
  6421. return IsSpecialDiscardedValue(BO->getRHS());
  6422. }
  6423. // - conditional expression (5.16) where both the second and the third
  6424. // operands are one of the above, or
  6425. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
  6426. return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
  6427. IsSpecialDiscardedValue(CO->getFalseExpr());
  6428. // The related edge case of "*x ?: *x".
  6429. if (BinaryConditionalOperator *BCO =
  6430. dyn_cast<BinaryConditionalOperator>(E)) {
  6431. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
  6432. return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
  6433. IsSpecialDiscardedValue(BCO->getFalseExpr());
  6434. }
  6435. // Objective-C++ extensions to the rule.
  6436. if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
  6437. return true;
  6438. return false;
  6439. }
  6440. /// Perform the conversions required for an expression used in a
  6441. /// context that ignores the result.
  6442. ExprResult Sema::IgnoredValueConversions(Expr *E) {
  6443. if (E->hasPlaceholderType()) {
  6444. ExprResult result = CheckPlaceholderExpr(E);
  6445. if (result.isInvalid()) return E;
  6446. E = result.get();
  6447. }
  6448. // C99 6.3.2.1:
  6449. // [Except in specific positions,] an lvalue that does not have
  6450. // array type is converted to the value stored in the
  6451. // designated object (and is no longer an lvalue).
  6452. if (E->isRValue()) {
  6453. // In C, function designators (i.e. expressions of function type)
  6454. // are r-values, but we still want to do function-to-pointer decay
  6455. // on them. This is both technically correct and convenient for
  6456. // some clients.
  6457. if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
  6458. return DefaultFunctionArrayConversion(E);
  6459. return E;
  6460. }
  6461. if (getLangOpts().CPlusPlus) {
  6462. // The C++11 standard defines the notion of a discarded-value expression;
  6463. // normally, we don't need to do anything to handle it, but if it is a
  6464. // volatile lvalue with a special form, we perform an lvalue-to-rvalue
  6465. // conversion.
  6466. if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
  6467. E->getType().isVolatileQualified() &&
  6468. IsSpecialDiscardedValue(E)) {
  6469. ExprResult Res = DefaultLvalueConversion(E);
  6470. if (Res.isInvalid())
  6471. return E;
  6472. E = Res.get();
  6473. }
  6474. // C++1z:
  6475. // If the expression is a prvalue after this optional conversion, the
  6476. // temporary materialization conversion is applied.
  6477. //
  6478. // We skip this step: IR generation is able to synthesize the storage for
  6479. // itself in the aggregate case, and adding the extra node to the AST is
  6480. // just clutter.
  6481. // FIXME: We don't emit lifetime markers for the temporaries due to this.
  6482. // FIXME: Do any other AST consumers care about this?
  6483. return E;
  6484. }
  6485. // GCC seems to also exclude expressions of incomplete enum type.
  6486. if (const EnumType *T = E->getType()->getAs<EnumType>()) {
  6487. if (!T->getDecl()->isComplete()) {
  6488. // FIXME: stupid workaround for a codegen bug!
  6489. E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
  6490. return E;
  6491. }
  6492. }
  6493. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  6494. if (Res.isInvalid())
  6495. return E;
  6496. E = Res.get();
  6497. if (!E->getType()->isVoidType())
  6498. RequireCompleteType(E->getExprLoc(), E->getType(),
  6499. diag::err_incomplete_type);
  6500. return E;
  6501. }
  6502. // If we can unambiguously determine whether Var can never be used
  6503. // in a constant expression, return true.
  6504. // - if the variable and its initializer are non-dependent, then
  6505. // we can unambiguously check if the variable is a constant expression.
  6506. // - if the initializer is not value dependent - we can determine whether
  6507. // it can be used to initialize a constant expression. If Init can not
  6508. // be used to initialize a constant expression we conclude that Var can
  6509. // never be a constant expression.
  6510. // - FXIME: if the initializer is dependent, we can still do some analysis and
  6511. // identify certain cases unambiguously as non-const by using a Visitor:
  6512. // - such as those that involve odr-use of a ParmVarDecl, involve a new
  6513. // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
  6514. static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
  6515. ASTContext &Context) {
  6516. if (isa<ParmVarDecl>(Var)) return true;
  6517. const VarDecl *DefVD = nullptr;
  6518. // If there is no initializer - this can not be a constant expression.
  6519. if (!Var->getAnyInitializer(DefVD)) return true;
  6520. assert(DefVD);
  6521. if (DefVD->isWeak()) return false;
  6522. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  6523. Expr *Init = cast<Expr>(Eval->Value);
  6524. if (Var->getType()->isDependentType() || Init->isValueDependent()) {
  6525. // FIXME: Teach the constant evaluator to deal with the non-dependent parts
  6526. // of value-dependent expressions, and use it here to determine whether the
  6527. // initializer is a potential constant expression.
  6528. return false;
  6529. }
  6530. return !Var->isUsableInConstantExpressions(Context);
  6531. }
  6532. /// Check if the current lambda has any potential captures
  6533. /// that must be captured by any of its enclosing lambdas that are ready to
  6534. /// capture. If there is a lambda that can capture a nested
  6535. /// potential-capture, go ahead and do so. Also, check to see if any
  6536. /// variables are uncaptureable or do not involve an odr-use so do not
  6537. /// need to be captured.
  6538. static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
  6539. Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
  6540. assert(!S.isUnevaluatedContext());
  6541. assert(S.CurContext->isDependentContext());
  6542. #ifndef NDEBUG
  6543. DeclContext *DC = S.CurContext;
  6544. while (DC && isa<CapturedDecl>(DC))
  6545. DC = DC->getParent();
  6546. assert(
  6547. CurrentLSI->CallOperator == DC &&
  6548. "The current call operator must be synchronized with Sema's CurContext");
  6549. #endif // NDEBUG
  6550. const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
  6551. // All the potentially captureable variables in the current nested
  6552. // lambda (within a generic outer lambda), must be captured by an
  6553. // outer lambda that is enclosed within a non-dependent context.
  6554. CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
  6555. // If the variable is clearly identified as non-odr-used and the full
  6556. // expression is not instantiation dependent, only then do we not
  6557. // need to check enclosing lambda's for speculative captures.
  6558. // For e.g.:
  6559. // Even though 'x' is not odr-used, it should be captured.
  6560. // int test() {
  6561. // const int x = 10;
  6562. // auto L = [=](auto a) {
  6563. // (void) +x + a;
  6564. // };
  6565. // }
  6566. if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
  6567. !IsFullExprInstantiationDependent)
  6568. return;
  6569. // If we have a capture-capable lambda for the variable, go ahead and
  6570. // capture the variable in that lambda (and all its enclosing lambdas).
  6571. if (const Optional<unsigned> Index =
  6572. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  6573. S.FunctionScopes, Var, S))
  6574. S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
  6575. Index.getValue());
  6576. const bool IsVarNeverAConstantExpression =
  6577. VariableCanNeverBeAConstantExpression(Var, S.Context);
  6578. if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
  6579. // This full expression is not instantiation dependent or the variable
  6580. // can not be used in a constant expression - which means
  6581. // this variable must be odr-used here, so diagnose a
  6582. // capture violation early, if the variable is un-captureable.
  6583. // This is purely for diagnosing errors early. Otherwise, this
  6584. // error would get diagnosed when the lambda becomes capture ready.
  6585. QualType CaptureType, DeclRefType;
  6586. SourceLocation ExprLoc = VarExpr->getExprLoc();
  6587. if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  6588. /*EllipsisLoc*/ SourceLocation(),
  6589. /*BuildAndDiagnose*/false, CaptureType,
  6590. DeclRefType, nullptr)) {
  6591. // We will never be able to capture this variable, and we need
  6592. // to be able to in any and all instantiations, so diagnose it.
  6593. S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
  6594. /*EllipsisLoc*/ SourceLocation(),
  6595. /*BuildAndDiagnose*/true, CaptureType,
  6596. DeclRefType, nullptr);
  6597. }
  6598. }
  6599. });
  6600. // Check if 'this' needs to be captured.
  6601. if (CurrentLSI->hasPotentialThisCapture()) {
  6602. // If we have a capture-capable lambda for 'this', go ahead and capture
  6603. // 'this' in that lambda (and all its enclosing lambdas).
  6604. if (const Optional<unsigned> Index =
  6605. getStackIndexOfNearestEnclosingCaptureCapableLambda(
  6606. S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
  6607. const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
  6608. S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
  6609. /*Explicit*/ false, /*BuildAndDiagnose*/ true,
  6610. &FunctionScopeIndexOfCapturableLambda);
  6611. }
  6612. }
  6613. // Reset all the potential captures at the end of each full-expression.
  6614. CurrentLSI->clearPotentialCaptures();
  6615. }
  6616. static ExprResult attemptRecovery(Sema &SemaRef,
  6617. const TypoCorrectionConsumer &Consumer,
  6618. const TypoCorrection &TC) {
  6619. LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
  6620. Consumer.getLookupResult().getLookupKind());
  6621. const CXXScopeSpec *SS = Consumer.getSS();
  6622. CXXScopeSpec NewSS;
  6623. // Use an approprate CXXScopeSpec for building the expr.
  6624. if (auto *NNS = TC.getCorrectionSpecifier())
  6625. NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
  6626. else if (SS && !TC.WillReplaceSpecifier())
  6627. NewSS = *SS;
  6628. if (auto *ND = TC.getFoundDecl()) {
  6629. R.setLookupName(ND->getDeclName());
  6630. R.addDecl(ND);
  6631. if (ND->isCXXClassMember()) {
  6632. // Figure out the correct naming class to add to the LookupResult.
  6633. CXXRecordDecl *Record = nullptr;
  6634. if (auto *NNS = TC.getCorrectionSpecifier())
  6635. Record = NNS->getAsType()->getAsCXXRecordDecl();
  6636. if (!Record)
  6637. Record =
  6638. dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
  6639. if (Record)
  6640. R.setNamingClass(Record);
  6641. // Detect and handle the case where the decl might be an implicit
  6642. // member.
  6643. bool MightBeImplicitMember;
  6644. if (!Consumer.isAddressOfOperand())
  6645. MightBeImplicitMember = true;
  6646. else if (!NewSS.isEmpty())
  6647. MightBeImplicitMember = false;
  6648. else if (R.isOverloadedResult())
  6649. MightBeImplicitMember = false;
  6650. else if (R.isUnresolvableResult())
  6651. MightBeImplicitMember = true;
  6652. else
  6653. MightBeImplicitMember = isa<FieldDecl>(ND) ||
  6654. isa<IndirectFieldDecl>(ND) ||
  6655. isa<MSPropertyDecl>(ND);
  6656. if (MightBeImplicitMember)
  6657. return SemaRef.BuildPossibleImplicitMemberExpr(
  6658. NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
  6659. /*TemplateArgs*/ nullptr, /*S*/ nullptr);
  6660. } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
  6661. return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
  6662. Ivar->getIdentifier());
  6663. }
  6664. }
  6665. return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
  6666. /*AcceptInvalidDecl*/ true);
  6667. }
  6668. namespace {
  6669. class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
  6670. llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
  6671. public:
  6672. explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
  6673. : TypoExprs(TypoExprs) {}
  6674. bool VisitTypoExpr(TypoExpr *TE) {
  6675. TypoExprs.insert(TE);
  6676. return true;
  6677. }
  6678. };
  6679. class TransformTypos : public TreeTransform<TransformTypos> {
  6680. typedef TreeTransform<TransformTypos> BaseTransform;
  6681. VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
  6682. // process of being initialized.
  6683. llvm::function_ref<ExprResult(Expr *)> ExprFilter;
  6684. llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
  6685. llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
  6686. llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
  6687. /// Emit diagnostics for all of the TypoExprs encountered.
  6688. ///
  6689. /// If the TypoExprs were successfully corrected, then the diagnostics should
  6690. /// suggest the corrections. Otherwise the diagnostics will not suggest
  6691. /// anything (having been passed an empty TypoCorrection).
  6692. ///
  6693. /// If we've failed to correct due to ambiguous corrections, we need to
  6694. /// be sure to pass empty corrections and replacements. Otherwise it's
  6695. /// possible that the Consumer has a TypoCorrection that failed to ambiguity
  6696. /// and we don't want to report those diagnostics.
  6697. void EmitAllDiagnostics(bool IsAmbiguous) {
  6698. for (TypoExpr *TE : TypoExprs) {
  6699. auto &State = SemaRef.getTypoExprState(TE);
  6700. if (State.DiagHandler) {
  6701. TypoCorrection TC = IsAmbiguous
  6702. ? TypoCorrection() : State.Consumer->getCurrentCorrection();
  6703. ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
  6704. // Extract the NamedDecl from the transformed TypoExpr and add it to the
  6705. // TypoCorrection, replacing the existing decls. This ensures the right
  6706. // NamedDecl is used in diagnostics e.g. in the case where overload
  6707. // resolution was used to select one from several possible decls that
  6708. // had been stored in the TypoCorrection.
  6709. if (auto *ND = getDeclFromExpr(
  6710. Replacement.isInvalid() ? nullptr : Replacement.get()))
  6711. TC.setCorrectionDecl(ND);
  6712. State.DiagHandler(TC);
  6713. }
  6714. SemaRef.clearDelayedTypo(TE);
  6715. }
  6716. }
  6717. /// If corrections for the first TypoExpr have been exhausted for a
  6718. /// given combination of the other TypoExprs, retry those corrections against
  6719. /// the next combination of substitutions for the other TypoExprs by advancing
  6720. /// to the next potential correction of the second TypoExpr. For the second
  6721. /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
  6722. /// the stream is reset and the next TypoExpr's stream is advanced by one (a
  6723. /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
  6724. /// TransformCache). Returns true if there is still any untried combinations
  6725. /// of corrections.
  6726. bool CheckAndAdvanceTypoExprCorrectionStreams() {
  6727. for (auto TE : TypoExprs) {
  6728. auto &State = SemaRef.getTypoExprState(TE);
  6729. TransformCache.erase(TE);
  6730. if (!State.Consumer->finished())
  6731. return true;
  6732. State.Consumer->resetCorrectionStream();
  6733. }
  6734. return false;
  6735. }
  6736. NamedDecl *getDeclFromExpr(Expr *E) {
  6737. if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
  6738. E = OverloadResolution[OE];
  6739. if (!E)
  6740. return nullptr;
  6741. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  6742. return DRE->getFoundDecl();
  6743. if (auto *ME = dyn_cast<MemberExpr>(E))
  6744. return ME->getFoundDecl();
  6745. // FIXME: Add any other expr types that could be be seen by the delayed typo
  6746. // correction TreeTransform for which the corresponding TypoCorrection could
  6747. // contain multiple decls.
  6748. return nullptr;
  6749. }
  6750. ExprResult TryTransform(Expr *E) {
  6751. Sema::SFINAETrap Trap(SemaRef);
  6752. ExprResult Res = TransformExpr(E);
  6753. if (Trap.hasErrorOccurred() || Res.isInvalid())
  6754. return ExprError();
  6755. return ExprFilter(Res.get());
  6756. }
  6757. // Since correcting typos may intoduce new TypoExprs, this function
  6758. // checks for new TypoExprs and recurses if it finds any. Note that it will
  6759. // only succeed if it is able to correct all typos in the given expression.
  6760. ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
  6761. if (Res.isInvalid()) {
  6762. return Res;
  6763. }
  6764. // Check to see if any new TypoExprs were created. If so, we need to recurse
  6765. // to check their validity.
  6766. Expr *FixedExpr = Res.get();
  6767. auto SavedTypoExprs = std::move(TypoExprs);
  6768. auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
  6769. TypoExprs.clear();
  6770. AmbiguousTypoExprs.clear();
  6771. FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
  6772. if (!TypoExprs.empty()) {
  6773. // Recurse to handle newly created TypoExprs. If we're not able to
  6774. // handle them, discard these TypoExprs.
  6775. ExprResult RecurResult =
  6776. RecursiveTransformLoop(FixedExpr, IsAmbiguous);
  6777. if (RecurResult.isInvalid()) {
  6778. Res = ExprError();
  6779. // Recursive corrections didn't work, wipe them away and don't add
  6780. // them to the TypoExprs set. Remove them from Sema's TypoExpr list
  6781. // since we don't want to clear them twice. Note: it's possible the
  6782. // TypoExprs were created recursively and thus won't be in our
  6783. // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
  6784. auto &SemaTypoExprs = SemaRef.TypoExprs;
  6785. for (auto TE : TypoExprs) {
  6786. TransformCache.erase(TE);
  6787. SemaRef.clearDelayedTypo(TE);
  6788. auto SI = find(SemaTypoExprs, TE);
  6789. if (SI != SemaTypoExprs.end()) {
  6790. SemaTypoExprs.erase(SI);
  6791. }
  6792. }
  6793. } else {
  6794. // TypoExpr is valid: add newly created TypoExprs since we were
  6795. // able to correct them.
  6796. Res = RecurResult;
  6797. SavedTypoExprs.set_union(TypoExprs);
  6798. }
  6799. }
  6800. TypoExprs = std::move(SavedTypoExprs);
  6801. AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
  6802. return Res;
  6803. }
  6804. // Try to transform the given expression, looping through the correction
  6805. // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
  6806. //
  6807. // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
  6808. // true and this method immediately will return an `ExprError`.
  6809. ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
  6810. ExprResult Res;
  6811. auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
  6812. SemaRef.TypoExprs.clear();
  6813. while (true) {
  6814. Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
  6815. // Recursion encountered an ambiguous correction. This means that our
  6816. // correction itself is ambiguous, so stop now.
  6817. if (IsAmbiguous)
  6818. break;
  6819. // If the transform is still valid after checking for any new typos,
  6820. // it's good to go.
  6821. if (!Res.isInvalid())
  6822. break;
  6823. // The transform was invalid, see if we have any TypoExprs with untried
  6824. // correction candidates.
  6825. if (!CheckAndAdvanceTypoExprCorrectionStreams())
  6826. break;
  6827. }
  6828. // If we found a valid result, double check to make sure it's not ambiguous.
  6829. if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
  6830. auto SavedTransformCache = std::move(TransformCache);
  6831. TransformCache.clear();
  6832. // Ensure none of the TypoExprs have multiple typo correction candidates
  6833. // with the same edit length that pass all the checks and filters.
  6834. while (!AmbiguousTypoExprs.empty()) {
  6835. auto TE = AmbiguousTypoExprs.back();
  6836. // TryTransform itself can create new Typos, adding them to the TypoExpr map
  6837. // and invalidating our TypoExprState, so always fetch it instead of storing.
  6838. SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
  6839. TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
  6840. TypoCorrection Next;
  6841. do {
  6842. // Fetch the next correction by erasing the typo from the cache and calling
  6843. // `TryTransform` which will iterate through corrections in
  6844. // `TransformTypoExpr`.
  6845. TransformCache.erase(TE);
  6846. ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
  6847. if (!AmbigRes.isInvalid() || IsAmbiguous) {
  6848. SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
  6849. SavedTransformCache.erase(TE);
  6850. Res = ExprError();
  6851. IsAmbiguous = true;
  6852. break;
  6853. }
  6854. } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
  6855. Next.getEditDistance(false) == TC.getEditDistance(false));
  6856. if (IsAmbiguous)
  6857. break;
  6858. AmbiguousTypoExprs.remove(TE);
  6859. SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
  6860. }
  6861. TransformCache = std::move(SavedTransformCache);
  6862. }
  6863. // Wipe away any newly created TypoExprs that we don't know about. Since we
  6864. // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
  6865. // possible if a `TypoExpr` is created during a transformation but then
  6866. // fails before we can discover it.
  6867. auto &SemaTypoExprs = SemaRef.TypoExprs;
  6868. for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
  6869. auto TE = *Iterator;
  6870. auto FI = find(TypoExprs, TE);
  6871. if (FI != TypoExprs.end()) {
  6872. Iterator++;
  6873. continue;
  6874. }
  6875. SemaRef.clearDelayedTypo(TE);
  6876. Iterator = SemaTypoExprs.erase(Iterator);
  6877. }
  6878. SemaRef.TypoExprs = std::move(SavedTypoExprs);
  6879. return Res;
  6880. }
  6881. public:
  6882. TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
  6883. : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
  6884. ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
  6885. MultiExprArg Args,
  6886. SourceLocation RParenLoc,
  6887. Expr *ExecConfig = nullptr) {
  6888. auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
  6889. RParenLoc, ExecConfig);
  6890. if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
  6891. if (Result.isUsable()) {
  6892. Expr *ResultCall = Result.get();
  6893. if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
  6894. ResultCall = BE->getSubExpr();
  6895. if (auto *CE = dyn_cast<CallExpr>(ResultCall))
  6896. OverloadResolution[OE] = CE->getCallee();
  6897. }
  6898. }
  6899. return Result;
  6900. }
  6901. ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
  6902. ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
  6903. ExprResult Transform(Expr *E) {
  6904. bool IsAmbiguous = false;
  6905. ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
  6906. if (!Res.isUsable())
  6907. FindTypoExprs(TypoExprs).TraverseStmt(E);
  6908. EmitAllDiagnostics(IsAmbiguous);
  6909. return Res;
  6910. }
  6911. ExprResult TransformTypoExpr(TypoExpr *E) {
  6912. // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
  6913. // cached transformation result if there is one and the TypoExpr isn't the
  6914. // first one that was encountered.
  6915. auto &CacheEntry = TransformCache[E];
  6916. if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
  6917. return CacheEntry;
  6918. }
  6919. auto &State = SemaRef.getTypoExprState(E);
  6920. assert(State.Consumer && "Cannot transform a cleared TypoExpr");
  6921. // For the first TypoExpr and an uncached TypoExpr, find the next likely
  6922. // typo correction and return it.
  6923. while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
  6924. if (InitDecl && TC.getFoundDecl() == InitDecl)
  6925. continue;
  6926. // FIXME: If we would typo-correct to an invalid declaration, it's
  6927. // probably best to just suppress all errors from this typo correction.
  6928. ExprResult NE = State.RecoveryHandler ?
  6929. State.RecoveryHandler(SemaRef, E, TC) :
  6930. attemptRecovery(SemaRef, *State.Consumer, TC);
  6931. if (!NE.isInvalid()) {
  6932. // Check whether there may be a second viable correction with the same
  6933. // edit distance; if so, remember this TypoExpr may have an ambiguous
  6934. // correction so it can be more thoroughly vetted later.
  6935. TypoCorrection Next;
  6936. if ((Next = State.Consumer->peekNextCorrection()) &&
  6937. Next.getEditDistance(false) == TC.getEditDistance(false)) {
  6938. AmbiguousTypoExprs.insert(E);
  6939. } else {
  6940. AmbiguousTypoExprs.remove(E);
  6941. }
  6942. assert(!NE.isUnset() &&
  6943. "Typo was transformed into a valid-but-null ExprResult");
  6944. return CacheEntry = NE;
  6945. }
  6946. }
  6947. return CacheEntry = ExprError();
  6948. }
  6949. };
  6950. }
  6951. ExprResult
  6952. Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
  6953. llvm::function_ref<ExprResult(Expr *)> Filter) {
  6954. // If the current evaluation context indicates there are uncorrected typos
  6955. // and the current expression isn't guaranteed to not have typos, try to
  6956. // resolve any TypoExpr nodes that might be in the expression.
  6957. if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
  6958. (E->isTypeDependent() || E->isValueDependent() ||
  6959. E->isInstantiationDependent())) {
  6960. auto TyposResolved = DelayedTypos.size();
  6961. auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
  6962. TyposResolved -= DelayedTypos.size();
  6963. if (Result.isInvalid() || Result.get() != E) {
  6964. ExprEvalContexts.back().NumTypos -= TyposResolved;
  6965. return Result;
  6966. }
  6967. assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
  6968. }
  6969. return E;
  6970. }
  6971. ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
  6972. bool DiscardedValue,
  6973. bool IsConstexpr) {
  6974. ExprResult FullExpr = FE;
  6975. if (!FullExpr.get())
  6976. return ExprError();
  6977. if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
  6978. return ExprError();
  6979. if (DiscardedValue) {
  6980. // Top-level expressions default to 'id' when we're in a debugger.
  6981. if (getLangOpts().DebuggerCastResultToId &&
  6982. FullExpr.get()->getType() == Context.UnknownAnyTy) {
  6983. FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
  6984. if (FullExpr.isInvalid())
  6985. return ExprError();
  6986. }
  6987. FullExpr = CheckPlaceholderExpr(FullExpr.get());
  6988. if (FullExpr.isInvalid())
  6989. return ExprError();
  6990. FullExpr = IgnoredValueConversions(FullExpr.get());
  6991. if (FullExpr.isInvalid())
  6992. return ExprError();
  6993. DiagnoseUnusedExprResult(FullExpr.get());
  6994. }
  6995. FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
  6996. if (FullExpr.isInvalid())
  6997. return ExprError();
  6998. CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
  6999. // At the end of this full expression (which could be a deeply nested
  7000. // lambda), if there is a potential capture within the nested lambda,
  7001. // have the outer capture-able lambda try and capture it.
  7002. // Consider the following code:
  7003. // void f(int, int);
  7004. // void f(const int&, double);
  7005. // void foo() {
  7006. // const int x = 10, y = 20;
  7007. // auto L = [=](auto a) {
  7008. // auto M = [=](auto b) {
  7009. // f(x, b); <-- requires x to be captured by L and M
  7010. // f(y, a); <-- requires y to be captured by L, but not all Ms
  7011. // };
  7012. // };
  7013. // }
  7014. // FIXME: Also consider what happens for something like this that involves
  7015. // the gnu-extension statement-expressions or even lambda-init-captures:
  7016. // void f() {
  7017. // const int n = 0;
  7018. // auto L = [&](auto a) {
  7019. // +n + ({ 0; a; });
  7020. // };
  7021. // }
  7022. //
  7023. // Here, we see +n, and then the full-expression 0; ends, so we don't
  7024. // capture n (and instead remove it from our list of potential captures),
  7025. // and then the full-expression +n + ({ 0; }); ends, but it's too late
  7026. // for us to see that we need to capture n after all.
  7027. LambdaScopeInfo *const CurrentLSI =
  7028. getCurLambda(/*IgnoreCapturedRegions=*/true);
  7029. // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
  7030. // even if CurContext is not a lambda call operator. Refer to that Bug Report
  7031. // for an example of the code that might cause this asynchrony.
  7032. // By ensuring we are in the context of a lambda's call operator
  7033. // we can fix the bug (we only need to check whether we need to capture
  7034. // if we are within a lambda's body); but per the comments in that
  7035. // PR, a proper fix would entail :
  7036. // "Alternative suggestion:
  7037. // - Add to Sema an integer holding the smallest (outermost) scope
  7038. // index that we are *lexically* within, and save/restore/set to
  7039. // FunctionScopes.size() in InstantiatingTemplate's
  7040. // constructor/destructor.
  7041. // - Teach the handful of places that iterate over FunctionScopes to
  7042. // stop at the outermost enclosing lexical scope."
  7043. DeclContext *DC = CurContext;
  7044. while (DC && isa<CapturedDecl>(DC))
  7045. DC = DC->getParent();
  7046. const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
  7047. if (IsInLambdaDeclContext && CurrentLSI &&
  7048. CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
  7049. CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
  7050. *this);
  7051. return MaybeCreateExprWithCleanups(FullExpr);
  7052. }
  7053. StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
  7054. if (!FullStmt) return StmtError();
  7055. return MaybeCreateStmtWithCleanups(FullStmt);
  7056. }
  7057. Sema::IfExistsResult
  7058. Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
  7059. CXXScopeSpec &SS,
  7060. const DeclarationNameInfo &TargetNameInfo) {
  7061. DeclarationName TargetName = TargetNameInfo.getName();
  7062. if (!TargetName)
  7063. return IER_DoesNotExist;
  7064. // If the name itself is dependent, then the result is dependent.
  7065. if (TargetName.isDependentName())
  7066. return IER_Dependent;
  7067. // Do the redeclaration lookup in the current scope.
  7068. LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
  7069. Sema::NotForRedeclaration);
  7070. LookupParsedName(R, S, &SS);
  7071. R.suppressDiagnostics();
  7072. switch (R.getResultKind()) {
  7073. case LookupResult::Found:
  7074. case LookupResult::FoundOverloaded:
  7075. case LookupResult::FoundUnresolvedValue:
  7076. case LookupResult::Ambiguous:
  7077. return IER_Exists;
  7078. case LookupResult::NotFound:
  7079. return IER_DoesNotExist;
  7080. case LookupResult::NotFoundInCurrentInstantiation:
  7081. return IER_Dependent;
  7082. }
  7083. llvm_unreachable("Invalid LookupResult Kind!");
  7084. }
  7085. Sema::IfExistsResult
  7086. Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
  7087. bool IsIfExists, CXXScopeSpec &SS,
  7088. UnqualifiedId &Name) {
  7089. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  7090. // Check for an unexpanded parameter pack.
  7091. auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
  7092. if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
  7093. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
  7094. return IER_Error;
  7095. return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
  7096. }