SemaExprCXX.cpp 362 KB

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