SemaExprCXX.cpp 315 KB

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