SemaExprCXX.cpp 321 KB

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