SemaInit.cpp 372 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558
  1. //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for initializers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclObjC.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/AST/ExprObjC.h"
  16. #include "clang/AST/ExprOpenMP.h"
  17. #include "clang/AST/TypeLoc.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/Sema/Designator.h"
  20. #include "clang/Sema/Initialization.h"
  21. #include "clang/Sema/Lookup.h"
  22. #include "clang/Sema/SemaInternal.h"
  23. #include "llvm/ADT/APInt.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace clang;
  28. //===----------------------------------------------------------------------===//
  29. // Sema Initialization Checking
  30. //===----------------------------------------------------------------------===//
  31. /// Check whether T is compatible with a wide character type (wchar_t,
  32. /// char16_t or char32_t).
  33. static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
  34. if (Context.typesAreCompatible(Context.getWideCharType(), T))
  35. return true;
  36. if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
  37. return Context.typesAreCompatible(Context.Char16Ty, T) ||
  38. Context.typesAreCompatible(Context.Char32Ty, T);
  39. }
  40. return false;
  41. }
  42. enum StringInitFailureKind {
  43. SIF_None,
  44. SIF_NarrowStringIntoWideChar,
  45. SIF_WideStringIntoChar,
  46. SIF_IncompatWideStringIntoWideChar,
  47. SIF_UTF8StringIntoPlainChar,
  48. SIF_PlainStringIntoUTF8Char,
  49. SIF_Other
  50. };
  51. /// Check whether the array of type AT can be initialized by the Init
  52. /// expression by means of string initialization. Returns SIF_None if so,
  53. /// otherwise returns a StringInitFailureKind that describes why the
  54. /// initialization would not work.
  55. static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
  56. ASTContext &Context) {
  57. if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
  58. return SIF_Other;
  59. // See if this is a string literal or @encode.
  60. Init = Init->IgnoreParens();
  61. // Handle @encode, which is a narrow string.
  62. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
  63. return SIF_None;
  64. // Otherwise we can only handle string literals.
  65. StringLiteral *SL = dyn_cast<StringLiteral>(Init);
  66. if (!SL)
  67. return SIF_Other;
  68. const QualType ElemTy =
  69. Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
  70. switch (SL->getKind()) {
  71. case StringLiteral::UTF8:
  72. // char8_t array can be initialized with a UTF-8 string.
  73. if (ElemTy->isChar8Type())
  74. return SIF_None;
  75. LLVM_FALLTHROUGH;
  76. case StringLiteral::Ascii:
  77. // char array can be initialized with a narrow string.
  78. // Only allow char x[] = "foo"; not char x[] = L"foo";
  79. if (ElemTy->isCharType())
  80. return (SL->getKind() == StringLiteral::UTF8 &&
  81. Context.getLangOpts().Char8)
  82. ? SIF_UTF8StringIntoPlainChar
  83. : SIF_None;
  84. if (ElemTy->isChar8Type())
  85. return SIF_PlainStringIntoUTF8Char;
  86. if (IsWideCharCompatible(ElemTy, Context))
  87. return SIF_NarrowStringIntoWideChar;
  88. return SIF_Other;
  89. // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
  90. // "An array with element type compatible with a qualified or unqualified
  91. // version of wchar_t, char16_t, or char32_t may be initialized by a wide
  92. // string literal with the corresponding encoding prefix (L, u, or U,
  93. // respectively), optionally enclosed in braces.
  94. case StringLiteral::UTF16:
  95. if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
  96. return SIF_None;
  97. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  98. return SIF_WideStringIntoChar;
  99. if (IsWideCharCompatible(ElemTy, Context))
  100. return SIF_IncompatWideStringIntoWideChar;
  101. return SIF_Other;
  102. case StringLiteral::UTF32:
  103. if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
  104. return SIF_None;
  105. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  106. return SIF_WideStringIntoChar;
  107. if (IsWideCharCompatible(ElemTy, Context))
  108. return SIF_IncompatWideStringIntoWideChar;
  109. return SIF_Other;
  110. case StringLiteral::Wide:
  111. if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
  112. return SIF_None;
  113. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  114. return SIF_WideStringIntoChar;
  115. if (IsWideCharCompatible(ElemTy, Context))
  116. return SIF_IncompatWideStringIntoWideChar;
  117. return SIF_Other;
  118. }
  119. llvm_unreachable("missed a StringLiteral kind?");
  120. }
  121. static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
  122. ASTContext &Context) {
  123. const ArrayType *arrayType = Context.getAsArrayType(declType);
  124. if (!arrayType)
  125. return SIF_Other;
  126. return IsStringInit(init, arrayType, Context);
  127. }
  128. /// Update the type of a string literal, including any surrounding parentheses,
  129. /// to match the type of the object which it is initializing.
  130. static void updateStringLiteralType(Expr *E, QualType Ty) {
  131. while (true) {
  132. E->setType(Ty);
  133. E->setValueKind(VK_RValue);
  134. if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
  135. break;
  136. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  137. E = PE->getSubExpr();
  138. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  139. assert(UO->getOpcode() == UO_Extension);
  140. E = UO->getSubExpr();
  141. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  142. E = GSE->getResultExpr();
  143. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  144. E = CE->getChosenSubExpr();
  145. } else {
  146. llvm_unreachable("unexpected expr in string literal init");
  147. }
  148. }
  149. }
  150. /// Fix a compound literal initializing an array so it's correctly marked
  151. /// as an rvalue.
  152. static void updateGNUCompoundLiteralRValue(Expr *E) {
  153. while (true) {
  154. E->setValueKind(VK_RValue);
  155. if (isa<CompoundLiteralExpr>(E)) {
  156. break;
  157. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  158. E = PE->getSubExpr();
  159. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  160. assert(UO->getOpcode() == UO_Extension);
  161. E = UO->getSubExpr();
  162. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  163. E = GSE->getResultExpr();
  164. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  165. E = CE->getChosenSubExpr();
  166. } else {
  167. llvm_unreachable("unexpected expr in array compound literal init");
  168. }
  169. }
  170. }
  171. static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
  172. Sema &S) {
  173. // Get the length of the string as parsed.
  174. auto *ConstantArrayTy =
  175. cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
  176. uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
  177. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  178. // C99 6.7.8p14. We have an array of character type with unknown size
  179. // being initialized to a string literal.
  180. llvm::APInt ConstVal(32, StrLength);
  181. // Return a new array type (C99 6.7.8p22).
  182. DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
  183. ConstVal,
  184. ArrayType::Normal, 0);
  185. updateStringLiteralType(Str, DeclT);
  186. return;
  187. }
  188. const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
  189. // We have an array of character type with known size. However,
  190. // the size may be smaller or larger than the string we are initializing.
  191. // FIXME: Avoid truncation for 64-bit length strings.
  192. if (S.getLangOpts().CPlusPlus) {
  193. if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
  194. // For Pascal strings it's OK to strip off the terminating null character,
  195. // so the example below is valid:
  196. //
  197. // unsigned char a[2] = "\pa";
  198. if (SL->isPascal())
  199. StrLength--;
  200. }
  201. // [dcl.init.string]p2
  202. if (StrLength > CAT->getSize().getZExtValue())
  203. S.Diag(Str->getBeginLoc(),
  204. diag::err_initializer_string_for_char_array_too_long)
  205. << Str->getSourceRange();
  206. } else {
  207. // C99 6.7.8p14.
  208. if (StrLength-1 > CAT->getSize().getZExtValue())
  209. S.Diag(Str->getBeginLoc(),
  210. diag::ext_initializer_string_for_char_array_too_long)
  211. << Str->getSourceRange();
  212. }
  213. // Set the type to the actual size that we are initializing. If we have
  214. // something like:
  215. // char x[1] = "foo";
  216. // then this will set the string literal's type to char[1].
  217. updateStringLiteralType(Str, DeclT);
  218. }
  219. //===----------------------------------------------------------------------===//
  220. // Semantic checking for initializer lists.
  221. //===----------------------------------------------------------------------===//
  222. namespace {
  223. /// Semantic checking for initializer lists.
  224. ///
  225. /// The InitListChecker class contains a set of routines that each
  226. /// handle the initialization of a certain kind of entity, e.g.,
  227. /// arrays, vectors, struct/union types, scalars, etc. The
  228. /// InitListChecker itself performs a recursive walk of the subobject
  229. /// structure of the type to be initialized, while stepping through
  230. /// the initializer list one element at a time. The IList and Index
  231. /// parameters to each of the Check* routines contain the active
  232. /// (syntactic) initializer list and the index into that initializer
  233. /// list that represents the current initializer. Each routine is
  234. /// responsible for moving that Index forward as it consumes elements.
  235. ///
  236. /// Each Check* routine also has a StructuredList/StructuredIndex
  237. /// arguments, which contains the current "structured" (semantic)
  238. /// initializer list and the index into that initializer list where we
  239. /// are copying initializers as we map them over to the semantic
  240. /// list. Once we have completed our recursive walk of the subobject
  241. /// structure, we will have constructed a full semantic initializer
  242. /// list.
  243. ///
  244. /// C99 designators cause changes in the initializer list traversal,
  245. /// because they make the initialization "jump" into a specific
  246. /// subobject and then continue the initialization from that
  247. /// point. CheckDesignatedInitializer() recursively steps into the
  248. /// designated subobject and manages backing out the recursion to
  249. /// initialize the subobjects after the one designated.
  250. class InitListChecker {
  251. Sema &SemaRef;
  252. bool hadError;
  253. bool VerifyOnly; // no diagnostics, no structure building
  254. bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
  255. llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
  256. InitListExpr *FullyStructuredList;
  257. void CheckImplicitInitList(const InitializedEntity &Entity,
  258. InitListExpr *ParentIList, QualType T,
  259. unsigned &Index, InitListExpr *StructuredList,
  260. unsigned &StructuredIndex);
  261. void CheckExplicitInitList(const InitializedEntity &Entity,
  262. InitListExpr *IList, QualType &T,
  263. InitListExpr *StructuredList,
  264. bool TopLevelObject = false);
  265. void CheckListElementTypes(const InitializedEntity &Entity,
  266. InitListExpr *IList, QualType &DeclType,
  267. bool SubobjectIsDesignatorContext,
  268. unsigned &Index,
  269. InitListExpr *StructuredList,
  270. unsigned &StructuredIndex,
  271. bool TopLevelObject = false);
  272. void CheckSubElementType(const InitializedEntity &Entity,
  273. InitListExpr *IList, QualType ElemType,
  274. unsigned &Index,
  275. InitListExpr *StructuredList,
  276. unsigned &StructuredIndex);
  277. void CheckComplexType(const InitializedEntity &Entity,
  278. InitListExpr *IList, QualType DeclType,
  279. unsigned &Index,
  280. InitListExpr *StructuredList,
  281. unsigned &StructuredIndex);
  282. void CheckScalarType(const InitializedEntity &Entity,
  283. InitListExpr *IList, QualType DeclType,
  284. unsigned &Index,
  285. InitListExpr *StructuredList,
  286. unsigned &StructuredIndex);
  287. void CheckReferenceType(const InitializedEntity &Entity,
  288. InitListExpr *IList, QualType DeclType,
  289. unsigned &Index,
  290. InitListExpr *StructuredList,
  291. unsigned &StructuredIndex);
  292. void CheckVectorType(const InitializedEntity &Entity,
  293. InitListExpr *IList, QualType DeclType, unsigned &Index,
  294. InitListExpr *StructuredList,
  295. unsigned &StructuredIndex);
  296. void CheckStructUnionTypes(const InitializedEntity &Entity,
  297. InitListExpr *IList, QualType DeclType,
  298. CXXRecordDecl::base_class_range Bases,
  299. RecordDecl::field_iterator Field,
  300. bool SubobjectIsDesignatorContext, unsigned &Index,
  301. InitListExpr *StructuredList,
  302. unsigned &StructuredIndex,
  303. bool TopLevelObject = false);
  304. void CheckArrayType(const InitializedEntity &Entity,
  305. InitListExpr *IList, QualType &DeclType,
  306. llvm::APSInt elementIndex,
  307. bool SubobjectIsDesignatorContext, unsigned &Index,
  308. InitListExpr *StructuredList,
  309. unsigned &StructuredIndex);
  310. bool CheckDesignatedInitializer(const InitializedEntity &Entity,
  311. InitListExpr *IList, DesignatedInitExpr *DIE,
  312. unsigned DesigIdx,
  313. QualType &CurrentObjectType,
  314. RecordDecl::field_iterator *NextField,
  315. llvm::APSInt *NextElementIndex,
  316. unsigned &Index,
  317. InitListExpr *StructuredList,
  318. unsigned &StructuredIndex,
  319. bool FinishSubobjectInit,
  320. bool TopLevelObject);
  321. InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  322. QualType CurrentObjectType,
  323. InitListExpr *StructuredList,
  324. unsigned StructuredIndex,
  325. SourceRange InitRange,
  326. bool IsFullyOverwritten = false);
  327. void UpdateStructuredListElement(InitListExpr *StructuredList,
  328. unsigned &StructuredIndex,
  329. Expr *expr);
  330. int numArrayElements(QualType DeclType);
  331. int numStructUnionElements(QualType DeclType);
  332. static ExprResult PerformEmptyInit(Sema &SemaRef,
  333. SourceLocation Loc,
  334. const InitializedEntity &Entity,
  335. bool VerifyOnly,
  336. bool TreatUnavailableAsInvalid);
  337. // Explanation on the "FillWithNoInit" mode:
  338. //
  339. // Assume we have the following definitions (Case#1):
  340. // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
  341. // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
  342. //
  343. // l.lp.x[1][0..1] should not be filled with implicit initializers because the
  344. // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
  345. //
  346. // But if we have (Case#2):
  347. // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
  348. //
  349. // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
  350. // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
  351. //
  352. // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
  353. // in the InitListExpr, the "holes" in Case#1 are filled not with empty
  354. // initializers but with special "NoInitExpr" place holders, which tells the
  355. // CodeGen not to generate any initializers for these parts.
  356. void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
  357. const InitializedEntity &ParentEntity,
  358. InitListExpr *ILE, bool &RequiresSecondPass,
  359. bool FillWithNoInit);
  360. void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  361. const InitializedEntity &ParentEntity,
  362. InitListExpr *ILE, bool &RequiresSecondPass,
  363. bool FillWithNoInit = false);
  364. void FillInEmptyInitializations(const InitializedEntity &Entity,
  365. InitListExpr *ILE, bool &RequiresSecondPass,
  366. InitListExpr *OuterILE, unsigned OuterIndex,
  367. bool FillWithNoInit = false);
  368. bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
  369. Expr *InitExpr, FieldDecl *Field,
  370. bool TopLevelObject);
  371. void CheckEmptyInitializable(const InitializedEntity &Entity,
  372. SourceLocation Loc);
  373. public:
  374. InitListChecker(Sema &S, const InitializedEntity &Entity,
  375. InitListExpr *IL, QualType &T, bool VerifyOnly,
  376. bool TreatUnavailableAsInvalid);
  377. bool HadError() { return hadError; }
  378. // Retrieves the fully-structured initializer list used for
  379. // semantic analysis and code generation.
  380. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
  381. };
  382. } // end anonymous namespace
  383. ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
  384. SourceLocation Loc,
  385. const InitializedEntity &Entity,
  386. bool VerifyOnly,
  387. bool TreatUnavailableAsInvalid) {
  388. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  389. true);
  390. MultiExprArg SubInit;
  391. Expr *InitExpr;
  392. InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
  393. // C++ [dcl.init.aggr]p7:
  394. // If there are fewer initializer-clauses in the list than there are
  395. // members in the aggregate, then each member not explicitly initialized
  396. // ...
  397. bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
  398. Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
  399. if (EmptyInitList) {
  400. // C++1y / DR1070:
  401. // shall be initialized [...] from an empty initializer list.
  402. //
  403. // We apply the resolution of this DR to C++11 but not C++98, since C++98
  404. // does not have useful semantics for initialization from an init list.
  405. // We treat this as copy-initialization, because aggregate initialization
  406. // always performs copy-initialization on its elements.
  407. //
  408. // Only do this if we're initializing a class type, to avoid filling in
  409. // the initializer list where possible.
  410. InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
  411. InitListExpr(SemaRef.Context, Loc, None, Loc);
  412. InitExpr->setType(SemaRef.Context.VoidTy);
  413. SubInit = InitExpr;
  414. Kind = InitializationKind::CreateCopy(Loc, Loc);
  415. } else {
  416. // C++03:
  417. // shall be value-initialized.
  418. }
  419. InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
  420. // libstdc++4.6 marks the vector default constructor as explicit in
  421. // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
  422. // stlport does so too. Look for std::__debug for libstdc++, and for
  423. // std:: for stlport. This is effectively a compiler-side implementation of
  424. // LWG2193.
  425. if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
  426. InitializationSequence::FK_ExplicitConstructor) {
  427. OverloadCandidateSet::iterator Best;
  428. OverloadingResult O =
  429. InitSeq.getFailedCandidateSet()
  430. .BestViableFunction(SemaRef, Kind.getLocation(), Best);
  431. (void)O;
  432. assert(O == OR_Success && "Inconsistent overload resolution");
  433. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  434. CXXRecordDecl *R = CtorDecl->getParent();
  435. if (CtorDecl->getMinRequiredArguments() == 0 &&
  436. CtorDecl->isExplicit() && R->getDeclName() &&
  437. SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
  438. bool IsInStd = false;
  439. for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
  440. ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
  441. if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
  442. IsInStd = true;
  443. }
  444. if (IsInStd && llvm::StringSwitch<bool>(R->getName())
  445. .Cases("basic_string", "deque", "forward_list", true)
  446. .Cases("list", "map", "multimap", "multiset", true)
  447. .Cases("priority_queue", "queue", "set", "stack", true)
  448. .Cases("unordered_map", "unordered_set", "vector", true)
  449. .Default(false)) {
  450. InitSeq.InitializeFrom(
  451. SemaRef, Entity,
  452. InitializationKind::CreateValue(Loc, Loc, Loc, true),
  453. MultiExprArg(), /*TopLevelOfInitList=*/false,
  454. TreatUnavailableAsInvalid);
  455. // Emit a warning for this. System header warnings aren't shown
  456. // by default, but people working on system headers should see it.
  457. if (!VerifyOnly) {
  458. SemaRef.Diag(CtorDecl->getLocation(),
  459. diag::warn_invalid_initializer_from_system_header);
  460. if (Entity.getKind() == InitializedEntity::EK_Member)
  461. SemaRef.Diag(Entity.getDecl()->getLocation(),
  462. diag::note_used_in_initialization_here);
  463. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
  464. SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
  465. }
  466. }
  467. }
  468. }
  469. if (!InitSeq) {
  470. if (!VerifyOnly) {
  471. InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
  472. if (Entity.getKind() == InitializedEntity::EK_Member)
  473. SemaRef.Diag(Entity.getDecl()->getLocation(),
  474. diag::note_in_omitted_aggregate_initializer)
  475. << /*field*/1 << Entity.getDecl();
  476. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
  477. bool IsTrailingArrayNewMember =
  478. Entity.getParent() &&
  479. Entity.getParent()->isVariableLengthArrayNew();
  480. SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
  481. << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
  482. << Entity.getElementIndex();
  483. }
  484. }
  485. return ExprError();
  486. }
  487. return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
  488. : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
  489. }
  490. void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
  491. SourceLocation Loc) {
  492. assert(VerifyOnly &&
  493. "CheckEmptyInitializable is only inteded for verification mode.");
  494. if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
  495. TreatUnavailableAsInvalid).isInvalid())
  496. hadError = true;
  497. }
  498. void InitListChecker::FillInEmptyInitForBase(
  499. unsigned Init, const CXXBaseSpecifier &Base,
  500. const InitializedEntity &ParentEntity, InitListExpr *ILE,
  501. bool &RequiresSecondPass, bool FillWithNoInit) {
  502. assert(Init < ILE->getNumInits() && "should have been expanded");
  503. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  504. SemaRef.Context, &Base, false, &ParentEntity);
  505. if (!ILE->getInit(Init)) {
  506. ExprResult BaseInit =
  507. FillWithNoInit
  508. ? new (SemaRef.Context) NoInitExpr(Base.getType())
  509. : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
  510. /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
  511. if (BaseInit.isInvalid()) {
  512. hadError = true;
  513. return;
  514. }
  515. ILE->setInit(Init, BaseInit.getAs<Expr>());
  516. } else if (InitListExpr *InnerILE =
  517. dyn_cast<InitListExpr>(ILE->getInit(Init))) {
  518. FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
  519. ILE, Init, FillWithNoInit);
  520. } else if (DesignatedInitUpdateExpr *InnerDIUE =
  521. dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
  522. FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
  523. RequiresSecondPass, ILE, Init,
  524. /*FillWithNoInit =*/true);
  525. }
  526. }
  527. void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  528. const InitializedEntity &ParentEntity,
  529. InitListExpr *ILE,
  530. bool &RequiresSecondPass,
  531. bool FillWithNoInit) {
  532. SourceLocation Loc = ILE->getEndLoc();
  533. unsigned NumInits = ILE->getNumInits();
  534. InitializedEntity MemberEntity
  535. = InitializedEntity::InitializeMember(Field, &ParentEntity);
  536. if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
  537. if (!RType->getDecl()->isUnion())
  538. assert(Init < NumInits && "This ILE should have been expanded");
  539. if (Init >= NumInits || !ILE->getInit(Init)) {
  540. if (FillWithNoInit) {
  541. Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
  542. if (Init < NumInits)
  543. ILE->setInit(Init, Filler);
  544. else
  545. ILE->updateInit(SemaRef.Context, Init, Filler);
  546. return;
  547. }
  548. // C++1y [dcl.init.aggr]p7:
  549. // If there are fewer initializer-clauses in the list than there are
  550. // members in the aggregate, then each member not explicitly initialized
  551. // shall be initialized from its brace-or-equal-initializer [...]
  552. if (Field->hasInClassInitializer()) {
  553. ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
  554. if (DIE.isInvalid()) {
  555. hadError = true;
  556. return;
  557. }
  558. SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
  559. if (Init < NumInits)
  560. ILE->setInit(Init, DIE.get());
  561. else {
  562. ILE->updateInit(SemaRef.Context, Init, DIE.get());
  563. RequiresSecondPass = true;
  564. }
  565. return;
  566. }
  567. if (Field->getType()->isReferenceType()) {
  568. // C++ [dcl.init.aggr]p9:
  569. // If an incomplete or empty initializer-list leaves a
  570. // member of reference type uninitialized, the program is
  571. // ill-formed.
  572. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
  573. << Field->getType()
  574. << ILE->getSyntacticForm()->getSourceRange();
  575. SemaRef.Diag(Field->getLocation(),
  576. diag::note_uninit_reference_member);
  577. hadError = true;
  578. return;
  579. }
  580. ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
  581. /*VerifyOnly*/false,
  582. TreatUnavailableAsInvalid);
  583. if (MemberInit.isInvalid()) {
  584. hadError = true;
  585. return;
  586. }
  587. if (hadError) {
  588. // Do nothing
  589. } else if (Init < NumInits) {
  590. ILE->setInit(Init, MemberInit.getAs<Expr>());
  591. } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
  592. // Empty initialization requires a constructor call, so
  593. // extend the initializer list to include the constructor
  594. // call and make a note that we'll need to take another pass
  595. // through the initializer list.
  596. ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
  597. RequiresSecondPass = true;
  598. }
  599. } else if (InitListExpr *InnerILE
  600. = dyn_cast<InitListExpr>(ILE->getInit(Init)))
  601. FillInEmptyInitializations(MemberEntity, InnerILE,
  602. RequiresSecondPass, ILE, Init, FillWithNoInit);
  603. else if (DesignatedInitUpdateExpr *InnerDIUE
  604. = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
  605. FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
  606. RequiresSecondPass, ILE, Init,
  607. /*FillWithNoInit =*/true);
  608. }
  609. /// Recursively replaces NULL values within the given initializer list
  610. /// with expressions that perform value-initialization of the
  611. /// appropriate type, and finish off the InitListExpr formation.
  612. void
  613. InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
  614. InitListExpr *ILE,
  615. bool &RequiresSecondPass,
  616. InitListExpr *OuterILE,
  617. unsigned OuterIndex,
  618. bool FillWithNoInit) {
  619. assert((ILE->getType() != SemaRef.Context.VoidTy) &&
  620. "Should not have void type");
  621. // If this is a nested initializer list, we might have changed its contents
  622. // (and therefore some of its properties, such as instantiation-dependence)
  623. // while filling it in. Inform the outer initializer list so that its state
  624. // can be updated to match.
  625. // FIXME: We should fully build the inner initializers before constructing
  626. // the outer InitListExpr instead of mutating AST nodes after they have
  627. // been used as subexpressions of other nodes.
  628. struct UpdateOuterILEWithUpdatedInit {
  629. InitListExpr *Outer;
  630. unsigned OuterIndex;
  631. ~UpdateOuterILEWithUpdatedInit() {
  632. if (Outer)
  633. Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
  634. }
  635. } UpdateOuterRAII = {OuterILE, OuterIndex};
  636. // A transparent ILE is not performing aggregate initialization and should
  637. // not be filled in.
  638. if (ILE->isTransparent())
  639. return;
  640. if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
  641. const RecordDecl *RDecl = RType->getDecl();
  642. if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
  643. FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
  644. Entity, ILE, RequiresSecondPass, FillWithNoInit);
  645. else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
  646. cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
  647. for (auto *Field : RDecl->fields()) {
  648. if (Field->hasInClassInitializer()) {
  649. FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
  650. FillWithNoInit);
  651. break;
  652. }
  653. }
  654. } else {
  655. // The fields beyond ILE->getNumInits() are default initialized, so in
  656. // order to leave them uninitialized, the ILE is expanded and the extra
  657. // fields are then filled with NoInitExpr.
  658. unsigned NumElems = numStructUnionElements(ILE->getType());
  659. if (RDecl->hasFlexibleArrayMember())
  660. ++NumElems;
  661. if (ILE->getNumInits() < NumElems)
  662. ILE->resizeInits(SemaRef.Context, NumElems);
  663. unsigned Init = 0;
  664. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
  665. for (auto &Base : CXXRD->bases()) {
  666. if (hadError)
  667. return;
  668. FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
  669. FillWithNoInit);
  670. ++Init;
  671. }
  672. }
  673. for (auto *Field : RDecl->fields()) {
  674. if (Field->isUnnamedBitfield())
  675. continue;
  676. if (hadError)
  677. return;
  678. FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
  679. FillWithNoInit);
  680. if (hadError)
  681. return;
  682. ++Init;
  683. // Only look at the first initialization of a union.
  684. if (RDecl->isUnion())
  685. break;
  686. }
  687. }
  688. return;
  689. }
  690. QualType ElementType;
  691. InitializedEntity ElementEntity = Entity;
  692. unsigned NumInits = ILE->getNumInits();
  693. unsigned NumElements = NumInits;
  694. if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
  695. ElementType = AType->getElementType();
  696. if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
  697. NumElements = CAType->getSize().getZExtValue();
  698. // For an array new with an unknown bound, ask for one additional element
  699. // in order to populate the array filler.
  700. if (Entity.isVariableLengthArrayNew())
  701. ++NumElements;
  702. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  703. 0, Entity);
  704. } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
  705. ElementType = VType->getElementType();
  706. NumElements = VType->getNumElements();
  707. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  708. 0, Entity);
  709. } else
  710. ElementType = ILE->getType();
  711. for (unsigned Init = 0; Init != NumElements; ++Init) {
  712. if (hadError)
  713. return;
  714. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
  715. ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
  716. ElementEntity.setElementIndex(Init);
  717. if (Init >= NumInits && ILE->hasArrayFiller())
  718. return;
  719. Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
  720. if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
  721. ILE->setInit(Init, ILE->getArrayFiller());
  722. else if (!InitExpr && !ILE->hasArrayFiller()) {
  723. Expr *Filler = nullptr;
  724. if (FillWithNoInit)
  725. Filler = new (SemaRef.Context) NoInitExpr(ElementType);
  726. else {
  727. ExprResult ElementInit =
  728. PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
  729. /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
  730. if (ElementInit.isInvalid()) {
  731. hadError = true;
  732. return;
  733. }
  734. Filler = ElementInit.getAs<Expr>();
  735. }
  736. if (hadError) {
  737. // Do nothing
  738. } else if (Init < NumInits) {
  739. // For arrays, just set the expression used for value-initialization
  740. // of the "holes" in the array.
  741. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
  742. ILE->setArrayFiller(Filler);
  743. else
  744. ILE->setInit(Init, Filler);
  745. } else {
  746. // For arrays, just set the expression used for value-initialization
  747. // of the rest of elements and exit.
  748. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  749. ILE->setArrayFiller(Filler);
  750. return;
  751. }
  752. if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
  753. // Empty initialization requires a constructor call, so
  754. // extend the initializer list to include the constructor
  755. // call and make a note that we'll need to take another pass
  756. // through the initializer list.
  757. ILE->updateInit(SemaRef.Context, Init, Filler);
  758. RequiresSecondPass = true;
  759. }
  760. }
  761. } else if (InitListExpr *InnerILE
  762. = dyn_cast_or_null<InitListExpr>(InitExpr))
  763. FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
  764. ILE, Init, FillWithNoInit);
  765. else if (DesignatedInitUpdateExpr *InnerDIUE
  766. = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
  767. FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
  768. RequiresSecondPass, ILE, Init,
  769. /*FillWithNoInit =*/true);
  770. }
  771. }
  772. InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
  773. InitListExpr *IL, QualType &T,
  774. bool VerifyOnly,
  775. bool TreatUnavailableAsInvalid)
  776. : SemaRef(S), VerifyOnly(VerifyOnly),
  777. TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
  778. // FIXME: Check that IL isn't already the semantic form of some other
  779. // InitListExpr. If it is, we'd create a broken AST.
  780. hadError = false;
  781. FullyStructuredList =
  782. getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
  783. CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
  784. /*TopLevelObject=*/true);
  785. if (!hadError && !VerifyOnly) {
  786. bool RequiresSecondPass = false;
  787. FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
  788. /*OuterILE=*/nullptr, /*OuterIndex=*/0);
  789. if (RequiresSecondPass && !hadError)
  790. FillInEmptyInitializations(Entity, FullyStructuredList,
  791. RequiresSecondPass, nullptr, 0);
  792. }
  793. }
  794. int InitListChecker::numArrayElements(QualType DeclType) {
  795. // FIXME: use a proper constant
  796. int maxElements = 0x7FFFFFFF;
  797. if (const ConstantArrayType *CAT =
  798. SemaRef.Context.getAsConstantArrayType(DeclType)) {
  799. maxElements = static_cast<int>(CAT->getSize().getZExtValue());
  800. }
  801. return maxElements;
  802. }
  803. int InitListChecker::numStructUnionElements(QualType DeclType) {
  804. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  805. int InitializableMembers = 0;
  806. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
  807. InitializableMembers += CXXRD->getNumBases();
  808. for (const auto *Field : structDecl->fields())
  809. if (!Field->isUnnamedBitfield())
  810. ++InitializableMembers;
  811. if (structDecl->isUnion())
  812. return std::min(InitializableMembers, 1);
  813. return InitializableMembers - structDecl->hasFlexibleArrayMember();
  814. }
  815. /// Determine whether Entity is an entity for which it is idiomatic to elide
  816. /// the braces in aggregate initialization.
  817. static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
  818. // Recursive initialization of the one and only field within an aggregate
  819. // class is considered idiomatic. This case arises in particular for
  820. // initialization of std::array, where the C++ standard suggests the idiom of
  821. //
  822. // std::array<T, N> arr = {1, 2, 3};
  823. //
  824. // (where std::array is an aggregate struct containing a single array field.
  825. // FIXME: Should aggregate initialization of a struct with a single
  826. // base class and no members also suppress the warning?
  827. if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
  828. return false;
  829. auto *ParentRD =
  830. Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
  831. if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
  832. if (CXXRD->getNumBases())
  833. return false;
  834. auto FieldIt = ParentRD->field_begin();
  835. assert(FieldIt != ParentRD->field_end() &&
  836. "no fields but have initializer for member?");
  837. return ++FieldIt == ParentRD->field_end();
  838. }
  839. /// Check whether the range of the initializer \p ParentIList from element
  840. /// \p Index onwards can be used to initialize an object of type \p T. Update
  841. /// \p Index to indicate how many elements of the list were consumed.
  842. ///
  843. /// This also fills in \p StructuredList, from element \p StructuredIndex
  844. /// onwards, with the fully-braced, desugared form of the initialization.
  845. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
  846. InitListExpr *ParentIList,
  847. QualType T, unsigned &Index,
  848. InitListExpr *StructuredList,
  849. unsigned &StructuredIndex) {
  850. int maxElements = 0;
  851. if (T->isArrayType())
  852. maxElements = numArrayElements(T);
  853. else if (T->isRecordType())
  854. maxElements = numStructUnionElements(T);
  855. else if (T->isVectorType())
  856. maxElements = T->getAs<VectorType>()->getNumElements();
  857. else
  858. llvm_unreachable("CheckImplicitInitList(): Illegal type");
  859. if (maxElements == 0) {
  860. if (!VerifyOnly)
  861. SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
  862. diag::err_implicit_empty_initializer);
  863. ++Index;
  864. hadError = true;
  865. return;
  866. }
  867. // Build a structured initializer list corresponding to this subobject.
  868. InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
  869. ParentIList, Index, T, StructuredList, StructuredIndex,
  870. SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
  871. ParentIList->getSourceRange().getEnd()));
  872. unsigned StructuredSubobjectInitIndex = 0;
  873. // Check the element types and build the structural subobject.
  874. unsigned StartIndex = Index;
  875. CheckListElementTypes(Entity, ParentIList, T,
  876. /*SubobjectIsDesignatorContext=*/false, Index,
  877. StructuredSubobjectInitList,
  878. StructuredSubobjectInitIndex);
  879. if (!VerifyOnly) {
  880. StructuredSubobjectInitList->setType(T);
  881. unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
  882. // Update the structured sub-object initializer so that it's ending
  883. // range corresponds with the end of the last initializer it used.
  884. if (EndIndex < ParentIList->getNumInits() &&
  885. ParentIList->getInit(EndIndex)) {
  886. SourceLocation EndLoc
  887. = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
  888. StructuredSubobjectInitList->setRBraceLoc(EndLoc);
  889. }
  890. // Complain about missing braces.
  891. if ((T->isArrayType() || T->isRecordType()) &&
  892. !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
  893. !isIdiomaticBraceElisionEntity(Entity)) {
  894. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  895. diag::warn_missing_braces)
  896. << StructuredSubobjectInitList->getSourceRange()
  897. << FixItHint::CreateInsertion(
  898. StructuredSubobjectInitList->getBeginLoc(), "{")
  899. << FixItHint::CreateInsertion(
  900. SemaRef.getLocForEndOfToken(
  901. StructuredSubobjectInitList->getEndLoc()),
  902. "}");
  903. }
  904. // Warn if this type won't be an aggregate in future versions of C++.
  905. auto *CXXRD = T->getAsCXXRecordDecl();
  906. if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  907. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  908. diag::warn_cxx2a_compat_aggregate_init_with_ctors)
  909. << StructuredSubobjectInitList->getSourceRange() << T;
  910. }
  911. }
  912. }
  913. /// Warn that \p Entity was of scalar type and was initialized by a
  914. /// single-element braced initializer list.
  915. static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
  916. SourceRange Braces) {
  917. // Don't warn during template instantiation. If the initialization was
  918. // non-dependent, we warned during the initial parse; otherwise, the
  919. // type might not be scalar in some uses of the template.
  920. if (S.inTemplateInstantiation())
  921. return;
  922. unsigned DiagID = 0;
  923. switch (Entity.getKind()) {
  924. case InitializedEntity::EK_VectorElement:
  925. case InitializedEntity::EK_ComplexElement:
  926. case InitializedEntity::EK_ArrayElement:
  927. case InitializedEntity::EK_Parameter:
  928. case InitializedEntity::EK_Parameter_CF_Audited:
  929. case InitializedEntity::EK_Result:
  930. // Extra braces here are suspicious.
  931. DiagID = diag::warn_braces_around_scalar_init;
  932. break;
  933. case InitializedEntity::EK_Member:
  934. // Warn on aggregate initialization but not on ctor init list or
  935. // default member initializer.
  936. if (Entity.getParent())
  937. DiagID = diag::warn_braces_around_scalar_init;
  938. break;
  939. case InitializedEntity::EK_Variable:
  940. case InitializedEntity::EK_LambdaCapture:
  941. // No warning, might be direct-list-initialization.
  942. // FIXME: Should we warn for copy-list-initialization in these cases?
  943. break;
  944. case InitializedEntity::EK_New:
  945. case InitializedEntity::EK_Temporary:
  946. case InitializedEntity::EK_CompoundLiteralInit:
  947. // No warning, braces are part of the syntax of the underlying construct.
  948. break;
  949. case InitializedEntity::EK_RelatedResult:
  950. // No warning, we already warned when initializing the result.
  951. break;
  952. case InitializedEntity::EK_Exception:
  953. case InitializedEntity::EK_Base:
  954. case InitializedEntity::EK_Delegating:
  955. case InitializedEntity::EK_BlockElement:
  956. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  957. case InitializedEntity::EK_Binding:
  958. case InitializedEntity::EK_StmtExprResult:
  959. llvm_unreachable("unexpected braced scalar init");
  960. }
  961. if (DiagID) {
  962. S.Diag(Braces.getBegin(), DiagID)
  963. << Braces
  964. << FixItHint::CreateRemoval(Braces.getBegin())
  965. << FixItHint::CreateRemoval(Braces.getEnd());
  966. }
  967. }
  968. /// Check whether the initializer \p IList (that was written with explicit
  969. /// braces) can be used to initialize an object of type \p T.
  970. ///
  971. /// This also fills in \p StructuredList with the fully-braced, desugared
  972. /// form of the initialization.
  973. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
  974. InitListExpr *IList, QualType &T,
  975. InitListExpr *StructuredList,
  976. bool TopLevelObject) {
  977. if (!VerifyOnly) {
  978. SyntacticToSemantic[IList] = StructuredList;
  979. StructuredList->setSyntacticForm(IList);
  980. }
  981. unsigned Index = 0, StructuredIndex = 0;
  982. CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
  983. Index, StructuredList, StructuredIndex, TopLevelObject);
  984. if (!VerifyOnly) {
  985. QualType ExprTy = T;
  986. if (!ExprTy->isArrayType())
  987. ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
  988. IList->setType(ExprTy);
  989. StructuredList->setType(ExprTy);
  990. }
  991. if (hadError)
  992. return;
  993. if (Index < IList->getNumInits()) {
  994. // We have leftover initializers
  995. if (VerifyOnly) {
  996. if (SemaRef.getLangOpts().CPlusPlus ||
  997. (SemaRef.getLangOpts().OpenCL &&
  998. IList->getType()->isVectorType())) {
  999. hadError = true;
  1000. }
  1001. return;
  1002. }
  1003. if (StructuredIndex == 1 &&
  1004. IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
  1005. SIF_None) {
  1006. unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
  1007. if (SemaRef.getLangOpts().CPlusPlus) {
  1008. DK = diag::err_excess_initializers_in_char_array_initializer;
  1009. hadError = true;
  1010. }
  1011. // Special-case
  1012. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1013. << IList->getInit(Index)->getSourceRange();
  1014. } else if (!T->isIncompleteType()) {
  1015. // Don't complain for incomplete types, since we'll get an error
  1016. // elsewhere
  1017. QualType CurrentObjectType = StructuredList->getType();
  1018. int initKind =
  1019. CurrentObjectType->isArrayType()? 0 :
  1020. CurrentObjectType->isVectorType()? 1 :
  1021. CurrentObjectType->isScalarType()? 2 :
  1022. CurrentObjectType->isUnionType()? 3 :
  1023. 4;
  1024. unsigned DK = diag::ext_excess_initializers;
  1025. if (SemaRef.getLangOpts().CPlusPlus) {
  1026. DK = diag::err_excess_initializers;
  1027. hadError = true;
  1028. }
  1029. if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
  1030. DK = diag::err_excess_initializers;
  1031. hadError = true;
  1032. }
  1033. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1034. << initKind << IList->getInit(Index)->getSourceRange();
  1035. }
  1036. }
  1037. if (!VerifyOnly) {
  1038. if (T->isScalarType() && IList->getNumInits() == 1 &&
  1039. !isa<InitListExpr>(IList->getInit(0)))
  1040. warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
  1041. // Warn if this is a class type that won't be an aggregate in future
  1042. // versions of C++.
  1043. auto *CXXRD = T->getAsCXXRecordDecl();
  1044. if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  1045. // Don't warn if there's an equivalent default constructor that would be
  1046. // used instead.
  1047. bool HasEquivCtor = false;
  1048. if (IList->getNumInits() == 0) {
  1049. auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
  1050. HasEquivCtor = CD && !CD->isDeleted();
  1051. }
  1052. if (!HasEquivCtor) {
  1053. SemaRef.Diag(IList->getBeginLoc(),
  1054. diag::warn_cxx2a_compat_aggregate_init_with_ctors)
  1055. << IList->getSourceRange() << T;
  1056. }
  1057. }
  1058. }
  1059. }
  1060. void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
  1061. InitListExpr *IList,
  1062. QualType &DeclType,
  1063. bool SubobjectIsDesignatorContext,
  1064. unsigned &Index,
  1065. InitListExpr *StructuredList,
  1066. unsigned &StructuredIndex,
  1067. bool TopLevelObject) {
  1068. if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
  1069. // Explicitly braced initializer for complex type can be real+imaginary
  1070. // parts.
  1071. CheckComplexType(Entity, IList, DeclType, Index,
  1072. StructuredList, StructuredIndex);
  1073. } else if (DeclType->isScalarType()) {
  1074. CheckScalarType(Entity, IList, DeclType, Index,
  1075. StructuredList, StructuredIndex);
  1076. } else if (DeclType->isVectorType()) {
  1077. CheckVectorType(Entity, IList, DeclType, Index,
  1078. StructuredList, StructuredIndex);
  1079. } else if (DeclType->isRecordType()) {
  1080. assert(DeclType->isAggregateType() &&
  1081. "non-aggregate records should be handed in CheckSubElementType");
  1082. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1083. auto Bases =
  1084. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  1085. CXXRecordDecl::base_class_iterator());
  1086. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1087. Bases = CXXRD->bases();
  1088. CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
  1089. SubobjectIsDesignatorContext, Index, StructuredList,
  1090. StructuredIndex, TopLevelObject);
  1091. } else if (DeclType->isArrayType()) {
  1092. llvm::APSInt Zero(
  1093. SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
  1094. false);
  1095. CheckArrayType(Entity, IList, DeclType, Zero,
  1096. SubobjectIsDesignatorContext, Index,
  1097. StructuredList, StructuredIndex);
  1098. } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
  1099. // This type is invalid, issue a diagnostic.
  1100. ++Index;
  1101. if (!VerifyOnly)
  1102. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1103. << DeclType;
  1104. hadError = true;
  1105. } else if (DeclType->isReferenceType()) {
  1106. CheckReferenceType(Entity, IList, DeclType, Index,
  1107. StructuredList, StructuredIndex);
  1108. } else if (DeclType->isObjCObjectType()) {
  1109. if (!VerifyOnly)
  1110. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
  1111. hadError = true;
  1112. } else if (DeclType->isOCLIntelSubgroupAVCType()) {
  1113. // Checks for scalar type are sufficient for these types too.
  1114. CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1115. StructuredIndex);
  1116. } else {
  1117. if (!VerifyOnly)
  1118. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1119. << DeclType;
  1120. hadError = true;
  1121. }
  1122. }
  1123. void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
  1124. InitListExpr *IList,
  1125. QualType ElemType,
  1126. unsigned &Index,
  1127. InitListExpr *StructuredList,
  1128. unsigned &StructuredIndex) {
  1129. Expr *expr = IList->getInit(Index);
  1130. if (ElemType->isReferenceType())
  1131. return CheckReferenceType(Entity, IList, ElemType, Index,
  1132. StructuredList, StructuredIndex);
  1133. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
  1134. if (SubInitList->getNumInits() == 1 &&
  1135. IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
  1136. SIF_None) {
  1137. expr = SubInitList->getInit(0);
  1138. } else if (!SemaRef.getLangOpts().CPlusPlus) {
  1139. InitListExpr *InnerStructuredList
  1140. = getStructuredSubobjectInit(IList, Index, ElemType,
  1141. StructuredList, StructuredIndex,
  1142. SubInitList->getSourceRange(), true);
  1143. CheckExplicitInitList(Entity, SubInitList, ElemType,
  1144. InnerStructuredList);
  1145. if (!hadError && !VerifyOnly) {
  1146. bool RequiresSecondPass = false;
  1147. FillInEmptyInitializations(Entity, InnerStructuredList,
  1148. RequiresSecondPass, StructuredList,
  1149. StructuredIndex);
  1150. if (RequiresSecondPass && !hadError)
  1151. FillInEmptyInitializations(Entity, InnerStructuredList,
  1152. RequiresSecondPass, StructuredList,
  1153. StructuredIndex);
  1154. }
  1155. ++StructuredIndex;
  1156. ++Index;
  1157. return;
  1158. }
  1159. // C++ initialization is handled later.
  1160. } else if (isa<ImplicitValueInitExpr>(expr)) {
  1161. // This happens during template instantiation when we see an InitListExpr
  1162. // that we've already checked once.
  1163. assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
  1164. "found implicit initialization for the wrong type");
  1165. if (!VerifyOnly)
  1166. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1167. ++Index;
  1168. return;
  1169. }
  1170. if (SemaRef.getLangOpts().CPlusPlus) {
  1171. // C++ [dcl.init.aggr]p2:
  1172. // Each member is copy-initialized from the corresponding
  1173. // initializer-clause.
  1174. // FIXME: Better EqualLoc?
  1175. InitializationKind Kind =
  1176. InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
  1177. InitializationSequence Seq(SemaRef, Entity, Kind, expr,
  1178. /*TopLevelOfInitList*/ true);
  1179. // C++14 [dcl.init.aggr]p13:
  1180. // If the assignment-expression can initialize a member, the member is
  1181. // initialized. Otherwise [...] brace elision is assumed
  1182. //
  1183. // Brace elision is never performed if the element is not an
  1184. // assignment-expression.
  1185. if (Seq || isa<InitListExpr>(expr)) {
  1186. if (!VerifyOnly) {
  1187. ExprResult Result =
  1188. Seq.Perform(SemaRef, Entity, Kind, expr);
  1189. if (Result.isInvalid())
  1190. hadError = true;
  1191. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1192. Result.getAs<Expr>());
  1193. } else if (!Seq)
  1194. hadError = true;
  1195. ++Index;
  1196. return;
  1197. }
  1198. // Fall through for subaggregate initialization
  1199. } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
  1200. // FIXME: Need to handle atomic aggregate types with implicit init lists.
  1201. return CheckScalarType(Entity, IList, ElemType, Index,
  1202. StructuredList, StructuredIndex);
  1203. } else if (const ArrayType *arrayType =
  1204. SemaRef.Context.getAsArrayType(ElemType)) {
  1205. // arrayType can be incomplete if we're initializing a flexible
  1206. // array member. There's nothing we can do with the completed
  1207. // type here, though.
  1208. if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
  1209. if (!VerifyOnly) {
  1210. CheckStringInit(expr, ElemType, arrayType, SemaRef);
  1211. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1212. }
  1213. ++Index;
  1214. return;
  1215. }
  1216. // Fall through for subaggregate initialization.
  1217. } else {
  1218. assert((ElemType->isRecordType() || ElemType->isVectorType() ||
  1219. ElemType->isOpenCLSpecificType()) && "Unexpected type");
  1220. // C99 6.7.8p13:
  1221. //
  1222. // The initializer for a structure or union object that has
  1223. // automatic storage duration shall be either an initializer
  1224. // list as described below, or a single expression that has
  1225. // compatible structure or union type. In the latter case, the
  1226. // initial value of the object, including unnamed members, is
  1227. // that of the expression.
  1228. ExprResult ExprRes = expr;
  1229. if (SemaRef.CheckSingleAssignmentConstraints(
  1230. ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
  1231. if (ExprRes.isInvalid())
  1232. hadError = true;
  1233. else {
  1234. ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
  1235. if (ExprRes.isInvalid())
  1236. hadError = true;
  1237. }
  1238. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1239. ExprRes.getAs<Expr>());
  1240. ++Index;
  1241. return;
  1242. }
  1243. ExprRes.get();
  1244. // Fall through for subaggregate initialization
  1245. }
  1246. // C++ [dcl.init.aggr]p12:
  1247. //
  1248. // [...] Otherwise, if the member is itself a non-empty
  1249. // subaggregate, brace elision is assumed and the initializer is
  1250. // considered for the initialization of the first member of
  1251. // the subaggregate.
  1252. // OpenCL vector initializer is handled elsewhere.
  1253. if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
  1254. ElemType->isAggregateType()) {
  1255. CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
  1256. StructuredIndex);
  1257. ++StructuredIndex;
  1258. } else {
  1259. if (!VerifyOnly) {
  1260. // We cannot initialize this element, so let
  1261. // PerformCopyInitialization produce the appropriate diagnostic.
  1262. SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
  1263. /*TopLevelOfInitList=*/true);
  1264. }
  1265. hadError = true;
  1266. ++Index;
  1267. ++StructuredIndex;
  1268. }
  1269. }
  1270. void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
  1271. InitListExpr *IList, QualType DeclType,
  1272. unsigned &Index,
  1273. InitListExpr *StructuredList,
  1274. unsigned &StructuredIndex) {
  1275. assert(Index == 0 && "Index in explicit init list must be zero");
  1276. // As an extension, clang supports complex initializers, which initialize
  1277. // a complex number component-wise. When an explicit initializer list for
  1278. // a complex number contains two two initializers, this extension kicks in:
  1279. // it exepcts the initializer list to contain two elements convertible to
  1280. // the element type of the complex type. The first element initializes
  1281. // the real part, and the second element intitializes the imaginary part.
  1282. if (IList->getNumInits() != 2)
  1283. return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1284. StructuredIndex);
  1285. // This is an extension in C. (The builtin _Complex type does not exist
  1286. // in the C++ standard.)
  1287. if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
  1288. SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
  1289. << IList->getSourceRange();
  1290. // Initialize the complex number.
  1291. QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
  1292. InitializedEntity ElementEntity =
  1293. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1294. for (unsigned i = 0; i < 2; ++i) {
  1295. ElementEntity.setElementIndex(Index);
  1296. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1297. StructuredList, StructuredIndex);
  1298. }
  1299. }
  1300. void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
  1301. InitListExpr *IList, QualType DeclType,
  1302. unsigned &Index,
  1303. InitListExpr *StructuredList,
  1304. unsigned &StructuredIndex) {
  1305. if (Index >= IList->getNumInits()) {
  1306. if (!VerifyOnly)
  1307. SemaRef.Diag(IList->getBeginLoc(),
  1308. SemaRef.getLangOpts().CPlusPlus11
  1309. ? diag::warn_cxx98_compat_empty_scalar_initializer
  1310. : diag::err_empty_scalar_initializer)
  1311. << IList->getSourceRange();
  1312. hadError = !SemaRef.getLangOpts().CPlusPlus11;
  1313. ++Index;
  1314. ++StructuredIndex;
  1315. return;
  1316. }
  1317. Expr *expr = IList->getInit(Index);
  1318. if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
  1319. // FIXME: This is invalid, and accepting it causes overload resolution
  1320. // to pick the wrong overload in some corner cases.
  1321. if (!VerifyOnly)
  1322. SemaRef.Diag(SubIList->getBeginLoc(),
  1323. diag::ext_many_braces_around_scalar_init)
  1324. << SubIList->getSourceRange();
  1325. CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
  1326. StructuredIndex);
  1327. return;
  1328. } else if (isa<DesignatedInitExpr>(expr)) {
  1329. if (!VerifyOnly)
  1330. SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
  1331. << DeclType << expr->getSourceRange();
  1332. hadError = true;
  1333. ++Index;
  1334. ++StructuredIndex;
  1335. return;
  1336. }
  1337. if (VerifyOnly) {
  1338. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1339. hadError = true;
  1340. ++Index;
  1341. return;
  1342. }
  1343. ExprResult Result =
  1344. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1345. /*TopLevelOfInitList=*/true);
  1346. Expr *ResultExpr = nullptr;
  1347. if (Result.isInvalid())
  1348. hadError = true; // types weren't compatible.
  1349. else {
  1350. ResultExpr = Result.getAs<Expr>();
  1351. if (ResultExpr != expr) {
  1352. // The type was promoted, update initializer list.
  1353. IList->setInit(Index, ResultExpr);
  1354. }
  1355. }
  1356. if (hadError)
  1357. ++StructuredIndex;
  1358. else
  1359. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  1360. ++Index;
  1361. }
  1362. void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
  1363. InitListExpr *IList, QualType DeclType,
  1364. unsigned &Index,
  1365. InitListExpr *StructuredList,
  1366. unsigned &StructuredIndex) {
  1367. if (Index >= IList->getNumInits()) {
  1368. // FIXME: It would be wonderful if we could point at the actual member. In
  1369. // general, it would be useful to pass location information down the stack,
  1370. // so that we know the location (or decl) of the "current object" being
  1371. // initialized.
  1372. if (!VerifyOnly)
  1373. SemaRef.Diag(IList->getBeginLoc(),
  1374. diag::err_init_reference_member_uninitialized)
  1375. << DeclType << IList->getSourceRange();
  1376. hadError = true;
  1377. ++Index;
  1378. ++StructuredIndex;
  1379. return;
  1380. }
  1381. Expr *expr = IList->getInit(Index);
  1382. if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
  1383. if (!VerifyOnly)
  1384. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
  1385. << DeclType << IList->getSourceRange();
  1386. hadError = true;
  1387. ++Index;
  1388. ++StructuredIndex;
  1389. return;
  1390. }
  1391. if (VerifyOnly) {
  1392. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1393. hadError = true;
  1394. ++Index;
  1395. return;
  1396. }
  1397. ExprResult Result =
  1398. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1399. /*TopLevelOfInitList=*/true);
  1400. if (Result.isInvalid())
  1401. hadError = true;
  1402. expr = Result.getAs<Expr>();
  1403. IList->setInit(Index, expr);
  1404. if (hadError)
  1405. ++StructuredIndex;
  1406. else
  1407. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1408. ++Index;
  1409. }
  1410. void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
  1411. InitListExpr *IList, QualType DeclType,
  1412. unsigned &Index,
  1413. InitListExpr *StructuredList,
  1414. unsigned &StructuredIndex) {
  1415. const VectorType *VT = DeclType->getAs<VectorType>();
  1416. unsigned maxElements = VT->getNumElements();
  1417. unsigned numEltsInit = 0;
  1418. QualType elementType = VT->getElementType();
  1419. if (Index >= IList->getNumInits()) {
  1420. // Make sure the element type can be value-initialized.
  1421. if (VerifyOnly)
  1422. CheckEmptyInitializable(
  1423. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1424. IList->getEndLoc());
  1425. return;
  1426. }
  1427. if (!SemaRef.getLangOpts().OpenCL) {
  1428. // If the initializing element is a vector, try to copy-initialize
  1429. // instead of breaking it apart (which is doomed to failure anyway).
  1430. Expr *Init = IList->getInit(Index);
  1431. if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
  1432. if (VerifyOnly) {
  1433. if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
  1434. hadError = true;
  1435. ++Index;
  1436. return;
  1437. }
  1438. ExprResult Result =
  1439. SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
  1440. /*TopLevelOfInitList=*/true);
  1441. Expr *ResultExpr = nullptr;
  1442. if (Result.isInvalid())
  1443. hadError = true; // types weren't compatible.
  1444. else {
  1445. ResultExpr = Result.getAs<Expr>();
  1446. if (ResultExpr != Init) {
  1447. // The type was promoted, update initializer list.
  1448. IList->setInit(Index, ResultExpr);
  1449. }
  1450. }
  1451. if (hadError)
  1452. ++StructuredIndex;
  1453. else
  1454. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1455. ResultExpr);
  1456. ++Index;
  1457. return;
  1458. }
  1459. InitializedEntity ElementEntity =
  1460. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1461. for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
  1462. // Don't attempt to go past the end of the init list
  1463. if (Index >= IList->getNumInits()) {
  1464. if (VerifyOnly)
  1465. CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
  1466. break;
  1467. }
  1468. ElementEntity.setElementIndex(Index);
  1469. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1470. StructuredList, StructuredIndex);
  1471. }
  1472. if (VerifyOnly)
  1473. return;
  1474. bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
  1475. const VectorType *T = Entity.getType()->getAs<VectorType>();
  1476. if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
  1477. T->getVectorKind() == VectorType::NeonPolyVector)) {
  1478. // The ability to use vector initializer lists is a GNU vector extension
  1479. // and is unrelated to the NEON intrinsics in arm_neon.h. On little
  1480. // endian machines it works fine, however on big endian machines it
  1481. // exhibits surprising behaviour:
  1482. //
  1483. // uint32x2_t x = {42, 64};
  1484. // return vget_lane_u32(x, 0); // Will return 64.
  1485. //
  1486. // Because of this, explicitly call out that it is non-portable.
  1487. //
  1488. SemaRef.Diag(IList->getBeginLoc(),
  1489. diag::warn_neon_vector_initializer_non_portable);
  1490. const char *typeCode;
  1491. unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
  1492. if (elementType->isFloatingType())
  1493. typeCode = "f";
  1494. else if (elementType->isSignedIntegerType())
  1495. typeCode = "s";
  1496. else if (elementType->isUnsignedIntegerType())
  1497. typeCode = "u";
  1498. else
  1499. llvm_unreachable("Invalid element type!");
  1500. SemaRef.Diag(IList->getBeginLoc(),
  1501. SemaRef.Context.getTypeSize(VT) > 64
  1502. ? diag::note_neon_vector_initializer_non_portable_q
  1503. : diag::note_neon_vector_initializer_non_portable)
  1504. << typeCode << typeSize;
  1505. }
  1506. return;
  1507. }
  1508. InitializedEntity ElementEntity =
  1509. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1510. // OpenCL initializers allows vectors to be constructed from vectors.
  1511. for (unsigned i = 0; i < maxElements; ++i) {
  1512. // Don't attempt to go past the end of the init list
  1513. if (Index >= IList->getNumInits())
  1514. break;
  1515. ElementEntity.setElementIndex(Index);
  1516. QualType IType = IList->getInit(Index)->getType();
  1517. if (!IType->isVectorType()) {
  1518. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1519. StructuredList, StructuredIndex);
  1520. ++numEltsInit;
  1521. } else {
  1522. QualType VecType;
  1523. const VectorType *IVT = IType->getAs<VectorType>();
  1524. unsigned numIElts = IVT->getNumElements();
  1525. if (IType->isExtVectorType())
  1526. VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
  1527. else
  1528. VecType = SemaRef.Context.getVectorType(elementType, numIElts,
  1529. IVT->getVectorKind());
  1530. CheckSubElementType(ElementEntity, IList, VecType, Index,
  1531. StructuredList, StructuredIndex);
  1532. numEltsInit += numIElts;
  1533. }
  1534. }
  1535. // OpenCL requires all elements to be initialized.
  1536. if (numEltsInit != maxElements) {
  1537. if (!VerifyOnly)
  1538. SemaRef.Diag(IList->getBeginLoc(),
  1539. diag::err_vector_incorrect_num_initializers)
  1540. << (numEltsInit < maxElements) << maxElements << numEltsInit;
  1541. hadError = true;
  1542. }
  1543. }
  1544. /// Check if the type of a class element has an accessible destructor, and marks
  1545. /// it referenced. Returns true if we shouldn't form a reference to the
  1546. /// destructor.
  1547. ///
  1548. /// Aggregate initialization requires a class element's destructor be
  1549. /// accessible per 11.6.1 [dcl.init.aggr]:
  1550. ///
  1551. /// The destructor for each element of class type is potentially invoked
  1552. /// (15.4 [class.dtor]) from the context where the aggregate initialization
  1553. /// occurs.
  1554. static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
  1555. Sema &SemaRef) {
  1556. auto *CXXRD = ElementType->getAsCXXRecordDecl();
  1557. if (!CXXRD)
  1558. return false;
  1559. CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
  1560. SemaRef.CheckDestructorAccess(Loc, Destructor,
  1561. SemaRef.PDiag(diag::err_access_dtor_temp)
  1562. << ElementType);
  1563. SemaRef.MarkFunctionReferenced(Loc, Destructor);
  1564. return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
  1565. }
  1566. void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
  1567. InitListExpr *IList, QualType &DeclType,
  1568. llvm::APSInt elementIndex,
  1569. bool SubobjectIsDesignatorContext,
  1570. unsigned &Index,
  1571. InitListExpr *StructuredList,
  1572. unsigned &StructuredIndex) {
  1573. const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
  1574. if (!VerifyOnly) {
  1575. if (checkDestructorReference(arrayType->getElementType(),
  1576. IList->getEndLoc(), SemaRef)) {
  1577. hadError = true;
  1578. return;
  1579. }
  1580. }
  1581. // Check for the special-case of initializing an array with a string.
  1582. if (Index < IList->getNumInits()) {
  1583. if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
  1584. SIF_None) {
  1585. // We place the string literal directly into the resulting
  1586. // initializer list. This is the only place where the structure
  1587. // of the structured initializer list doesn't match exactly,
  1588. // because doing so would involve allocating one character
  1589. // constant for each string.
  1590. if (!VerifyOnly) {
  1591. CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
  1592. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1593. IList->getInit(Index));
  1594. StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
  1595. }
  1596. ++Index;
  1597. return;
  1598. }
  1599. }
  1600. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
  1601. // Check for VLAs; in standard C it would be possible to check this
  1602. // earlier, but I don't know where clang accepts VLAs (gcc accepts
  1603. // them in all sorts of strange places).
  1604. if (!VerifyOnly)
  1605. SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
  1606. diag::err_variable_object_no_init)
  1607. << VAT->getSizeExpr()->getSourceRange();
  1608. hadError = true;
  1609. ++Index;
  1610. ++StructuredIndex;
  1611. return;
  1612. }
  1613. // We might know the maximum number of elements in advance.
  1614. llvm::APSInt maxElements(elementIndex.getBitWidth(),
  1615. elementIndex.isUnsigned());
  1616. bool maxElementsKnown = false;
  1617. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
  1618. maxElements = CAT->getSize();
  1619. elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
  1620. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1621. maxElementsKnown = true;
  1622. }
  1623. QualType elementType = arrayType->getElementType();
  1624. while (Index < IList->getNumInits()) {
  1625. Expr *Init = IList->getInit(Index);
  1626. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1627. // If we're not the subobject that matches up with the '{' for
  1628. // the designator, we shouldn't be handling the
  1629. // designator. Return immediately.
  1630. if (!SubobjectIsDesignatorContext)
  1631. return;
  1632. // Handle this designated initializer. elementIndex will be
  1633. // updated to be the next array element we'll initialize.
  1634. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1635. DeclType, nullptr, &elementIndex, Index,
  1636. StructuredList, StructuredIndex, true,
  1637. false)) {
  1638. hadError = true;
  1639. continue;
  1640. }
  1641. if (elementIndex.getBitWidth() > maxElements.getBitWidth())
  1642. maxElements = maxElements.extend(elementIndex.getBitWidth());
  1643. else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
  1644. elementIndex = elementIndex.extend(maxElements.getBitWidth());
  1645. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1646. // If the array is of incomplete type, keep track of the number of
  1647. // elements in the initializer.
  1648. if (!maxElementsKnown && elementIndex > maxElements)
  1649. maxElements = elementIndex;
  1650. continue;
  1651. }
  1652. // If we know the maximum number of elements, and we've already
  1653. // hit it, stop consuming elements in the initializer list.
  1654. if (maxElementsKnown && elementIndex == maxElements)
  1655. break;
  1656. InitializedEntity ElementEntity =
  1657. InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
  1658. Entity);
  1659. // Check this element.
  1660. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1661. StructuredList, StructuredIndex);
  1662. ++elementIndex;
  1663. // If the array is of incomplete type, keep track of the number of
  1664. // elements in the initializer.
  1665. if (!maxElementsKnown && elementIndex > maxElements)
  1666. maxElements = elementIndex;
  1667. }
  1668. if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
  1669. // If this is an incomplete array type, the actual type needs to
  1670. // be calculated here.
  1671. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
  1672. if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
  1673. // Sizing an array implicitly to zero is not allowed by ISO C,
  1674. // but is supported by GNU.
  1675. SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
  1676. }
  1677. DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
  1678. ArrayType::Normal, 0);
  1679. }
  1680. if (!hadError && VerifyOnly) {
  1681. // If there are any members of the array that get value-initialized, check
  1682. // that is possible. That happens if we know the bound and don't have
  1683. // enough elements, or if we're performing an array new with an unknown
  1684. // bound.
  1685. // FIXME: This needs to detect holes left by designated initializers too.
  1686. if ((maxElementsKnown && elementIndex < maxElements) ||
  1687. Entity.isVariableLengthArrayNew())
  1688. CheckEmptyInitializable(
  1689. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1690. IList->getEndLoc());
  1691. }
  1692. }
  1693. bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
  1694. Expr *InitExpr,
  1695. FieldDecl *Field,
  1696. bool TopLevelObject) {
  1697. // Handle GNU flexible array initializers.
  1698. unsigned FlexArrayDiag;
  1699. if (isa<InitListExpr>(InitExpr) &&
  1700. cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
  1701. // Empty flexible array init always allowed as an extension
  1702. FlexArrayDiag = diag::ext_flexible_array_init;
  1703. } else if (SemaRef.getLangOpts().CPlusPlus) {
  1704. // Disallow flexible array init in C++; it is not required for gcc
  1705. // compatibility, and it needs work to IRGen correctly in general.
  1706. FlexArrayDiag = diag::err_flexible_array_init;
  1707. } else if (!TopLevelObject) {
  1708. // Disallow flexible array init on non-top-level object
  1709. FlexArrayDiag = diag::err_flexible_array_init;
  1710. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  1711. // Disallow flexible array init on anything which is not a variable.
  1712. FlexArrayDiag = diag::err_flexible_array_init;
  1713. } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
  1714. // Disallow flexible array init on local variables.
  1715. FlexArrayDiag = diag::err_flexible_array_init;
  1716. } else {
  1717. // Allow other cases.
  1718. FlexArrayDiag = diag::ext_flexible_array_init;
  1719. }
  1720. if (!VerifyOnly) {
  1721. SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
  1722. << InitExpr->getBeginLoc();
  1723. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1724. << Field;
  1725. }
  1726. return FlexArrayDiag != diag::ext_flexible_array_init;
  1727. }
  1728. void InitListChecker::CheckStructUnionTypes(
  1729. const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
  1730. CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
  1731. bool SubobjectIsDesignatorContext, unsigned &Index,
  1732. InitListExpr *StructuredList, unsigned &StructuredIndex,
  1733. bool TopLevelObject) {
  1734. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  1735. // If the record is invalid, some of it's members are invalid. To avoid
  1736. // confusion, we forgo checking the intializer for the entire record.
  1737. if (structDecl->isInvalidDecl()) {
  1738. // Assume it was supposed to consume a single initializer.
  1739. ++Index;
  1740. hadError = true;
  1741. return;
  1742. }
  1743. if (DeclType->isUnionType() && IList->getNumInits() == 0) {
  1744. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1745. if (!VerifyOnly)
  1746. for (FieldDecl *FD : RD->fields()) {
  1747. QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
  1748. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  1749. hadError = true;
  1750. return;
  1751. }
  1752. }
  1753. // If there's a default initializer, use it.
  1754. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
  1755. if (VerifyOnly)
  1756. return;
  1757. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1758. Field != FieldEnd; ++Field) {
  1759. if (Field->hasInClassInitializer()) {
  1760. StructuredList->setInitializedFieldInUnion(*Field);
  1761. // FIXME: Actually build a CXXDefaultInitExpr?
  1762. return;
  1763. }
  1764. }
  1765. }
  1766. // Value-initialize the first member of the union that isn't an unnamed
  1767. // bitfield.
  1768. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1769. Field != FieldEnd; ++Field) {
  1770. if (!Field->isUnnamedBitfield()) {
  1771. if (VerifyOnly)
  1772. CheckEmptyInitializable(
  1773. InitializedEntity::InitializeMember(*Field, &Entity),
  1774. IList->getEndLoc());
  1775. else
  1776. StructuredList->setInitializedFieldInUnion(*Field);
  1777. break;
  1778. }
  1779. }
  1780. return;
  1781. }
  1782. bool InitializedSomething = false;
  1783. // If we have any base classes, they are initialized prior to the fields.
  1784. for (auto &Base : Bases) {
  1785. Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
  1786. // Designated inits always initialize fields, so if we see one, all
  1787. // remaining base classes have no explicit initializer.
  1788. if (Init && isa<DesignatedInitExpr>(Init))
  1789. Init = nullptr;
  1790. SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
  1791. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  1792. SemaRef.Context, &Base, false, &Entity);
  1793. if (Init) {
  1794. CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
  1795. StructuredList, StructuredIndex);
  1796. InitializedSomething = true;
  1797. } else if (VerifyOnly) {
  1798. CheckEmptyInitializable(BaseEntity, InitLoc);
  1799. }
  1800. if (!VerifyOnly)
  1801. if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
  1802. hadError = true;
  1803. return;
  1804. }
  1805. }
  1806. // If structDecl is a forward declaration, this loop won't do
  1807. // anything except look at designated initializers; That's okay,
  1808. // because an error should get printed out elsewhere. It might be
  1809. // worthwhile to skip over the rest of the initializer, though.
  1810. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1811. RecordDecl::field_iterator FieldEnd = RD->field_end();
  1812. bool CheckForMissingFields =
  1813. !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
  1814. bool HasDesignatedInit = false;
  1815. while (Index < IList->getNumInits()) {
  1816. Expr *Init = IList->getInit(Index);
  1817. SourceLocation InitLoc = Init->getBeginLoc();
  1818. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1819. // If we're not the subobject that matches up with the '{' for
  1820. // the designator, we shouldn't be handling the
  1821. // designator. Return immediately.
  1822. if (!SubobjectIsDesignatorContext)
  1823. return;
  1824. HasDesignatedInit = true;
  1825. // Handle this designated initializer. Field will be updated to
  1826. // the next field that we'll be initializing.
  1827. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1828. DeclType, &Field, nullptr, Index,
  1829. StructuredList, StructuredIndex,
  1830. true, TopLevelObject))
  1831. hadError = true;
  1832. else if (!VerifyOnly) {
  1833. // Find the field named by the designated initializer.
  1834. RecordDecl::field_iterator F = RD->field_begin();
  1835. while (std::next(F) != Field)
  1836. ++F;
  1837. QualType ET = SemaRef.Context.getBaseElementType(F->getType());
  1838. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  1839. hadError = true;
  1840. return;
  1841. }
  1842. }
  1843. InitializedSomething = true;
  1844. // Disable check for missing fields when designators are used.
  1845. // This matches gcc behaviour.
  1846. CheckForMissingFields = false;
  1847. continue;
  1848. }
  1849. if (Field == FieldEnd) {
  1850. // We've run out of fields. We're done.
  1851. break;
  1852. }
  1853. // We've already initialized a member of a union. We're done.
  1854. if (InitializedSomething && DeclType->isUnionType())
  1855. break;
  1856. // If we've hit the flexible array member at the end, we're done.
  1857. if (Field->getType()->isIncompleteArrayType())
  1858. break;
  1859. if (Field->isUnnamedBitfield()) {
  1860. // Don't initialize unnamed bitfields, e.g. "int : 20;"
  1861. ++Field;
  1862. continue;
  1863. }
  1864. // Make sure we can use this declaration.
  1865. bool InvalidUse;
  1866. if (VerifyOnly)
  1867. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  1868. else
  1869. InvalidUse = SemaRef.DiagnoseUseOfDecl(
  1870. *Field, IList->getInit(Index)->getBeginLoc());
  1871. if (InvalidUse) {
  1872. ++Index;
  1873. ++Field;
  1874. hadError = true;
  1875. continue;
  1876. }
  1877. if (!VerifyOnly) {
  1878. QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
  1879. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  1880. hadError = true;
  1881. return;
  1882. }
  1883. }
  1884. InitializedEntity MemberEntity =
  1885. InitializedEntity::InitializeMember(*Field, &Entity);
  1886. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1887. StructuredList, StructuredIndex);
  1888. InitializedSomething = true;
  1889. if (DeclType->isUnionType() && !VerifyOnly) {
  1890. // Initialize the first field within the union.
  1891. StructuredList->setInitializedFieldInUnion(*Field);
  1892. }
  1893. ++Field;
  1894. }
  1895. // Emit warnings for missing struct field initializers.
  1896. if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
  1897. Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
  1898. !DeclType->isUnionType()) {
  1899. // It is possible we have one or more unnamed bitfields remaining.
  1900. // Find first (if any) named field and emit warning.
  1901. for (RecordDecl::field_iterator it = Field, end = RD->field_end();
  1902. it != end; ++it) {
  1903. if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
  1904. SemaRef.Diag(IList->getSourceRange().getEnd(),
  1905. diag::warn_missing_field_initializers) << *it;
  1906. break;
  1907. }
  1908. }
  1909. }
  1910. // Check that any remaining fields can be value-initialized.
  1911. if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
  1912. !Field->getType()->isIncompleteArrayType()) {
  1913. // FIXME: Should check for holes left by designated initializers too.
  1914. for (; Field != FieldEnd && !hadError; ++Field) {
  1915. if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
  1916. CheckEmptyInitializable(
  1917. InitializedEntity::InitializeMember(*Field, &Entity),
  1918. IList->getEndLoc());
  1919. }
  1920. }
  1921. // Check that the types of the remaining fields have accessible destructors.
  1922. if (!VerifyOnly) {
  1923. // If the initializer expression has a designated initializer, check the
  1924. // elements for which a designated initializer is not provided too.
  1925. RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
  1926. : Field;
  1927. for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
  1928. QualType ET = SemaRef.Context.getBaseElementType(I->getType());
  1929. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  1930. hadError = true;
  1931. return;
  1932. }
  1933. }
  1934. }
  1935. if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
  1936. Index >= IList->getNumInits())
  1937. return;
  1938. if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
  1939. TopLevelObject)) {
  1940. hadError = true;
  1941. ++Index;
  1942. return;
  1943. }
  1944. InitializedEntity MemberEntity =
  1945. InitializedEntity::InitializeMember(*Field, &Entity);
  1946. if (isa<InitListExpr>(IList->getInit(Index)))
  1947. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1948. StructuredList, StructuredIndex);
  1949. else
  1950. CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
  1951. StructuredList, StructuredIndex);
  1952. }
  1953. /// Expand a field designator that refers to a member of an
  1954. /// anonymous struct or union into a series of field designators that
  1955. /// refers to the field within the appropriate subobject.
  1956. ///
  1957. static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
  1958. DesignatedInitExpr *DIE,
  1959. unsigned DesigIdx,
  1960. IndirectFieldDecl *IndirectField) {
  1961. typedef DesignatedInitExpr::Designator Designator;
  1962. // Build the replacement designators.
  1963. SmallVector<Designator, 4> Replacements;
  1964. for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
  1965. PE = IndirectField->chain_end(); PI != PE; ++PI) {
  1966. if (PI + 1 == PE)
  1967. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1968. DIE->getDesignator(DesigIdx)->getDotLoc(),
  1969. DIE->getDesignator(DesigIdx)->getFieldLoc()));
  1970. else
  1971. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1972. SourceLocation(), SourceLocation()));
  1973. assert(isa<FieldDecl>(*PI));
  1974. Replacements.back().setField(cast<FieldDecl>(*PI));
  1975. }
  1976. // Expand the current designator into the set of replacement
  1977. // designators, so we have a full subobject path down to where the
  1978. // member of the anonymous struct/union is actually stored.
  1979. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
  1980. &Replacements[0] + Replacements.size());
  1981. }
  1982. static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
  1983. DesignatedInitExpr *DIE) {
  1984. unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
  1985. SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
  1986. for (unsigned I = 0; I < NumIndexExprs; ++I)
  1987. IndexExprs[I] = DIE->getSubExpr(I + 1);
  1988. return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
  1989. IndexExprs,
  1990. DIE->getEqualOrColonLoc(),
  1991. DIE->usesGNUSyntax(), DIE->getInit());
  1992. }
  1993. namespace {
  1994. // Callback to only accept typo corrections that are for field members of
  1995. // the given struct or union.
  1996. class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
  1997. public:
  1998. explicit FieldInitializerValidatorCCC(RecordDecl *RD)
  1999. : Record(RD) {}
  2000. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2001. FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
  2002. return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
  2003. }
  2004. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2005. return llvm::make_unique<FieldInitializerValidatorCCC>(*this);
  2006. }
  2007. private:
  2008. RecordDecl *Record;
  2009. };
  2010. } // end anonymous namespace
  2011. /// Check the well-formedness of a C99 designated initializer.
  2012. ///
  2013. /// Determines whether the designated initializer @p DIE, which
  2014. /// resides at the given @p Index within the initializer list @p
  2015. /// IList, is well-formed for a current object of type @p DeclType
  2016. /// (C99 6.7.8). The actual subobject that this designator refers to
  2017. /// within the current subobject is returned in either
  2018. /// @p NextField or @p NextElementIndex (whichever is appropriate).
  2019. ///
  2020. /// @param IList The initializer list in which this designated
  2021. /// initializer occurs.
  2022. ///
  2023. /// @param DIE The designated initializer expression.
  2024. ///
  2025. /// @param DesigIdx The index of the current designator.
  2026. ///
  2027. /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
  2028. /// into which the designation in @p DIE should refer.
  2029. ///
  2030. /// @param NextField If non-NULL and the first designator in @p DIE is
  2031. /// a field, this will be set to the field declaration corresponding
  2032. /// to the field named by the designator.
  2033. ///
  2034. /// @param NextElementIndex If non-NULL and the first designator in @p
  2035. /// DIE is an array designator or GNU array-range designator, this
  2036. /// will be set to the last index initialized by this designator.
  2037. ///
  2038. /// @param Index Index into @p IList where the designated initializer
  2039. /// @p DIE occurs.
  2040. ///
  2041. /// @param StructuredList The initializer list expression that
  2042. /// describes all of the subobject initializers in the order they'll
  2043. /// actually be initialized.
  2044. ///
  2045. /// @returns true if there was an error, false otherwise.
  2046. bool
  2047. InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
  2048. InitListExpr *IList,
  2049. DesignatedInitExpr *DIE,
  2050. unsigned DesigIdx,
  2051. QualType &CurrentObjectType,
  2052. RecordDecl::field_iterator *NextField,
  2053. llvm::APSInt *NextElementIndex,
  2054. unsigned &Index,
  2055. InitListExpr *StructuredList,
  2056. unsigned &StructuredIndex,
  2057. bool FinishSubobjectInit,
  2058. bool TopLevelObject) {
  2059. if (DesigIdx == DIE->size()) {
  2060. // Check the actual initialization for the designated object type.
  2061. bool prevHadError = hadError;
  2062. // Temporarily remove the designator expression from the
  2063. // initializer list that the child calls see, so that we don't try
  2064. // to re-process the designator.
  2065. unsigned OldIndex = Index;
  2066. IList->setInit(OldIndex, DIE->getInit());
  2067. CheckSubElementType(Entity, IList, CurrentObjectType, Index,
  2068. StructuredList, StructuredIndex);
  2069. // Restore the designated initializer expression in the syntactic
  2070. // form of the initializer list.
  2071. if (IList->getInit(OldIndex) != DIE->getInit())
  2072. DIE->setInit(IList->getInit(OldIndex));
  2073. IList->setInit(OldIndex, DIE);
  2074. return hadError && !prevHadError;
  2075. }
  2076. DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
  2077. bool IsFirstDesignator = (DesigIdx == 0);
  2078. if (!VerifyOnly) {
  2079. assert((IsFirstDesignator || StructuredList) &&
  2080. "Need a non-designated initializer list to start from");
  2081. // Determine the structural initializer list that corresponds to the
  2082. // current subobject.
  2083. if (IsFirstDesignator)
  2084. StructuredList = SyntacticToSemantic.lookup(IList);
  2085. else {
  2086. Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
  2087. StructuredList->getInit(StructuredIndex) : nullptr;
  2088. if (!ExistingInit && StructuredList->hasArrayFiller())
  2089. ExistingInit = StructuredList->getArrayFiller();
  2090. if (!ExistingInit)
  2091. StructuredList = getStructuredSubobjectInit(
  2092. IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
  2093. SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
  2094. else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
  2095. StructuredList = Result;
  2096. else {
  2097. if (DesignatedInitUpdateExpr *E =
  2098. dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
  2099. StructuredList = E->getUpdater();
  2100. else {
  2101. DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
  2102. DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
  2103. ExistingInit, DIE->getEndLoc());
  2104. StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
  2105. StructuredList = DIUE->getUpdater();
  2106. }
  2107. // We need to check on source range validity because the previous
  2108. // initializer does not have to be an explicit initializer. e.g.,
  2109. //
  2110. // struct P { int a, b; };
  2111. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  2112. //
  2113. // There is an overwrite taking place because the first braced initializer
  2114. // list "{ .a = 2 }" already provides value for .p.b (which is zero).
  2115. if (ExistingInit->getSourceRange().isValid()) {
  2116. // We are creating an initializer list that initializes the
  2117. // subobjects of the current object, but there was already an
  2118. // initialization that completely initialized the current
  2119. // subobject, e.g., by a compound literal:
  2120. //
  2121. // struct X { int a, b; };
  2122. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2123. //
  2124. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  2125. // designated initializer re-initializes the whole
  2126. // subobject [0], overwriting previous initializers.
  2127. SemaRef.Diag(D->getBeginLoc(),
  2128. diag::warn_subobject_initializer_overrides)
  2129. << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
  2130. SemaRef.Diag(ExistingInit->getBeginLoc(),
  2131. diag::note_previous_initializer)
  2132. << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
  2133. }
  2134. }
  2135. }
  2136. assert(StructuredList && "Expected a structured initializer list");
  2137. }
  2138. if (D->isFieldDesignator()) {
  2139. // C99 6.7.8p7:
  2140. //
  2141. // If a designator has the form
  2142. //
  2143. // . identifier
  2144. //
  2145. // then the current object (defined below) shall have
  2146. // structure or union type and the identifier shall be the
  2147. // name of a member of that type.
  2148. const RecordType *RT = CurrentObjectType->getAs<RecordType>();
  2149. if (!RT) {
  2150. SourceLocation Loc = D->getDotLoc();
  2151. if (Loc.isInvalid())
  2152. Loc = D->getFieldLoc();
  2153. if (!VerifyOnly)
  2154. SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
  2155. << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
  2156. ++Index;
  2157. return true;
  2158. }
  2159. FieldDecl *KnownField = D->getField();
  2160. if (!KnownField) {
  2161. IdentifierInfo *FieldName = D->getFieldName();
  2162. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
  2163. for (NamedDecl *ND : Lookup) {
  2164. if (auto *FD = dyn_cast<FieldDecl>(ND)) {
  2165. KnownField = FD;
  2166. break;
  2167. }
  2168. if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
  2169. // In verify mode, don't modify the original.
  2170. if (VerifyOnly)
  2171. DIE = CloneDesignatedInitExpr(SemaRef, DIE);
  2172. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
  2173. D = DIE->getDesignator(DesigIdx);
  2174. KnownField = cast<FieldDecl>(*IFD->chain_begin());
  2175. break;
  2176. }
  2177. }
  2178. if (!KnownField) {
  2179. if (VerifyOnly) {
  2180. ++Index;
  2181. return true; // No typo correction when just trying this out.
  2182. }
  2183. // Name lookup found something, but it wasn't a field.
  2184. if (!Lookup.empty()) {
  2185. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
  2186. << FieldName;
  2187. SemaRef.Diag(Lookup.front()->getLocation(),
  2188. diag::note_field_designator_found);
  2189. ++Index;
  2190. return true;
  2191. }
  2192. // Name lookup didn't find anything.
  2193. // Determine whether this was a typo for another field name.
  2194. FieldInitializerValidatorCCC CCC(RT->getDecl());
  2195. if (TypoCorrection Corrected = SemaRef.CorrectTypo(
  2196. DeclarationNameInfo(FieldName, D->getFieldLoc()),
  2197. Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
  2198. Sema::CTK_ErrorRecovery, RT->getDecl())) {
  2199. SemaRef.diagnoseTypo(
  2200. Corrected,
  2201. SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
  2202. << FieldName << CurrentObjectType);
  2203. KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
  2204. hadError = true;
  2205. } else {
  2206. // Typo correction didn't find anything.
  2207. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
  2208. << FieldName << CurrentObjectType;
  2209. ++Index;
  2210. return true;
  2211. }
  2212. }
  2213. }
  2214. unsigned FieldIndex = 0;
  2215. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2216. FieldIndex = CXXRD->getNumBases();
  2217. for (auto *FI : RT->getDecl()->fields()) {
  2218. if (FI->isUnnamedBitfield())
  2219. continue;
  2220. if (declaresSameEntity(KnownField, FI)) {
  2221. KnownField = FI;
  2222. break;
  2223. }
  2224. ++FieldIndex;
  2225. }
  2226. RecordDecl::field_iterator Field =
  2227. RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
  2228. // All of the fields of a union are located at the same place in
  2229. // the initializer list.
  2230. if (RT->getDecl()->isUnion()) {
  2231. FieldIndex = 0;
  2232. if (!VerifyOnly) {
  2233. FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
  2234. if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
  2235. assert(StructuredList->getNumInits() == 1
  2236. && "A union should never have more than one initializer!");
  2237. Expr *ExistingInit = StructuredList->getInit(0);
  2238. if (ExistingInit) {
  2239. // We're about to throw away an initializer, emit warning.
  2240. SemaRef.Diag(D->getFieldLoc(),
  2241. diag::warn_initializer_overrides)
  2242. << D->getSourceRange();
  2243. SemaRef.Diag(ExistingInit->getBeginLoc(),
  2244. diag::note_previous_initializer)
  2245. << /*FIXME:has side effects=*/0
  2246. << ExistingInit->getSourceRange();
  2247. }
  2248. // remove existing initializer
  2249. StructuredList->resizeInits(SemaRef.Context, 0);
  2250. StructuredList->setInitializedFieldInUnion(nullptr);
  2251. }
  2252. StructuredList->setInitializedFieldInUnion(*Field);
  2253. }
  2254. }
  2255. // Make sure we can use this declaration.
  2256. bool InvalidUse;
  2257. if (VerifyOnly)
  2258. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  2259. else
  2260. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
  2261. if (InvalidUse) {
  2262. ++Index;
  2263. return true;
  2264. }
  2265. if (!VerifyOnly) {
  2266. // Update the designator with the field declaration.
  2267. D->setField(*Field);
  2268. // Make sure that our non-designated initializer list has space
  2269. // for a subobject corresponding to this field.
  2270. if (FieldIndex >= StructuredList->getNumInits())
  2271. StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
  2272. }
  2273. // This designator names a flexible array member.
  2274. if (Field->getType()->isIncompleteArrayType()) {
  2275. bool Invalid = false;
  2276. if ((DesigIdx + 1) != DIE->size()) {
  2277. // We can't designate an object within the flexible array
  2278. // member (because GCC doesn't allow it).
  2279. if (!VerifyOnly) {
  2280. DesignatedInitExpr::Designator *NextD
  2281. = DIE->getDesignator(DesigIdx + 1);
  2282. SemaRef.Diag(NextD->getBeginLoc(),
  2283. diag::err_designator_into_flexible_array_member)
  2284. << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
  2285. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2286. << *Field;
  2287. }
  2288. Invalid = true;
  2289. }
  2290. if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
  2291. !isa<StringLiteral>(DIE->getInit())) {
  2292. // The initializer is not an initializer list.
  2293. if (!VerifyOnly) {
  2294. SemaRef.Diag(DIE->getInit()->getBeginLoc(),
  2295. diag::err_flexible_array_init_needs_braces)
  2296. << DIE->getInit()->getSourceRange();
  2297. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2298. << *Field;
  2299. }
  2300. Invalid = true;
  2301. }
  2302. // Check GNU flexible array initializer.
  2303. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
  2304. TopLevelObject))
  2305. Invalid = true;
  2306. if (Invalid) {
  2307. ++Index;
  2308. return true;
  2309. }
  2310. // Initialize the array.
  2311. bool prevHadError = hadError;
  2312. unsigned newStructuredIndex = FieldIndex;
  2313. unsigned OldIndex = Index;
  2314. IList->setInit(Index, DIE->getInit());
  2315. InitializedEntity MemberEntity =
  2316. InitializedEntity::InitializeMember(*Field, &Entity);
  2317. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2318. StructuredList, newStructuredIndex);
  2319. IList->setInit(OldIndex, DIE);
  2320. if (hadError && !prevHadError) {
  2321. ++Field;
  2322. ++FieldIndex;
  2323. if (NextField)
  2324. *NextField = Field;
  2325. StructuredIndex = FieldIndex;
  2326. return true;
  2327. }
  2328. } else {
  2329. // Recurse to check later designated subobjects.
  2330. QualType FieldType = Field->getType();
  2331. unsigned newStructuredIndex = FieldIndex;
  2332. InitializedEntity MemberEntity =
  2333. InitializedEntity::InitializeMember(*Field, &Entity);
  2334. if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
  2335. FieldType, nullptr, nullptr, Index,
  2336. StructuredList, newStructuredIndex,
  2337. FinishSubobjectInit, false))
  2338. return true;
  2339. }
  2340. // Find the position of the next field to be initialized in this
  2341. // subobject.
  2342. ++Field;
  2343. ++FieldIndex;
  2344. // If this the first designator, our caller will continue checking
  2345. // the rest of this struct/class/union subobject.
  2346. if (IsFirstDesignator) {
  2347. if (NextField)
  2348. *NextField = Field;
  2349. StructuredIndex = FieldIndex;
  2350. return false;
  2351. }
  2352. if (!FinishSubobjectInit)
  2353. return false;
  2354. // We've already initialized something in the union; we're done.
  2355. if (RT->getDecl()->isUnion())
  2356. return hadError;
  2357. // Check the remaining fields within this class/struct/union subobject.
  2358. bool prevHadError = hadError;
  2359. auto NoBases =
  2360. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  2361. CXXRecordDecl::base_class_iterator());
  2362. CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
  2363. false, Index, StructuredList, FieldIndex);
  2364. return hadError && !prevHadError;
  2365. }
  2366. // C99 6.7.8p6:
  2367. //
  2368. // If a designator has the form
  2369. //
  2370. // [ constant-expression ]
  2371. //
  2372. // then the current object (defined below) shall have array
  2373. // type and the expression shall be an integer constant
  2374. // expression. If the array is of unknown size, any
  2375. // nonnegative value is valid.
  2376. //
  2377. // Additionally, cope with the GNU extension that permits
  2378. // designators of the form
  2379. //
  2380. // [ constant-expression ... constant-expression ]
  2381. const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
  2382. if (!AT) {
  2383. if (!VerifyOnly)
  2384. SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
  2385. << CurrentObjectType;
  2386. ++Index;
  2387. return true;
  2388. }
  2389. Expr *IndexExpr = nullptr;
  2390. llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
  2391. if (D->isArrayDesignator()) {
  2392. IndexExpr = DIE->getArrayIndex(*D);
  2393. DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
  2394. DesignatedEndIndex = DesignatedStartIndex;
  2395. } else {
  2396. assert(D->isArrayRangeDesignator() && "Need array-range designator");
  2397. DesignatedStartIndex =
  2398. DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2399. DesignatedEndIndex =
  2400. DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2401. IndexExpr = DIE->getArrayRangeEnd(*D);
  2402. // Codegen can't handle evaluating array range designators that have side
  2403. // effects, because we replicate the AST value for each initialized element.
  2404. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
  2405. // elements with something that has a side effect, so codegen can emit an
  2406. // "error unsupported" error instead of miscompiling the app.
  2407. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
  2408. DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
  2409. FullyStructuredList->sawArrayRangeDesignator();
  2410. }
  2411. if (isa<ConstantArrayType>(AT)) {
  2412. llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
  2413. DesignatedStartIndex
  2414. = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
  2415. DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
  2416. DesignatedEndIndex
  2417. = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
  2418. DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
  2419. if (DesignatedEndIndex >= MaxElements) {
  2420. if (!VerifyOnly)
  2421. SemaRef.Diag(IndexExpr->getBeginLoc(),
  2422. diag::err_array_designator_too_large)
  2423. << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
  2424. << IndexExpr->getSourceRange();
  2425. ++Index;
  2426. return true;
  2427. }
  2428. } else {
  2429. unsigned DesignatedIndexBitWidth =
  2430. ConstantArrayType::getMaxSizeBits(SemaRef.Context);
  2431. DesignatedStartIndex =
  2432. DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
  2433. DesignatedEndIndex =
  2434. DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
  2435. DesignatedStartIndex.setIsUnsigned(true);
  2436. DesignatedEndIndex.setIsUnsigned(true);
  2437. }
  2438. if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
  2439. // We're modifying a string literal init; we have to decompose the string
  2440. // so we can modify the individual characters.
  2441. ASTContext &Context = SemaRef.Context;
  2442. Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
  2443. // Compute the character type
  2444. QualType CharTy = AT->getElementType();
  2445. // Compute the type of the integer literals.
  2446. QualType PromotedCharTy = CharTy;
  2447. if (CharTy->isPromotableIntegerType())
  2448. PromotedCharTy = Context.getPromotedIntegerType(CharTy);
  2449. unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
  2450. if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
  2451. // Get the length of the string.
  2452. uint64_t StrLen = SL->getLength();
  2453. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2454. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2455. StructuredList->resizeInits(Context, StrLen);
  2456. // Build a literal for each character in the string, and put them into
  2457. // the init list.
  2458. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2459. llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
  2460. Expr *Init = new (Context) IntegerLiteral(
  2461. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2462. if (CharTy != PromotedCharTy)
  2463. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2464. Init, nullptr, VK_RValue);
  2465. StructuredList->updateInit(Context, i, Init);
  2466. }
  2467. } else {
  2468. ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
  2469. std::string Str;
  2470. Context.getObjCEncodingForType(E->getEncodedType(), Str);
  2471. // Get the length of the string.
  2472. uint64_t StrLen = Str.size();
  2473. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2474. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2475. StructuredList->resizeInits(Context, StrLen);
  2476. // Build a literal for each character in the string, and put them into
  2477. // the init list.
  2478. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2479. llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
  2480. Expr *Init = new (Context) IntegerLiteral(
  2481. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2482. if (CharTy != PromotedCharTy)
  2483. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2484. Init, nullptr, VK_RValue);
  2485. StructuredList->updateInit(Context, i, Init);
  2486. }
  2487. }
  2488. }
  2489. // Make sure that our non-designated initializer list has space
  2490. // for a subobject corresponding to this array element.
  2491. if (!VerifyOnly &&
  2492. DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
  2493. StructuredList->resizeInits(SemaRef.Context,
  2494. DesignatedEndIndex.getZExtValue() + 1);
  2495. // Repeatedly perform subobject initializations in the range
  2496. // [DesignatedStartIndex, DesignatedEndIndex].
  2497. // Move to the next designator
  2498. unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
  2499. unsigned OldIndex = Index;
  2500. InitializedEntity ElementEntity =
  2501. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  2502. while (DesignatedStartIndex <= DesignatedEndIndex) {
  2503. // Recurse to check later designated subobjects.
  2504. QualType ElementType = AT->getElementType();
  2505. Index = OldIndex;
  2506. ElementEntity.setElementIndex(ElementIndex);
  2507. if (CheckDesignatedInitializer(
  2508. ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
  2509. nullptr, Index, StructuredList, ElementIndex,
  2510. FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
  2511. false))
  2512. return true;
  2513. // Move to the next index in the array that we'll be initializing.
  2514. ++DesignatedStartIndex;
  2515. ElementIndex = DesignatedStartIndex.getZExtValue();
  2516. }
  2517. // If this the first designator, our caller will continue checking
  2518. // the rest of this array subobject.
  2519. if (IsFirstDesignator) {
  2520. if (NextElementIndex)
  2521. *NextElementIndex = DesignatedStartIndex;
  2522. StructuredIndex = ElementIndex;
  2523. return false;
  2524. }
  2525. if (!FinishSubobjectInit)
  2526. return false;
  2527. // Check the remaining elements within this array subobject.
  2528. bool prevHadError = hadError;
  2529. CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
  2530. /*SubobjectIsDesignatorContext=*/false, Index,
  2531. StructuredList, ElementIndex);
  2532. return hadError && !prevHadError;
  2533. }
  2534. // Get the structured initializer list for a subobject of type
  2535. // @p CurrentObjectType.
  2536. InitListExpr *
  2537. InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  2538. QualType CurrentObjectType,
  2539. InitListExpr *StructuredList,
  2540. unsigned StructuredIndex,
  2541. SourceRange InitRange,
  2542. bool IsFullyOverwritten) {
  2543. if (VerifyOnly)
  2544. return nullptr; // No structured list in verification-only mode.
  2545. Expr *ExistingInit = nullptr;
  2546. if (!StructuredList)
  2547. ExistingInit = SyntacticToSemantic.lookup(IList);
  2548. else if (StructuredIndex < StructuredList->getNumInits())
  2549. ExistingInit = StructuredList->getInit(StructuredIndex);
  2550. if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
  2551. // There might have already been initializers for subobjects of the current
  2552. // object, but a subsequent initializer list will overwrite the entirety
  2553. // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
  2554. //
  2555. // struct P { char x[6]; };
  2556. // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
  2557. //
  2558. // The first designated initializer is ignored, and l.x is just "f".
  2559. if (!IsFullyOverwritten)
  2560. return Result;
  2561. if (ExistingInit) {
  2562. // We are creating an initializer list that initializes the
  2563. // subobjects of the current object, but there was already an
  2564. // initialization that completely initialized the current
  2565. // subobject, e.g., by a compound literal:
  2566. //
  2567. // struct X { int a, b; };
  2568. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2569. //
  2570. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  2571. // designated initializer re-initializes the whole
  2572. // subobject [0], overwriting previous initializers.
  2573. SemaRef.Diag(InitRange.getBegin(),
  2574. diag::warn_subobject_initializer_overrides)
  2575. << InitRange;
  2576. SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
  2577. << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
  2578. }
  2579. InitListExpr *Result
  2580. = new (SemaRef.Context) InitListExpr(SemaRef.Context,
  2581. InitRange.getBegin(), None,
  2582. InitRange.getEnd());
  2583. QualType ResultType = CurrentObjectType;
  2584. if (!ResultType->isArrayType())
  2585. ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
  2586. Result->setType(ResultType);
  2587. // Pre-allocate storage for the structured initializer list.
  2588. unsigned NumElements = 0;
  2589. unsigned NumInits = 0;
  2590. bool GotNumInits = false;
  2591. if (!StructuredList) {
  2592. NumInits = IList->getNumInits();
  2593. GotNumInits = true;
  2594. } else if (Index < IList->getNumInits()) {
  2595. if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
  2596. NumInits = SubList->getNumInits();
  2597. GotNumInits = true;
  2598. }
  2599. }
  2600. if (const ArrayType *AType
  2601. = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
  2602. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
  2603. NumElements = CAType->getSize().getZExtValue();
  2604. // Simple heuristic so that we don't allocate a very large
  2605. // initializer with many empty entries at the end.
  2606. if (GotNumInits && NumElements > NumInits)
  2607. NumElements = 0;
  2608. }
  2609. } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
  2610. NumElements = VType->getNumElements();
  2611. else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
  2612. RecordDecl *RDecl = RType->getDecl();
  2613. if (RDecl->isUnion())
  2614. NumElements = 1;
  2615. else
  2616. NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
  2617. }
  2618. Result->reserveInits(SemaRef.Context, NumElements);
  2619. // Link this new initializer list into the structured initializer
  2620. // lists.
  2621. if (StructuredList)
  2622. StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
  2623. else {
  2624. Result->setSyntacticForm(IList);
  2625. SyntacticToSemantic[IList] = Result;
  2626. }
  2627. return Result;
  2628. }
  2629. /// Update the initializer at index @p StructuredIndex within the
  2630. /// structured initializer list to the value @p expr.
  2631. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
  2632. unsigned &StructuredIndex,
  2633. Expr *expr) {
  2634. // No structured initializer list to update
  2635. if (!StructuredList)
  2636. return;
  2637. if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
  2638. StructuredIndex, expr)) {
  2639. // This initializer overwrites a previous initializer. Warn.
  2640. // We need to check on source range validity because the previous
  2641. // initializer does not have to be an explicit initializer.
  2642. // struct P { int a, b; };
  2643. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  2644. // There is an overwrite taking place because the first braced initializer
  2645. // list "{ .a = 2 }' already provides value for .p.b (which is zero).
  2646. if (PrevInit->getSourceRange().isValid()) {
  2647. SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
  2648. << expr->getSourceRange();
  2649. SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
  2650. << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
  2651. }
  2652. }
  2653. ++StructuredIndex;
  2654. }
  2655. /// Check that the given Index expression is a valid array designator
  2656. /// value. This is essentially just a wrapper around
  2657. /// VerifyIntegerConstantExpression that also checks for negative values
  2658. /// and produces a reasonable diagnostic if there is a
  2659. /// failure. Returns the index expression, possibly with an implicit cast
  2660. /// added, on success. If everything went okay, Value will receive the
  2661. /// value of the constant expression.
  2662. static ExprResult
  2663. CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
  2664. SourceLocation Loc = Index->getBeginLoc();
  2665. // Make sure this is an integer constant expression.
  2666. ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
  2667. if (Result.isInvalid())
  2668. return Result;
  2669. if (Value.isSigned() && Value.isNegative())
  2670. return S.Diag(Loc, diag::err_array_designator_negative)
  2671. << Value.toString(10) << Index->getSourceRange();
  2672. Value.setIsUnsigned(true);
  2673. return Result;
  2674. }
  2675. ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
  2676. SourceLocation Loc,
  2677. bool GNUSyntax,
  2678. ExprResult Init) {
  2679. typedef DesignatedInitExpr::Designator ASTDesignator;
  2680. bool Invalid = false;
  2681. SmallVector<ASTDesignator, 32> Designators;
  2682. SmallVector<Expr *, 32> InitExpressions;
  2683. // Build designators and check array designator expressions.
  2684. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
  2685. const Designator &D = Desig.getDesignator(Idx);
  2686. switch (D.getKind()) {
  2687. case Designator::FieldDesignator:
  2688. Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
  2689. D.getFieldLoc()));
  2690. break;
  2691. case Designator::ArrayDesignator: {
  2692. Expr *Index = static_cast<Expr *>(D.getArrayIndex());
  2693. llvm::APSInt IndexValue;
  2694. if (!Index->isTypeDependent() && !Index->isValueDependent())
  2695. Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
  2696. if (!Index)
  2697. Invalid = true;
  2698. else {
  2699. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2700. D.getLBracketLoc(),
  2701. D.getRBracketLoc()));
  2702. InitExpressions.push_back(Index);
  2703. }
  2704. break;
  2705. }
  2706. case Designator::ArrayRangeDesignator: {
  2707. Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
  2708. Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
  2709. llvm::APSInt StartValue;
  2710. llvm::APSInt EndValue;
  2711. bool StartDependent = StartIndex->isTypeDependent() ||
  2712. StartIndex->isValueDependent();
  2713. bool EndDependent = EndIndex->isTypeDependent() ||
  2714. EndIndex->isValueDependent();
  2715. if (!StartDependent)
  2716. StartIndex =
  2717. CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
  2718. if (!EndDependent)
  2719. EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
  2720. if (!StartIndex || !EndIndex)
  2721. Invalid = true;
  2722. else {
  2723. // Make sure we're comparing values with the same bit width.
  2724. if (StartDependent || EndDependent) {
  2725. // Nothing to compute.
  2726. } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
  2727. EndValue = EndValue.extend(StartValue.getBitWidth());
  2728. else if (StartValue.getBitWidth() < EndValue.getBitWidth())
  2729. StartValue = StartValue.extend(EndValue.getBitWidth());
  2730. if (!StartDependent && !EndDependent && EndValue < StartValue) {
  2731. Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
  2732. << StartValue.toString(10) << EndValue.toString(10)
  2733. << StartIndex->getSourceRange() << EndIndex->getSourceRange();
  2734. Invalid = true;
  2735. } else {
  2736. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2737. D.getLBracketLoc(),
  2738. D.getEllipsisLoc(),
  2739. D.getRBracketLoc()));
  2740. InitExpressions.push_back(StartIndex);
  2741. InitExpressions.push_back(EndIndex);
  2742. }
  2743. }
  2744. break;
  2745. }
  2746. }
  2747. }
  2748. if (Invalid || Init.isInvalid())
  2749. return ExprError();
  2750. // Clear out the expressions within the designation.
  2751. Desig.ClearExprs(*this);
  2752. DesignatedInitExpr *DIE
  2753. = DesignatedInitExpr::Create(Context,
  2754. Designators,
  2755. InitExpressions, Loc, GNUSyntax,
  2756. Init.getAs<Expr>());
  2757. if (!getLangOpts().C99)
  2758. Diag(DIE->getBeginLoc(), diag::ext_designated_init)
  2759. << DIE->getSourceRange();
  2760. return DIE;
  2761. }
  2762. //===----------------------------------------------------------------------===//
  2763. // Initialization entity
  2764. //===----------------------------------------------------------------------===//
  2765. InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
  2766. const InitializedEntity &Parent)
  2767. : Parent(&Parent), Index(Index)
  2768. {
  2769. if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
  2770. Kind = EK_ArrayElement;
  2771. Type = AT->getElementType();
  2772. } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
  2773. Kind = EK_VectorElement;
  2774. Type = VT->getElementType();
  2775. } else {
  2776. const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
  2777. assert(CT && "Unexpected type");
  2778. Kind = EK_ComplexElement;
  2779. Type = CT->getElementType();
  2780. }
  2781. }
  2782. InitializedEntity
  2783. InitializedEntity::InitializeBase(ASTContext &Context,
  2784. const CXXBaseSpecifier *Base,
  2785. bool IsInheritedVirtualBase,
  2786. const InitializedEntity *Parent) {
  2787. InitializedEntity Result;
  2788. Result.Kind = EK_Base;
  2789. Result.Parent = Parent;
  2790. Result.Base = reinterpret_cast<uintptr_t>(Base);
  2791. if (IsInheritedVirtualBase)
  2792. Result.Base |= 0x01;
  2793. Result.Type = Base->getType();
  2794. return Result;
  2795. }
  2796. DeclarationName InitializedEntity::getName() const {
  2797. switch (getKind()) {
  2798. case EK_Parameter:
  2799. case EK_Parameter_CF_Audited: {
  2800. ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2801. return (D ? D->getDeclName() : DeclarationName());
  2802. }
  2803. case EK_Variable:
  2804. case EK_Member:
  2805. case EK_Binding:
  2806. return Variable.VariableOrMember->getDeclName();
  2807. case EK_LambdaCapture:
  2808. return DeclarationName(Capture.VarID);
  2809. case EK_Result:
  2810. case EK_StmtExprResult:
  2811. case EK_Exception:
  2812. case EK_New:
  2813. case EK_Temporary:
  2814. case EK_Base:
  2815. case EK_Delegating:
  2816. case EK_ArrayElement:
  2817. case EK_VectorElement:
  2818. case EK_ComplexElement:
  2819. case EK_BlockElement:
  2820. case EK_LambdaToBlockConversionBlockElement:
  2821. case EK_CompoundLiteralInit:
  2822. case EK_RelatedResult:
  2823. return DeclarationName();
  2824. }
  2825. llvm_unreachable("Invalid EntityKind!");
  2826. }
  2827. ValueDecl *InitializedEntity::getDecl() const {
  2828. switch (getKind()) {
  2829. case EK_Variable:
  2830. case EK_Member:
  2831. case EK_Binding:
  2832. return Variable.VariableOrMember;
  2833. case EK_Parameter:
  2834. case EK_Parameter_CF_Audited:
  2835. return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2836. case EK_Result:
  2837. case EK_StmtExprResult:
  2838. case EK_Exception:
  2839. case EK_New:
  2840. case EK_Temporary:
  2841. case EK_Base:
  2842. case EK_Delegating:
  2843. case EK_ArrayElement:
  2844. case EK_VectorElement:
  2845. case EK_ComplexElement:
  2846. case EK_BlockElement:
  2847. case EK_LambdaToBlockConversionBlockElement:
  2848. case EK_LambdaCapture:
  2849. case EK_CompoundLiteralInit:
  2850. case EK_RelatedResult:
  2851. return nullptr;
  2852. }
  2853. llvm_unreachable("Invalid EntityKind!");
  2854. }
  2855. bool InitializedEntity::allowsNRVO() const {
  2856. switch (getKind()) {
  2857. case EK_Result:
  2858. case EK_Exception:
  2859. return LocAndNRVO.NRVO;
  2860. case EK_StmtExprResult:
  2861. case EK_Variable:
  2862. case EK_Parameter:
  2863. case EK_Parameter_CF_Audited:
  2864. case EK_Member:
  2865. case EK_Binding:
  2866. case EK_New:
  2867. case EK_Temporary:
  2868. case EK_CompoundLiteralInit:
  2869. case EK_Base:
  2870. case EK_Delegating:
  2871. case EK_ArrayElement:
  2872. case EK_VectorElement:
  2873. case EK_ComplexElement:
  2874. case EK_BlockElement:
  2875. case EK_LambdaToBlockConversionBlockElement:
  2876. case EK_LambdaCapture:
  2877. case EK_RelatedResult:
  2878. break;
  2879. }
  2880. return false;
  2881. }
  2882. unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
  2883. assert(getParent() != this);
  2884. unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
  2885. for (unsigned I = 0; I != Depth; ++I)
  2886. OS << "`-";
  2887. switch (getKind()) {
  2888. case EK_Variable: OS << "Variable"; break;
  2889. case EK_Parameter: OS << "Parameter"; break;
  2890. case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
  2891. break;
  2892. case EK_Result: OS << "Result"; break;
  2893. case EK_StmtExprResult: OS << "StmtExprResult"; break;
  2894. case EK_Exception: OS << "Exception"; break;
  2895. case EK_Member: OS << "Member"; break;
  2896. case EK_Binding: OS << "Binding"; break;
  2897. case EK_New: OS << "New"; break;
  2898. case EK_Temporary: OS << "Temporary"; break;
  2899. case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
  2900. case EK_RelatedResult: OS << "RelatedResult"; break;
  2901. case EK_Base: OS << "Base"; break;
  2902. case EK_Delegating: OS << "Delegating"; break;
  2903. case EK_ArrayElement: OS << "ArrayElement " << Index; break;
  2904. case EK_VectorElement: OS << "VectorElement " << Index; break;
  2905. case EK_ComplexElement: OS << "ComplexElement " << Index; break;
  2906. case EK_BlockElement: OS << "Block"; break;
  2907. case EK_LambdaToBlockConversionBlockElement:
  2908. OS << "Block (lambda)";
  2909. break;
  2910. case EK_LambdaCapture:
  2911. OS << "LambdaCapture ";
  2912. OS << DeclarationName(Capture.VarID);
  2913. break;
  2914. }
  2915. if (auto *D = getDecl()) {
  2916. OS << " ";
  2917. D->printQualifiedName(OS);
  2918. }
  2919. OS << " '" << getType().getAsString() << "'\n";
  2920. return Depth + 1;
  2921. }
  2922. LLVM_DUMP_METHOD void InitializedEntity::dump() const {
  2923. dumpImpl(llvm::errs());
  2924. }
  2925. //===----------------------------------------------------------------------===//
  2926. // Initialization sequence
  2927. //===----------------------------------------------------------------------===//
  2928. void InitializationSequence::Step::Destroy() {
  2929. switch (Kind) {
  2930. case SK_ResolveAddressOfOverloadedFunction:
  2931. case SK_CastDerivedToBaseRValue:
  2932. case SK_CastDerivedToBaseXValue:
  2933. case SK_CastDerivedToBaseLValue:
  2934. case SK_BindReference:
  2935. case SK_BindReferenceToTemporary:
  2936. case SK_FinalCopy:
  2937. case SK_ExtraneousCopyToTemporary:
  2938. case SK_UserConversion:
  2939. case SK_QualificationConversionRValue:
  2940. case SK_QualificationConversionXValue:
  2941. case SK_QualificationConversionLValue:
  2942. case SK_AtomicConversion:
  2943. case SK_ListInitialization:
  2944. case SK_UnwrapInitList:
  2945. case SK_RewrapInitList:
  2946. case SK_ConstructorInitialization:
  2947. case SK_ConstructorInitializationFromList:
  2948. case SK_ZeroInitialization:
  2949. case SK_CAssignment:
  2950. case SK_StringInit:
  2951. case SK_ObjCObjectConversion:
  2952. case SK_ArrayLoopIndex:
  2953. case SK_ArrayLoopInit:
  2954. case SK_ArrayInit:
  2955. case SK_GNUArrayInit:
  2956. case SK_ParenthesizedArrayInit:
  2957. case SK_PassByIndirectCopyRestore:
  2958. case SK_PassByIndirectRestore:
  2959. case SK_ProduceObjCObject:
  2960. case SK_StdInitializerList:
  2961. case SK_StdInitializerListConstructorCall:
  2962. case SK_OCLSamplerInit:
  2963. case SK_OCLZeroOpaqueType:
  2964. break;
  2965. case SK_ConversionSequence:
  2966. case SK_ConversionSequenceNoNarrowing:
  2967. delete ICS;
  2968. }
  2969. }
  2970. bool InitializationSequence::isDirectReferenceBinding() const {
  2971. // There can be some lvalue adjustments after the SK_BindReference step.
  2972. for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
  2973. if (I->Kind == SK_BindReference)
  2974. return true;
  2975. if (I->Kind == SK_BindReferenceToTemporary)
  2976. return false;
  2977. }
  2978. return false;
  2979. }
  2980. bool InitializationSequence::isAmbiguous() const {
  2981. if (!Failed())
  2982. return false;
  2983. switch (getFailureKind()) {
  2984. case FK_TooManyInitsForReference:
  2985. case FK_ParenthesizedListInitForReference:
  2986. case FK_ArrayNeedsInitList:
  2987. case FK_ArrayNeedsInitListOrStringLiteral:
  2988. case FK_ArrayNeedsInitListOrWideStringLiteral:
  2989. case FK_NarrowStringIntoWideCharArray:
  2990. case FK_WideStringIntoCharArray:
  2991. case FK_IncompatWideStringIntoWideChar:
  2992. case FK_PlainStringIntoUTF8Char:
  2993. case FK_UTF8StringIntoPlainChar:
  2994. case FK_AddressOfOverloadFailed: // FIXME: Could do better
  2995. case FK_NonConstLValueReferenceBindingToTemporary:
  2996. case FK_NonConstLValueReferenceBindingToBitfield:
  2997. case FK_NonConstLValueReferenceBindingToVectorElement:
  2998. case FK_NonConstLValueReferenceBindingToUnrelated:
  2999. case FK_RValueReferenceBindingToLValue:
  3000. case FK_ReferenceAddrspaceMismatchTemporary:
  3001. case FK_ReferenceInitDropsQualifiers:
  3002. case FK_ReferenceInitFailed:
  3003. case FK_ConversionFailed:
  3004. case FK_ConversionFromPropertyFailed:
  3005. case FK_TooManyInitsForScalar:
  3006. case FK_ParenthesizedListInitForScalar:
  3007. case FK_ReferenceBindingToInitList:
  3008. case FK_InitListBadDestinationType:
  3009. case FK_DefaultInitOfConst:
  3010. case FK_Incomplete:
  3011. case FK_ArrayTypeMismatch:
  3012. case FK_NonConstantArrayInit:
  3013. case FK_ListInitializationFailed:
  3014. case FK_VariableLengthArrayHasInitializer:
  3015. case FK_PlaceholderType:
  3016. case FK_ExplicitConstructor:
  3017. case FK_AddressOfUnaddressableFunction:
  3018. return false;
  3019. case FK_ReferenceInitOverloadFailed:
  3020. case FK_UserConversionOverloadFailed:
  3021. case FK_ConstructorOverloadFailed:
  3022. case FK_ListConstructorOverloadFailed:
  3023. return FailedOverloadResult == OR_Ambiguous;
  3024. }
  3025. llvm_unreachable("Invalid EntityKind!");
  3026. }
  3027. bool InitializationSequence::isConstructorInitialization() const {
  3028. return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
  3029. }
  3030. void
  3031. InitializationSequence
  3032. ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
  3033. DeclAccessPair Found,
  3034. bool HadMultipleCandidates) {
  3035. Step S;
  3036. S.Kind = SK_ResolveAddressOfOverloadedFunction;
  3037. S.Type = Function->getType();
  3038. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3039. S.Function.Function = Function;
  3040. S.Function.FoundDecl = Found;
  3041. Steps.push_back(S);
  3042. }
  3043. void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
  3044. ExprValueKind VK) {
  3045. Step S;
  3046. switch (VK) {
  3047. case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
  3048. case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
  3049. case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
  3050. }
  3051. S.Type = BaseType;
  3052. Steps.push_back(S);
  3053. }
  3054. void InitializationSequence::AddReferenceBindingStep(QualType T,
  3055. bool BindingTemporary) {
  3056. Step S;
  3057. S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
  3058. S.Type = T;
  3059. Steps.push_back(S);
  3060. }
  3061. void InitializationSequence::AddFinalCopy(QualType T) {
  3062. Step S;
  3063. S.Kind = SK_FinalCopy;
  3064. S.Type = T;
  3065. Steps.push_back(S);
  3066. }
  3067. void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
  3068. Step S;
  3069. S.Kind = SK_ExtraneousCopyToTemporary;
  3070. S.Type = T;
  3071. Steps.push_back(S);
  3072. }
  3073. void
  3074. InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
  3075. DeclAccessPair FoundDecl,
  3076. QualType T,
  3077. bool HadMultipleCandidates) {
  3078. Step S;
  3079. S.Kind = SK_UserConversion;
  3080. S.Type = T;
  3081. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3082. S.Function.Function = Function;
  3083. S.Function.FoundDecl = FoundDecl;
  3084. Steps.push_back(S);
  3085. }
  3086. void InitializationSequence::AddQualificationConversionStep(QualType Ty,
  3087. ExprValueKind VK) {
  3088. Step S;
  3089. S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
  3090. switch (VK) {
  3091. case VK_RValue:
  3092. S.Kind = SK_QualificationConversionRValue;
  3093. break;
  3094. case VK_XValue:
  3095. S.Kind = SK_QualificationConversionXValue;
  3096. break;
  3097. case VK_LValue:
  3098. S.Kind = SK_QualificationConversionLValue;
  3099. break;
  3100. }
  3101. S.Type = Ty;
  3102. Steps.push_back(S);
  3103. }
  3104. void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
  3105. Step S;
  3106. S.Kind = SK_AtomicConversion;
  3107. S.Type = Ty;
  3108. Steps.push_back(S);
  3109. }
  3110. void InitializationSequence::AddConversionSequenceStep(
  3111. const ImplicitConversionSequence &ICS, QualType T,
  3112. bool TopLevelOfInitList) {
  3113. Step S;
  3114. S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
  3115. : SK_ConversionSequence;
  3116. S.Type = T;
  3117. S.ICS = new ImplicitConversionSequence(ICS);
  3118. Steps.push_back(S);
  3119. }
  3120. void InitializationSequence::AddListInitializationStep(QualType T) {
  3121. Step S;
  3122. S.Kind = SK_ListInitialization;
  3123. S.Type = T;
  3124. Steps.push_back(S);
  3125. }
  3126. void InitializationSequence::AddConstructorInitializationStep(
  3127. DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
  3128. bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
  3129. Step S;
  3130. S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
  3131. : SK_ConstructorInitializationFromList
  3132. : SK_ConstructorInitialization;
  3133. S.Type = T;
  3134. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3135. S.Function.Function = Constructor;
  3136. S.Function.FoundDecl = FoundDecl;
  3137. Steps.push_back(S);
  3138. }
  3139. void InitializationSequence::AddZeroInitializationStep(QualType T) {
  3140. Step S;
  3141. S.Kind = SK_ZeroInitialization;
  3142. S.Type = T;
  3143. Steps.push_back(S);
  3144. }
  3145. void InitializationSequence::AddCAssignmentStep(QualType T) {
  3146. Step S;
  3147. S.Kind = SK_CAssignment;
  3148. S.Type = T;
  3149. Steps.push_back(S);
  3150. }
  3151. void InitializationSequence::AddStringInitStep(QualType T) {
  3152. Step S;
  3153. S.Kind = SK_StringInit;
  3154. S.Type = T;
  3155. Steps.push_back(S);
  3156. }
  3157. void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
  3158. Step S;
  3159. S.Kind = SK_ObjCObjectConversion;
  3160. S.Type = T;
  3161. Steps.push_back(S);
  3162. }
  3163. void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
  3164. Step S;
  3165. S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
  3166. S.Type = T;
  3167. Steps.push_back(S);
  3168. }
  3169. void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
  3170. Step S;
  3171. S.Kind = SK_ArrayLoopIndex;
  3172. S.Type = EltT;
  3173. Steps.insert(Steps.begin(), S);
  3174. S.Kind = SK_ArrayLoopInit;
  3175. S.Type = T;
  3176. Steps.push_back(S);
  3177. }
  3178. void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
  3179. Step S;
  3180. S.Kind = SK_ParenthesizedArrayInit;
  3181. S.Type = T;
  3182. Steps.push_back(S);
  3183. }
  3184. void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
  3185. bool shouldCopy) {
  3186. Step s;
  3187. s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
  3188. : SK_PassByIndirectRestore);
  3189. s.Type = type;
  3190. Steps.push_back(s);
  3191. }
  3192. void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
  3193. Step S;
  3194. S.Kind = SK_ProduceObjCObject;
  3195. S.Type = T;
  3196. Steps.push_back(S);
  3197. }
  3198. void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
  3199. Step S;
  3200. S.Kind = SK_StdInitializerList;
  3201. S.Type = T;
  3202. Steps.push_back(S);
  3203. }
  3204. void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
  3205. Step S;
  3206. S.Kind = SK_OCLSamplerInit;
  3207. S.Type = T;
  3208. Steps.push_back(S);
  3209. }
  3210. void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
  3211. Step S;
  3212. S.Kind = SK_OCLZeroOpaqueType;
  3213. S.Type = T;
  3214. Steps.push_back(S);
  3215. }
  3216. void InitializationSequence::RewrapReferenceInitList(QualType T,
  3217. InitListExpr *Syntactic) {
  3218. assert(Syntactic->getNumInits() == 1 &&
  3219. "Can only rewrap trivial init lists.");
  3220. Step S;
  3221. S.Kind = SK_UnwrapInitList;
  3222. S.Type = Syntactic->getInit(0)->getType();
  3223. Steps.insert(Steps.begin(), S);
  3224. S.Kind = SK_RewrapInitList;
  3225. S.Type = T;
  3226. S.WrappingSyntacticList = Syntactic;
  3227. Steps.push_back(S);
  3228. }
  3229. void InitializationSequence::SetOverloadFailure(FailureKind Failure,
  3230. OverloadingResult Result) {
  3231. setSequenceKind(FailedSequence);
  3232. this->Failure = Failure;
  3233. this->FailedOverloadResult = Result;
  3234. }
  3235. //===----------------------------------------------------------------------===//
  3236. // Attempt initialization
  3237. //===----------------------------------------------------------------------===//
  3238. /// Tries to add a zero initializer. Returns true if that worked.
  3239. static bool
  3240. maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
  3241. const InitializedEntity &Entity) {
  3242. if (Entity.getKind() != InitializedEntity::EK_Variable)
  3243. return false;
  3244. VarDecl *VD = cast<VarDecl>(Entity.getDecl());
  3245. if (VD->getInit() || VD->getEndLoc().isMacroID())
  3246. return false;
  3247. QualType VariableTy = VD->getType().getCanonicalType();
  3248. SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
  3249. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  3250. if (!Init.empty()) {
  3251. Sequence.AddZeroInitializationStep(Entity.getType());
  3252. Sequence.SetZeroInitializationFixit(Init, Loc);
  3253. return true;
  3254. }
  3255. return false;
  3256. }
  3257. static void MaybeProduceObjCObject(Sema &S,
  3258. InitializationSequence &Sequence,
  3259. const InitializedEntity &Entity) {
  3260. if (!S.getLangOpts().ObjCAutoRefCount) return;
  3261. /// When initializing a parameter, produce the value if it's marked
  3262. /// __attribute__((ns_consumed)).
  3263. if (Entity.isParameterKind()) {
  3264. if (!Entity.isParameterConsumed())
  3265. return;
  3266. assert(Entity.getType()->isObjCRetainableType() &&
  3267. "consuming an object of unretainable type?");
  3268. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3269. /// When initializing a return value, if the return type is a
  3270. /// retainable type, then returns need to immediately retain the
  3271. /// object. If an autorelease is required, it will be done at the
  3272. /// last instant.
  3273. } else if (Entity.getKind() == InitializedEntity::EK_Result ||
  3274. Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
  3275. if (!Entity.getType()->isObjCRetainableType())
  3276. return;
  3277. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3278. }
  3279. }
  3280. static void TryListInitialization(Sema &S,
  3281. const InitializedEntity &Entity,
  3282. const InitializationKind &Kind,
  3283. InitListExpr *InitList,
  3284. InitializationSequence &Sequence,
  3285. bool TreatUnavailableAsInvalid);
  3286. /// When initializing from init list via constructor, handle
  3287. /// initialization of an object of type std::initializer_list<T>.
  3288. ///
  3289. /// \return true if we have handled initialization of an object of type
  3290. /// std::initializer_list<T>, false otherwise.
  3291. static bool TryInitializerListConstruction(Sema &S,
  3292. InitListExpr *List,
  3293. QualType DestType,
  3294. InitializationSequence &Sequence,
  3295. bool TreatUnavailableAsInvalid) {
  3296. QualType E;
  3297. if (!S.isStdInitializerList(DestType, &E))
  3298. return false;
  3299. if (!S.isCompleteType(List->getExprLoc(), E)) {
  3300. Sequence.setIncompleteTypeFailure(E);
  3301. return true;
  3302. }
  3303. // Try initializing a temporary array from the init list.
  3304. QualType ArrayType = S.Context.getConstantArrayType(
  3305. E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  3306. List->getNumInits()),
  3307. clang::ArrayType::Normal, 0);
  3308. InitializedEntity HiddenArray =
  3309. InitializedEntity::InitializeTemporary(ArrayType);
  3310. InitializationKind Kind = InitializationKind::CreateDirectList(
  3311. List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
  3312. TryListInitialization(S, HiddenArray, Kind, List, Sequence,
  3313. TreatUnavailableAsInvalid);
  3314. if (Sequence)
  3315. Sequence.AddStdInitializerListConstructionStep(DestType);
  3316. return true;
  3317. }
  3318. /// Determine if the constructor has the signature of a copy or move
  3319. /// constructor for the type T of the class in which it was found. That is,
  3320. /// determine if its first parameter is of type T or reference to (possibly
  3321. /// cv-qualified) T.
  3322. static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
  3323. const ConstructorInfo &Info) {
  3324. if (Info.Constructor->getNumParams() == 0)
  3325. return false;
  3326. QualType ParmT =
  3327. Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
  3328. QualType ClassT =
  3329. Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
  3330. return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
  3331. }
  3332. static OverloadingResult
  3333. ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
  3334. MultiExprArg Args,
  3335. OverloadCandidateSet &CandidateSet,
  3336. QualType DestType,
  3337. DeclContext::lookup_result Ctors,
  3338. OverloadCandidateSet::iterator &Best,
  3339. bool CopyInitializing, bool AllowExplicit,
  3340. bool OnlyListConstructors, bool IsListInit,
  3341. bool SecondStepOfCopyInit = false) {
  3342. CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
  3343. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  3344. for (NamedDecl *D : Ctors) {
  3345. auto Info = getConstructorInfo(D);
  3346. if (!Info.Constructor || Info.Constructor->isInvalidDecl())
  3347. continue;
  3348. if (!AllowExplicit && Info.Constructor->isExplicit())
  3349. continue;
  3350. if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
  3351. continue;
  3352. // C++11 [over.best.ics]p4:
  3353. // ... and the constructor or user-defined conversion function is a
  3354. // candidate by
  3355. // - 13.3.1.3, when the argument is the temporary in the second step
  3356. // of a class copy-initialization, or
  3357. // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
  3358. // - the second phase of 13.3.1.7 when the initializer list has exactly
  3359. // one element that is itself an initializer list, and the target is
  3360. // the first parameter of a constructor of class X, and the conversion
  3361. // is to X or reference to (possibly cv-qualified X),
  3362. // user-defined conversion sequences are not considered.
  3363. bool SuppressUserConversions =
  3364. SecondStepOfCopyInit ||
  3365. (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  3366. hasCopyOrMoveCtorParam(S.Context, Info));
  3367. if (Info.ConstructorTmpl)
  3368. S.AddTemplateOverloadCandidate(
  3369. Info.ConstructorTmpl, Info.FoundDecl,
  3370. /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
  3371. /*PartialOverloading=*/false, AllowExplicit);
  3372. else {
  3373. // C++ [over.match.copy]p1:
  3374. // - When initializing a temporary to be bound to the first parameter
  3375. // of a constructor [for type T] that takes a reference to possibly
  3376. // cv-qualified T as its first argument, called with a single
  3377. // argument in the context of direct-initialization, explicit
  3378. // conversion functions are also considered.
  3379. // FIXME: What if a constructor template instantiates to such a signature?
  3380. bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
  3381. Args.size() == 1 &&
  3382. hasCopyOrMoveCtorParam(S.Context, Info);
  3383. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
  3384. CandidateSet, SuppressUserConversions,
  3385. /*PartialOverloading=*/false, AllowExplicit,
  3386. AllowExplicitConv);
  3387. }
  3388. }
  3389. // FIXME: Work around a bug in C++17 guaranteed copy elision.
  3390. //
  3391. // When initializing an object of class type T by constructor
  3392. // ([over.match.ctor]) or by list-initialization ([over.match.list])
  3393. // from a single expression of class type U, conversion functions of
  3394. // U that convert to the non-reference type cv T are candidates.
  3395. // Explicit conversion functions are only candidates during
  3396. // direct-initialization.
  3397. //
  3398. // Note: SecondStepOfCopyInit is only ever true in this case when
  3399. // evaluating whether to produce a C++98 compatibility warning.
  3400. if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
  3401. !SecondStepOfCopyInit) {
  3402. Expr *Initializer = Args[0];
  3403. auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
  3404. if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
  3405. const auto &Conversions = SourceRD->getVisibleConversionFunctions();
  3406. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3407. NamedDecl *D = *I;
  3408. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3409. D = D->getUnderlyingDecl();
  3410. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3411. CXXConversionDecl *Conv;
  3412. if (ConvTemplate)
  3413. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3414. else
  3415. Conv = cast<CXXConversionDecl>(D);
  3416. if (AllowExplicit || !Conv->isExplicit()) {
  3417. if (ConvTemplate)
  3418. S.AddTemplateConversionCandidate(
  3419. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  3420. CandidateSet, AllowExplicit, AllowExplicit,
  3421. /*AllowResultConversion*/ false);
  3422. else
  3423. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  3424. DestType, CandidateSet, AllowExplicit,
  3425. AllowExplicit,
  3426. /*AllowResultConversion*/ false);
  3427. }
  3428. }
  3429. }
  3430. }
  3431. // Perform overload resolution and return the result.
  3432. return CandidateSet.BestViableFunction(S, DeclLoc, Best);
  3433. }
  3434. /// Attempt initialization by constructor (C++ [dcl.init]), which
  3435. /// enumerates the constructors of the initialized entity and performs overload
  3436. /// resolution to select the best.
  3437. /// \param DestType The destination class type.
  3438. /// \param DestArrayType The destination type, which is either DestType or
  3439. /// a (possibly multidimensional) array of DestType.
  3440. /// \param IsListInit Is this list-initialization?
  3441. /// \param IsInitListCopy Is this non-list-initialization resulting from a
  3442. /// list-initialization from {x} where x is the same
  3443. /// type as the entity?
  3444. static void TryConstructorInitialization(Sema &S,
  3445. const InitializedEntity &Entity,
  3446. const InitializationKind &Kind,
  3447. MultiExprArg Args, QualType DestType,
  3448. QualType DestArrayType,
  3449. InitializationSequence &Sequence,
  3450. bool IsListInit = false,
  3451. bool IsInitListCopy = false) {
  3452. assert(((!IsListInit && !IsInitListCopy) ||
  3453. (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
  3454. "IsListInit/IsInitListCopy must come with a single initializer list "
  3455. "argument.");
  3456. InitListExpr *ILE =
  3457. (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
  3458. MultiExprArg UnwrappedArgs =
  3459. ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
  3460. // The type we're constructing needs to be complete.
  3461. if (!S.isCompleteType(Kind.getLocation(), DestType)) {
  3462. Sequence.setIncompleteTypeFailure(DestType);
  3463. return;
  3464. }
  3465. // C++17 [dcl.init]p17:
  3466. // - If the initializer expression is a prvalue and the cv-unqualified
  3467. // version of the source type is the same class as the class of the
  3468. // destination, the initializer expression is used to initialize the
  3469. // destination object.
  3470. // Per DR (no number yet), this does not apply when initializing a base
  3471. // class or delegating to another constructor from a mem-initializer.
  3472. // ObjC++: Lambda captured by the block in the lambda to block conversion
  3473. // should avoid copy elision.
  3474. if (S.getLangOpts().CPlusPlus17 &&
  3475. Entity.getKind() != InitializedEntity::EK_Base &&
  3476. Entity.getKind() != InitializedEntity::EK_Delegating &&
  3477. Entity.getKind() !=
  3478. InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
  3479. UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
  3480. S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
  3481. // Convert qualifications if necessary.
  3482. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  3483. if (ILE)
  3484. Sequence.RewrapReferenceInitList(DestType, ILE);
  3485. return;
  3486. }
  3487. const RecordType *DestRecordType = DestType->getAs<RecordType>();
  3488. assert(DestRecordType && "Constructor initialization requires record type");
  3489. CXXRecordDecl *DestRecordDecl
  3490. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  3491. // Build the candidate set directly in the initialization sequence
  3492. // structure, so that it will persist if we fail.
  3493. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3494. // Determine whether we are allowed to call explicit constructors or
  3495. // explicit conversion operators.
  3496. bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
  3497. bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
  3498. // - Otherwise, if T is a class type, constructors are considered. The
  3499. // applicable constructors are enumerated, and the best one is chosen
  3500. // through overload resolution.
  3501. DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
  3502. OverloadingResult Result = OR_No_Viable_Function;
  3503. OverloadCandidateSet::iterator Best;
  3504. bool AsInitializerList = false;
  3505. // C++11 [over.match.list]p1, per DR1467:
  3506. // When objects of non-aggregate type T are list-initialized, such that
  3507. // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
  3508. // according to the rules in this section, overload resolution selects
  3509. // the constructor in two phases:
  3510. //
  3511. // - Initially, the candidate functions are the initializer-list
  3512. // constructors of the class T and the argument list consists of the
  3513. // initializer list as a single argument.
  3514. if (IsListInit) {
  3515. AsInitializerList = true;
  3516. // If the initializer list has no elements and T has a default constructor,
  3517. // the first phase is omitted.
  3518. if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
  3519. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
  3520. CandidateSet, DestType, Ctors, Best,
  3521. CopyInitialization, AllowExplicit,
  3522. /*OnlyListConstructors=*/true,
  3523. IsListInit);
  3524. }
  3525. // C++11 [over.match.list]p1:
  3526. // - If no viable initializer-list constructor is found, overload resolution
  3527. // is performed again, where the candidate functions are all the
  3528. // constructors of the class T and the argument list consists of the
  3529. // elements of the initializer list.
  3530. if (Result == OR_No_Viable_Function) {
  3531. AsInitializerList = false;
  3532. Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
  3533. CandidateSet, DestType, Ctors, Best,
  3534. CopyInitialization, AllowExplicit,
  3535. /*OnlyListConstructors=*/false,
  3536. IsListInit);
  3537. }
  3538. if (Result) {
  3539. Sequence.SetOverloadFailure(IsListInit ?
  3540. InitializationSequence::FK_ListConstructorOverloadFailed :
  3541. InitializationSequence::FK_ConstructorOverloadFailed,
  3542. Result);
  3543. return;
  3544. }
  3545. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3546. // In C++17, ResolveConstructorOverload can select a conversion function
  3547. // instead of a constructor.
  3548. if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3549. // Add the user-defined conversion step that calls the conversion function.
  3550. QualType ConvType = CD->getConversionType();
  3551. assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
  3552. "should not have selected this conversion function");
  3553. Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
  3554. HadMultipleCandidates);
  3555. if (!S.Context.hasSameType(ConvType, DestType))
  3556. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  3557. if (IsListInit)
  3558. Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
  3559. return;
  3560. }
  3561. // C++11 [dcl.init]p6:
  3562. // If a program calls for the default initialization of an object
  3563. // of a const-qualified type T, T shall be a class type with a
  3564. // user-provided default constructor.
  3565. // C++ core issue 253 proposal:
  3566. // If the implicit default constructor initializes all subobjects, no
  3567. // initializer should be required.
  3568. // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
  3569. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  3570. if (Kind.getKind() == InitializationKind::IK_Default &&
  3571. Entity.getType().isConstQualified()) {
  3572. if (!CtorDecl->getParent()->allowConstDefaultInit()) {
  3573. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  3574. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3575. return;
  3576. }
  3577. }
  3578. // C++11 [over.match.list]p1:
  3579. // In copy-list-initialization, if an explicit constructor is chosen, the
  3580. // initializer is ill-formed.
  3581. if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
  3582. Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
  3583. return;
  3584. }
  3585. // Add the constructor initialization step. Any cv-qualification conversion is
  3586. // subsumed by the initialization.
  3587. Sequence.AddConstructorInitializationStep(
  3588. Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
  3589. IsListInit | IsInitListCopy, AsInitializerList);
  3590. }
  3591. static bool
  3592. ResolveOverloadedFunctionForReferenceBinding(Sema &S,
  3593. Expr *Initializer,
  3594. QualType &SourceType,
  3595. QualType &UnqualifiedSourceType,
  3596. QualType UnqualifiedTargetType,
  3597. InitializationSequence &Sequence) {
  3598. if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
  3599. S.Context.OverloadTy) {
  3600. DeclAccessPair Found;
  3601. bool HadMultipleCandidates = false;
  3602. if (FunctionDecl *Fn
  3603. = S.ResolveAddressOfOverloadedFunction(Initializer,
  3604. UnqualifiedTargetType,
  3605. false, Found,
  3606. &HadMultipleCandidates)) {
  3607. Sequence.AddAddressOverloadResolutionStep(Fn, Found,
  3608. HadMultipleCandidates);
  3609. SourceType = Fn->getType();
  3610. UnqualifiedSourceType = SourceType.getUnqualifiedType();
  3611. } else if (!UnqualifiedTargetType->isRecordType()) {
  3612. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3613. return true;
  3614. }
  3615. }
  3616. return false;
  3617. }
  3618. static void TryReferenceInitializationCore(Sema &S,
  3619. const InitializedEntity &Entity,
  3620. const InitializationKind &Kind,
  3621. Expr *Initializer,
  3622. QualType cv1T1, QualType T1,
  3623. Qualifiers T1Quals,
  3624. QualType cv2T2, QualType T2,
  3625. Qualifiers T2Quals,
  3626. InitializationSequence &Sequence);
  3627. static void TryValueInitialization(Sema &S,
  3628. const InitializedEntity &Entity,
  3629. const InitializationKind &Kind,
  3630. InitializationSequence &Sequence,
  3631. InitListExpr *InitList = nullptr);
  3632. /// Attempt list initialization of a reference.
  3633. static void TryReferenceListInitialization(Sema &S,
  3634. const InitializedEntity &Entity,
  3635. const InitializationKind &Kind,
  3636. InitListExpr *InitList,
  3637. InitializationSequence &Sequence,
  3638. bool TreatUnavailableAsInvalid) {
  3639. // First, catch C++03 where this isn't possible.
  3640. if (!S.getLangOpts().CPlusPlus11) {
  3641. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3642. return;
  3643. }
  3644. // Can't reference initialize a compound literal.
  3645. if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
  3646. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3647. return;
  3648. }
  3649. QualType DestType = Entity.getType();
  3650. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3651. Qualifiers T1Quals;
  3652. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  3653. // Reference initialization via an initializer list works thus:
  3654. // If the initializer list consists of a single element that is
  3655. // reference-related to the referenced type, bind directly to that element
  3656. // (possibly creating temporaries).
  3657. // Otherwise, initialize a temporary with the initializer list and
  3658. // bind to that.
  3659. if (InitList->getNumInits() == 1) {
  3660. Expr *Initializer = InitList->getInit(0);
  3661. QualType cv2T2 = Initializer->getType();
  3662. Qualifiers T2Quals;
  3663. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  3664. // If this fails, creating a temporary wouldn't work either.
  3665. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  3666. T1, Sequence))
  3667. return;
  3668. SourceLocation DeclLoc = Initializer->getBeginLoc();
  3669. bool dummy1, dummy2, dummy3;
  3670. Sema::ReferenceCompareResult RefRelationship
  3671. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
  3672. dummy2, dummy3);
  3673. if (RefRelationship >= Sema::Ref_Related) {
  3674. // Try to bind the reference here.
  3675. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  3676. T1Quals, cv2T2, T2, T2Quals, Sequence);
  3677. if (Sequence)
  3678. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3679. return;
  3680. }
  3681. // Update the initializer if we've resolved an overloaded function.
  3682. if (Sequence.step_begin() != Sequence.step_end())
  3683. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3684. }
  3685. // Not reference-related. Create a temporary and bind to that.
  3686. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  3687. TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
  3688. TreatUnavailableAsInvalid);
  3689. if (Sequence) {
  3690. if (DestType->isRValueReferenceType() ||
  3691. (T1Quals.hasConst() && !T1Quals.hasVolatile()))
  3692. Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
  3693. else
  3694. Sequence.SetFailed(
  3695. InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3696. }
  3697. }
  3698. /// Attempt list initialization (C++0x [dcl.init.list])
  3699. static void TryListInitialization(Sema &S,
  3700. const InitializedEntity &Entity,
  3701. const InitializationKind &Kind,
  3702. InitListExpr *InitList,
  3703. InitializationSequence &Sequence,
  3704. bool TreatUnavailableAsInvalid) {
  3705. QualType DestType = Entity.getType();
  3706. // C++ doesn't allow scalar initialization with more than one argument.
  3707. // But C99 complex numbers are scalars and it makes sense there.
  3708. if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
  3709. !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
  3710. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
  3711. return;
  3712. }
  3713. if (DestType->isReferenceType()) {
  3714. TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
  3715. TreatUnavailableAsInvalid);
  3716. return;
  3717. }
  3718. if (DestType->isRecordType() &&
  3719. !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
  3720. Sequence.setIncompleteTypeFailure(DestType);
  3721. return;
  3722. }
  3723. // C++11 [dcl.init.list]p3, per DR1467:
  3724. // - If T is a class type and the initializer list has a single element of
  3725. // type cv U, where U is T or a class derived from T, the object is
  3726. // initialized from that element (by copy-initialization for
  3727. // copy-list-initialization, or by direct-initialization for
  3728. // direct-list-initialization).
  3729. // - Otherwise, if T is a character array and the initializer list has a
  3730. // single element that is an appropriately-typed string literal
  3731. // (8.5.2 [dcl.init.string]), initialization is performed as described
  3732. // in that section.
  3733. // - Otherwise, if T is an aggregate, [...] (continue below).
  3734. if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
  3735. if (DestType->isRecordType()) {
  3736. QualType InitType = InitList->getInit(0)->getType();
  3737. if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
  3738. S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
  3739. Expr *InitListAsExpr = InitList;
  3740. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  3741. DestType, Sequence,
  3742. /*InitListSyntax*/false,
  3743. /*IsInitListCopy*/true);
  3744. return;
  3745. }
  3746. }
  3747. if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
  3748. Expr *SubInit[1] = {InitList->getInit(0)};
  3749. if (!isa<VariableArrayType>(DestAT) &&
  3750. IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
  3751. InitializationKind SubKind =
  3752. Kind.getKind() == InitializationKind::IK_DirectList
  3753. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3754. InitList->getLBraceLoc(),
  3755. InitList->getRBraceLoc())
  3756. : Kind;
  3757. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3758. /*TopLevelOfInitList*/ true,
  3759. TreatUnavailableAsInvalid);
  3760. // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
  3761. // the element is not an appropriately-typed string literal, in which
  3762. // case we should proceed as in C++11 (below).
  3763. if (Sequence) {
  3764. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3765. return;
  3766. }
  3767. }
  3768. }
  3769. }
  3770. // C++11 [dcl.init.list]p3:
  3771. // - If T is an aggregate, aggregate initialization is performed.
  3772. if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
  3773. (S.getLangOpts().CPlusPlus11 &&
  3774. S.isStdInitializerList(DestType, nullptr))) {
  3775. if (S.getLangOpts().CPlusPlus11) {
  3776. // - Otherwise, if the initializer list has no elements and T is a
  3777. // class type with a default constructor, the object is
  3778. // value-initialized.
  3779. if (InitList->getNumInits() == 0) {
  3780. CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
  3781. if (RD->hasDefaultConstructor()) {
  3782. TryValueInitialization(S, Entity, Kind, Sequence, InitList);
  3783. return;
  3784. }
  3785. }
  3786. // - Otherwise, if T is a specialization of std::initializer_list<E>,
  3787. // an initializer_list object constructed [...]
  3788. if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
  3789. TreatUnavailableAsInvalid))
  3790. return;
  3791. // - Otherwise, if T is a class type, constructors are considered.
  3792. Expr *InitListAsExpr = InitList;
  3793. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  3794. DestType, Sequence, /*InitListSyntax*/true);
  3795. } else
  3796. Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
  3797. return;
  3798. }
  3799. if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
  3800. InitList->getNumInits() == 1) {
  3801. Expr *E = InitList->getInit(0);
  3802. // - Otherwise, if T is an enumeration with a fixed underlying type,
  3803. // the initializer-list has a single element v, and the initialization
  3804. // is direct-list-initialization, the object is initialized with the
  3805. // value T(v); if a narrowing conversion is required to convert v to
  3806. // the underlying type of T, the program is ill-formed.
  3807. auto *ET = DestType->getAs<EnumType>();
  3808. if (S.getLangOpts().CPlusPlus17 &&
  3809. Kind.getKind() == InitializationKind::IK_DirectList &&
  3810. ET && ET->getDecl()->isFixed() &&
  3811. !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
  3812. (E->getType()->isIntegralOrEnumerationType() ||
  3813. E->getType()->isFloatingType())) {
  3814. // There are two ways that T(v) can work when T is an enumeration type.
  3815. // If there is either an implicit conversion sequence from v to T or
  3816. // a conversion function that can convert from v to T, then we use that.
  3817. // Otherwise, if v is of integral, enumeration, or floating-point type,
  3818. // it is converted to the enumeration type via its underlying type.
  3819. // There is no overlap possible between these two cases (except when the
  3820. // source value is already of the destination type), and the first
  3821. // case is handled by the general case for single-element lists below.
  3822. ImplicitConversionSequence ICS;
  3823. ICS.setStandard();
  3824. ICS.Standard.setAsIdentityConversion();
  3825. if (!E->isRValue())
  3826. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  3827. // If E is of a floating-point type, then the conversion is ill-formed
  3828. // due to narrowing, but go through the motions in order to produce the
  3829. // right diagnostic.
  3830. ICS.Standard.Second = E->getType()->isFloatingType()
  3831. ? ICK_Floating_Integral
  3832. : ICK_Integral_Conversion;
  3833. ICS.Standard.setFromType(E->getType());
  3834. ICS.Standard.setToType(0, E->getType());
  3835. ICS.Standard.setToType(1, DestType);
  3836. ICS.Standard.setToType(2, DestType);
  3837. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
  3838. /*TopLevelOfInitList*/true);
  3839. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3840. return;
  3841. }
  3842. // - Otherwise, if the initializer list has a single element of type E
  3843. // [...references are handled above...], the object or reference is
  3844. // initialized from that element (by copy-initialization for
  3845. // copy-list-initialization, or by direct-initialization for
  3846. // direct-list-initialization); if a narrowing conversion is required
  3847. // to convert the element to T, the program is ill-formed.
  3848. //
  3849. // Per core-24034, this is direct-initialization if we were performing
  3850. // direct-list-initialization and copy-initialization otherwise.
  3851. // We can't use InitListChecker for this, because it always performs
  3852. // copy-initialization. This only matters if we might use an 'explicit'
  3853. // conversion operator, so we only need to handle the cases where the source
  3854. // is of record type.
  3855. if (InitList->getInit(0)->getType()->isRecordType()) {
  3856. InitializationKind SubKind =
  3857. Kind.getKind() == InitializationKind::IK_DirectList
  3858. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3859. InitList->getLBraceLoc(),
  3860. InitList->getRBraceLoc())
  3861. : Kind;
  3862. Expr *SubInit[1] = { InitList->getInit(0) };
  3863. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3864. /*TopLevelOfInitList*/true,
  3865. TreatUnavailableAsInvalid);
  3866. if (Sequence)
  3867. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3868. return;
  3869. }
  3870. }
  3871. InitListChecker CheckInitList(S, Entity, InitList,
  3872. DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
  3873. if (CheckInitList.HadError()) {
  3874. Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
  3875. return;
  3876. }
  3877. // Add the list initialization step with the built init list.
  3878. Sequence.AddListInitializationStep(DestType);
  3879. }
  3880. /// Try a reference initialization that involves calling a conversion
  3881. /// function.
  3882. static OverloadingResult TryRefInitWithConversionFunction(
  3883. Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
  3884. Expr *Initializer, bool AllowRValues, bool IsLValueRef,
  3885. InitializationSequence &Sequence) {
  3886. QualType DestType = Entity.getType();
  3887. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3888. QualType T1 = cv1T1.getUnqualifiedType();
  3889. QualType cv2T2 = Initializer->getType();
  3890. QualType T2 = cv2T2.getUnqualifiedType();
  3891. bool DerivedToBase;
  3892. bool ObjCConversion;
  3893. bool ObjCLifetimeConversion;
  3894. assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
  3895. DerivedToBase, ObjCConversion,
  3896. ObjCLifetimeConversion) &&
  3897. "Must have incompatible references when binding via conversion");
  3898. (void)DerivedToBase;
  3899. (void)ObjCConversion;
  3900. (void)ObjCLifetimeConversion;
  3901. // Build the candidate set directly in the initialization sequence
  3902. // structure, so that it will persist if we fail.
  3903. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3904. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3905. // Determine whether we are allowed to call explicit conversion operators.
  3906. // Note that none of [over.match.copy], [over.match.conv], nor
  3907. // [over.match.ref] permit an explicit constructor to be chosen when
  3908. // initializing a reference, not even for direct-initialization.
  3909. bool AllowExplicitCtors = false;
  3910. bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
  3911. const RecordType *T1RecordType = nullptr;
  3912. if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
  3913. S.isCompleteType(Kind.getLocation(), T1)) {
  3914. // The type we're converting to is a class type. Enumerate its constructors
  3915. // to see if there is a suitable conversion.
  3916. CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
  3917. for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
  3918. auto Info = getConstructorInfo(D);
  3919. if (!Info.Constructor)
  3920. continue;
  3921. if (!Info.Constructor->isInvalidDecl() &&
  3922. Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
  3923. if (Info.ConstructorTmpl)
  3924. S.AddTemplateOverloadCandidate(
  3925. Info.ConstructorTmpl, Info.FoundDecl,
  3926. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  3927. /*SuppressUserConversions=*/true,
  3928. /*PartialOverloading*/ false, AllowExplicitCtors);
  3929. else
  3930. S.AddOverloadCandidate(
  3931. Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
  3932. /*SuppressUserConversions=*/true,
  3933. /*PartialOverloading*/ false, AllowExplicitCtors);
  3934. }
  3935. }
  3936. }
  3937. if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
  3938. return OR_No_Viable_Function;
  3939. const RecordType *T2RecordType = nullptr;
  3940. if ((T2RecordType = T2->getAs<RecordType>()) &&
  3941. S.isCompleteType(Kind.getLocation(), T2)) {
  3942. // The type we're converting from is a class type, enumerate its conversion
  3943. // functions.
  3944. CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
  3945. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3946. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3947. NamedDecl *D = *I;
  3948. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3949. if (isa<UsingShadowDecl>(D))
  3950. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3951. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3952. CXXConversionDecl *Conv;
  3953. if (ConvTemplate)
  3954. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3955. else
  3956. Conv = cast<CXXConversionDecl>(D);
  3957. // If the conversion function doesn't return a reference type,
  3958. // it can't be considered for this conversion unless we're allowed to
  3959. // consider rvalues.
  3960. // FIXME: Do we need to make sure that we only consider conversion
  3961. // candidates with reference-compatible results? That might be needed to
  3962. // break recursion.
  3963. if ((AllowExplicitConvs || !Conv->isExplicit()) &&
  3964. (AllowRValues ||
  3965. Conv->getConversionType()->isLValueReferenceType())) {
  3966. if (ConvTemplate)
  3967. S.AddTemplateConversionCandidate(
  3968. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  3969. CandidateSet,
  3970. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  3971. else
  3972. S.AddConversionCandidate(
  3973. Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
  3974. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  3975. }
  3976. }
  3977. }
  3978. if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
  3979. return OR_No_Viable_Function;
  3980. SourceLocation DeclLoc = Initializer->getBeginLoc();
  3981. // Perform overload resolution. If it fails, return the failed result.
  3982. OverloadCandidateSet::iterator Best;
  3983. if (OverloadingResult Result
  3984. = CandidateSet.BestViableFunction(S, DeclLoc, Best))
  3985. return Result;
  3986. FunctionDecl *Function = Best->Function;
  3987. // This is the overload that will be used for this initialization step if we
  3988. // use this initialization. Mark it as referenced.
  3989. Function->setReferenced();
  3990. // Compute the returned type and value kind of the conversion.
  3991. QualType cv3T3;
  3992. if (isa<CXXConversionDecl>(Function))
  3993. cv3T3 = Function->getReturnType();
  3994. else
  3995. cv3T3 = T1;
  3996. ExprValueKind VK = VK_RValue;
  3997. if (cv3T3->isLValueReferenceType())
  3998. VK = VK_LValue;
  3999. else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
  4000. VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
  4001. cv3T3 = cv3T3.getNonLValueExprType(S.Context);
  4002. // Add the user-defined conversion step.
  4003. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4004. Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
  4005. HadMultipleCandidates);
  4006. // Determine whether we'll need to perform derived-to-base adjustments or
  4007. // other conversions.
  4008. bool NewDerivedToBase = false;
  4009. bool NewObjCConversion = false;
  4010. bool NewObjCLifetimeConversion = false;
  4011. Sema::ReferenceCompareResult NewRefRelationship
  4012. = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
  4013. NewDerivedToBase, NewObjCConversion,
  4014. NewObjCLifetimeConversion);
  4015. // Add the final conversion sequence, if necessary.
  4016. if (NewRefRelationship == Sema::Ref_Incompatible) {
  4017. assert(!isa<CXXConstructorDecl>(Function) &&
  4018. "should not have conversion after constructor");
  4019. ImplicitConversionSequence ICS;
  4020. ICS.setStandard();
  4021. ICS.Standard = Best->FinalConversion;
  4022. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
  4023. // Every implicit conversion results in a prvalue, except for a glvalue
  4024. // derived-to-base conversion, which we handle below.
  4025. cv3T3 = ICS.Standard.getToType(2);
  4026. VK = VK_RValue;
  4027. }
  4028. // If the converted initializer is a prvalue, its type T4 is adjusted to
  4029. // type "cv1 T4" and the temporary materialization conversion is applied.
  4030. //
  4031. // We adjust the cv-qualifications to match the reference regardless of
  4032. // whether we have a prvalue so that the AST records the change. In this
  4033. // case, T4 is "cv3 T3".
  4034. QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
  4035. if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
  4036. Sequence.AddQualificationConversionStep(cv1T4, VK);
  4037. Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
  4038. VK = IsLValueRef ? VK_LValue : VK_XValue;
  4039. if (NewDerivedToBase)
  4040. Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
  4041. else if (NewObjCConversion)
  4042. Sequence.AddObjCObjectConversionStep(cv1T1);
  4043. return OR_Success;
  4044. }
  4045. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  4046. const InitializedEntity &Entity,
  4047. Expr *CurInitExpr);
  4048. /// Attempt reference initialization (C++0x [dcl.init.ref])
  4049. static void TryReferenceInitialization(Sema &S,
  4050. const InitializedEntity &Entity,
  4051. const InitializationKind &Kind,
  4052. Expr *Initializer,
  4053. InitializationSequence &Sequence) {
  4054. QualType DestType = Entity.getType();
  4055. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  4056. Qualifiers T1Quals;
  4057. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  4058. QualType cv2T2 = Initializer->getType();
  4059. Qualifiers T2Quals;
  4060. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  4061. // If the initializer is the address of an overloaded function, try
  4062. // to resolve the overloaded function. If all goes well, T2 is the
  4063. // type of the resulting function.
  4064. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  4065. T1, Sequence))
  4066. return;
  4067. // Delegate everything else to a subfunction.
  4068. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  4069. T1Quals, cv2T2, T2, T2Quals, Sequence);
  4070. }
  4071. /// Determine whether an expression is a non-referenceable glvalue (one to
  4072. /// which a reference can never bind). Attempting to bind a reference to
  4073. /// such a glvalue will always create a temporary.
  4074. static bool isNonReferenceableGLValue(Expr *E) {
  4075. return E->refersToBitField() || E->refersToVectorElement();
  4076. }
  4077. /// Reference initialization without resolving overloaded functions.
  4078. static void TryReferenceInitializationCore(Sema &S,
  4079. const InitializedEntity &Entity,
  4080. const InitializationKind &Kind,
  4081. Expr *Initializer,
  4082. QualType cv1T1, QualType T1,
  4083. Qualifiers T1Quals,
  4084. QualType cv2T2, QualType T2,
  4085. Qualifiers T2Quals,
  4086. InitializationSequence &Sequence) {
  4087. QualType DestType = Entity.getType();
  4088. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4089. // Compute some basic properties of the types and the initializer.
  4090. bool isLValueRef = DestType->isLValueReferenceType();
  4091. bool isRValueRef = !isLValueRef;
  4092. bool DerivedToBase = false;
  4093. bool ObjCConversion = false;
  4094. bool ObjCLifetimeConversion = false;
  4095. Expr::Classification InitCategory = Initializer->Classify(S.Context);
  4096. Sema::ReferenceCompareResult RefRelationship
  4097. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
  4098. ObjCConversion, ObjCLifetimeConversion);
  4099. // C++0x [dcl.init.ref]p5:
  4100. // A reference to type "cv1 T1" is initialized by an expression of type
  4101. // "cv2 T2" as follows:
  4102. //
  4103. // - If the reference is an lvalue reference and the initializer
  4104. // expression
  4105. // Note the analogous bullet points for rvalue refs to functions. Because
  4106. // there are no function rvalues in C++, rvalue refs to functions are treated
  4107. // like lvalue refs.
  4108. OverloadingResult ConvOvlResult = OR_Success;
  4109. bool T1Function = T1->isFunctionType();
  4110. if (isLValueRef || T1Function) {
  4111. if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
  4112. (RefRelationship == Sema::Ref_Compatible ||
  4113. (Kind.isCStyleOrFunctionalCast() &&
  4114. RefRelationship == Sema::Ref_Related))) {
  4115. // - is an lvalue (but is not a bit-field), and "cv1 T1" is
  4116. // reference-compatible with "cv2 T2," or
  4117. if (T1Quals != T2Quals)
  4118. // Convert to cv1 T2. This should only add qualifiers unless this is a
  4119. // c-style cast. The removal of qualifiers in that case notionally
  4120. // happens after the reference binding, but that doesn't matter.
  4121. Sequence.AddQualificationConversionStep(
  4122. S.Context.getQualifiedType(T2, T1Quals),
  4123. Initializer->getValueKind());
  4124. if (DerivedToBase)
  4125. Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
  4126. else if (ObjCConversion)
  4127. Sequence.AddObjCObjectConversionStep(cv1T1);
  4128. // We only create a temporary here when binding a reference to a
  4129. // bit-field or vector element. Those cases are't supposed to be
  4130. // handled by this bullet, but the outcome is the same either way.
  4131. Sequence.AddReferenceBindingStep(cv1T1, false);
  4132. return;
  4133. }
  4134. // - has a class type (i.e., T2 is a class type), where T1 is not
  4135. // reference-related to T2, and can be implicitly converted to an
  4136. // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
  4137. // with "cv3 T3" (this conversion is selected by enumerating the
  4138. // applicable conversion functions (13.3.1.6) and choosing the best
  4139. // one through overload resolution (13.3)),
  4140. // If we have an rvalue ref to function type here, the rhs must be
  4141. // an rvalue. DR1287 removed the "implicitly" here.
  4142. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
  4143. (isLValueRef || InitCategory.isRValue())) {
  4144. ConvOvlResult = TryRefInitWithConversionFunction(
  4145. S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
  4146. /*IsLValueRef*/ isLValueRef, Sequence);
  4147. if (ConvOvlResult == OR_Success)
  4148. return;
  4149. if (ConvOvlResult != OR_No_Viable_Function)
  4150. Sequence.SetOverloadFailure(
  4151. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4152. ConvOvlResult);
  4153. }
  4154. }
  4155. // - Otherwise, the reference shall be an lvalue reference to a
  4156. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4157. // shall be an rvalue reference.
  4158. // For address spaces, we interpret this to mean that an addr space
  4159. // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
  4160. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
  4161. T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
  4162. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4163. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4164. else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4165. Sequence.SetOverloadFailure(
  4166. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4167. ConvOvlResult);
  4168. else if (!InitCategory.isLValue())
  4169. Sequence.SetFailed(
  4170. T1Quals.isAddressSpaceSupersetOf(T2Quals)
  4171. ? InitializationSequence::
  4172. FK_NonConstLValueReferenceBindingToTemporary
  4173. : InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4174. else {
  4175. InitializationSequence::FailureKind FK;
  4176. switch (RefRelationship) {
  4177. case Sema::Ref_Compatible:
  4178. if (Initializer->refersToBitField())
  4179. FK = InitializationSequence::
  4180. FK_NonConstLValueReferenceBindingToBitfield;
  4181. else if (Initializer->refersToVectorElement())
  4182. FK = InitializationSequence::
  4183. FK_NonConstLValueReferenceBindingToVectorElement;
  4184. else
  4185. llvm_unreachable("unexpected kind of compatible initializer");
  4186. break;
  4187. case Sema::Ref_Related:
  4188. FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
  4189. break;
  4190. case Sema::Ref_Incompatible:
  4191. FK = InitializationSequence::
  4192. FK_NonConstLValueReferenceBindingToUnrelated;
  4193. break;
  4194. }
  4195. Sequence.SetFailed(FK);
  4196. }
  4197. return;
  4198. }
  4199. // - If the initializer expression
  4200. // - is an
  4201. // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
  4202. // [1z] rvalue (but not a bit-field) or
  4203. // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
  4204. //
  4205. // Note: functions are handled above and below rather than here...
  4206. if (!T1Function &&
  4207. (RefRelationship == Sema::Ref_Compatible ||
  4208. (Kind.isCStyleOrFunctionalCast() &&
  4209. RefRelationship == Sema::Ref_Related)) &&
  4210. ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
  4211. (InitCategory.isPRValue() &&
  4212. (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
  4213. T2->isArrayType())))) {
  4214. ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
  4215. if (InitCategory.isPRValue() && T2->isRecordType()) {
  4216. // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
  4217. // compiler the freedom to perform a copy here or bind to the
  4218. // object, while C++0x requires that we bind directly to the
  4219. // object. Hence, we always bind to the object without making an
  4220. // extra copy. However, in C++03 requires that we check for the
  4221. // presence of a suitable copy constructor:
  4222. //
  4223. // The constructor that would be used to make the copy shall
  4224. // be callable whether or not the copy is actually done.
  4225. if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
  4226. Sequence.AddExtraneousCopyToTemporary(cv2T2);
  4227. else if (S.getLangOpts().CPlusPlus11)
  4228. CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
  4229. }
  4230. // C++1z [dcl.init.ref]/5.2.1.2:
  4231. // If the converted initializer is a prvalue, its type T4 is adjusted
  4232. // to type "cv1 T4" and the temporary materialization conversion is
  4233. // applied.
  4234. // Postpone address space conversions to after the temporary materialization
  4235. // conversion to allow creating temporaries in the alloca address space.
  4236. auto T1QualsIgnoreAS = T1Quals;
  4237. auto T2QualsIgnoreAS = T2Quals;
  4238. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4239. T1QualsIgnoreAS.removeAddressSpace();
  4240. T2QualsIgnoreAS.removeAddressSpace();
  4241. }
  4242. QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
  4243. if (T1QualsIgnoreAS != T2QualsIgnoreAS)
  4244. Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
  4245. Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
  4246. ValueKind = isLValueRef ? VK_LValue : VK_XValue;
  4247. // Add addr space conversion if required.
  4248. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4249. auto T4Quals = cv1T4.getQualifiers();
  4250. T4Quals.addAddressSpace(T1Quals.getAddressSpace());
  4251. QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
  4252. Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
  4253. }
  4254. // In any case, the reference is bound to the resulting glvalue (or to
  4255. // an appropriate base class subobject).
  4256. if (DerivedToBase)
  4257. Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
  4258. else if (ObjCConversion)
  4259. Sequence.AddObjCObjectConversionStep(cv1T1);
  4260. return;
  4261. }
  4262. // - has a class type (i.e., T2 is a class type), where T1 is not
  4263. // reference-related to T2, and can be implicitly converted to an
  4264. // xvalue, class prvalue, or function lvalue of type "cv3 T3",
  4265. // where "cv1 T1" is reference-compatible with "cv3 T3",
  4266. //
  4267. // DR1287 removes the "implicitly" here.
  4268. if (T2->isRecordType()) {
  4269. if (RefRelationship == Sema::Ref_Incompatible) {
  4270. ConvOvlResult = TryRefInitWithConversionFunction(
  4271. S, Entity, Kind, Initializer, /*AllowRValues*/ true,
  4272. /*IsLValueRef*/ isLValueRef, Sequence);
  4273. if (ConvOvlResult)
  4274. Sequence.SetOverloadFailure(
  4275. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4276. ConvOvlResult);
  4277. return;
  4278. }
  4279. if (RefRelationship == Sema::Ref_Compatible &&
  4280. isRValueRef && InitCategory.isLValue()) {
  4281. Sequence.SetFailed(
  4282. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4283. return;
  4284. }
  4285. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4286. return;
  4287. }
  4288. // - Otherwise, a temporary of type "cv1 T1" is created and initialized
  4289. // from the initializer expression using the rules for a non-reference
  4290. // copy-initialization (8.5). The reference is then bound to the
  4291. // temporary. [...]
  4292. // Ignore address space of reference type at this point and perform address
  4293. // space conversion after the reference binding step.
  4294. QualType cv1T1IgnoreAS =
  4295. T1Quals.hasAddressSpace()
  4296. ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
  4297. : cv1T1;
  4298. InitializedEntity TempEntity =
  4299. InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
  4300. // FIXME: Why do we use an implicit conversion here rather than trying
  4301. // copy-initialization?
  4302. ImplicitConversionSequence ICS
  4303. = S.TryImplicitConversion(Initializer, TempEntity.getType(),
  4304. /*SuppressUserConversions=*/false,
  4305. /*AllowExplicit=*/false,
  4306. /*FIXME:InOverloadResolution=*/false,
  4307. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  4308. /*AllowObjCWritebackConversion=*/false);
  4309. if (ICS.isBad()) {
  4310. // FIXME: Use the conversion function set stored in ICS to turn
  4311. // this into an overloading ambiguity diagnostic. However, we need
  4312. // to keep that set as an OverloadCandidateSet rather than as some
  4313. // other kind of set.
  4314. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4315. Sequence.SetOverloadFailure(
  4316. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4317. ConvOvlResult);
  4318. else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4319. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4320. else
  4321. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
  4322. return;
  4323. } else {
  4324. Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
  4325. }
  4326. // [...] If T1 is reference-related to T2, cv1 must be the
  4327. // same cv-qualification as, or greater cv-qualification
  4328. // than, cv2; otherwise, the program is ill-formed.
  4329. unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
  4330. unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
  4331. if ((RefRelationship == Sema::Ref_Related &&
  4332. (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
  4333. !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
  4334. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4335. return;
  4336. }
  4337. // [...] If T1 is reference-related to T2 and the reference is an rvalue
  4338. // reference, the initializer expression shall not be an lvalue.
  4339. if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
  4340. InitCategory.isLValue()) {
  4341. Sequence.SetFailed(
  4342. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4343. return;
  4344. }
  4345. Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
  4346. if (T1Quals.hasAddressSpace()) {
  4347. if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
  4348. LangAS::Default)) {
  4349. Sequence.SetFailed(
  4350. InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
  4351. return;
  4352. }
  4353. Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
  4354. : VK_XValue);
  4355. }
  4356. }
  4357. /// Attempt character array initialization from a string literal
  4358. /// (C++ [dcl.init.string], C99 6.7.8).
  4359. static void TryStringLiteralInitialization(Sema &S,
  4360. const InitializedEntity &Entity,
  4361. const InitializationKind &Kind,
  4362. Expr *Initializer,
  4363. InitializationSequence &Sequence) {
  4364. Sequence.AddStringInitStep(Entity.getType());
  4365. }
  4366. /// Attempt value initialization (C++ [dcl.init]p7).
  4367. static void TryValueInitialization(Sema &S,
  4368. const InitializedEntity &Entity,
  4369. const InitializationKind &Kind,
  4370. InitializationSequence &Sequence,
  4371. InitListExpr *InitList) {
  4372. assert((!InitList || InitList->getNumInits() == 0) &&
  4373. "Shouldn't use value-init for non-empty init lists");
  4374. // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
  4375. //
  4376. // To value-initialize an object of type T means:
  4377. QualType T = Entity.getType();
  4378. // -- if T is an array type, then each element is value-initialized;
  4379. T = S.Context.getBaseElementType(T);
  4380. if (const RecordType *RT = T->getAs<RecordType>()) {
  4381. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  4382. bool NeedZeroInitialization = true;
  4383. // C++98:
  4384. // -- if T is a class type (clause 9) with a user-declared constructor
  4385. // (12.1), then the default constructor for T is called (and the
  4386. // initialization is ill-formed if T has no accessible default
  4387. // constructor);
  4388. // C++11:
  4389. // -- if T is a class type (clause 9) with either no default constructor
  4390. // (12.1 [class.ctor]) or a default constructor that is user-provided
  4391. // or deleted, then the object is default-initialized;
  4392. //
  4393. // Note that the C++11 rule is the same as the C++98 rule if there are no
  4394. // defaulted or deleted constructors, so we just use it unconditionally.
  4395. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
  4396. if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
  4397. NeedZeroInitialization = false;
  4398. // -- if T is a (possibly cv-qualified) non-union class type without a
  4399. // user-provided or deleted default constructor, then the object is
  4400. // zero-initialized and, if T has a non-trivial default constructor,
  4401. // default-initialized;
  4402. // The 'non-union' here was removed by DR1502. The 'non-trivial default
  4403. // constructor' part was removed by DR1507.
  4404. if (NeedZeroInitialization)
  4405. Sequence.AddZeroInitializationStep(Entity.getType());
  4406. // C++03:
  4407. // -- if T is a non-union class type without a user-declared constructor,
  4408. // then every non-static data member and base class component of T is
  4409. // value-initialized;
  4410. // [...] A program that calls for [...] value-initialization of an
  4411. // entity of reference type is ill-formed.
  4412. //
  4413. // C++11 doesn't need this handling, because value-initialization does not
  4414. // occur recursively there, and the implicit default constructor is
  4415. // defined as deleted in the problematic cases.
  4416. if (!S.getLangOpts().CPlusPlus11 &&
  4417. ClassDecl->hasUninitializedReferenceMember()) {
  4418. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
  4419. return;
  4420. }
  4421. // If this is list-value-initialization, pass the empty init list on when
  4422. // building the constructor call. This affects the semantics of a few
  4423. // things (such as whether an explicit default constructor can be called).
  4424. Expr *InitListAsExpr = InitList;
  4425. MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
  4426. bool InitListSyntax = InitList;
  4427. // FIXME: Instead of creating a CXXConstructExpr of array type here,
  4428. // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
  4429. return TryConstructorInitialization(
  4430. S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
  4431. }
  4432. }
  4433. Sequence.AddZeroInitializationStep(Entity.getType());
  4434. }
  4435. /// Attempt default initialization (C++ [dcl.init]p6).
  4436. static void TryDefaultInitialization(Sema &S,
  4437. const InitializedEntity &Entity,
  4438. const InitializationKind &Kind,
  4439. InitializationSequence &Sequence) {
  4440. assert(Kind.getKind() == InitializationKind::IK_Default);
  4441. // C++ [dcl.init]p6:
  4442. // To default-initialize an object of type T means:
  4443. // - if T is an array type, each element is default-initialized;
  4444. QualType DestType = S.Context.getBaseElementType(Entity.getType());
  4445. // - if T is a (possibly cv-qualified) class type (Clause 9), the default
  4446. // constructor for T is called (and the initialization is ill-formed if
  4447. // T has no accessible default constructor);
  4448. if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
  4449. TryConstructorInitialization(S, Entity, Kind, None, DestType,
  4450. Entity.getType(), Sequence);
  4451. return;
  4452. }
  4453. // - otherwise, no initialization is performed.
  4454. // If a program calls for the default initialization of an object of
  4455. // a const-qualified type T, T shall be a class type with a user-provided
  4456. // default constructor.
  4457. if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
  4458. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  4459. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  4460. return;
  4461. }
  4462. // If the destination type has a lifetime property, zero-initialize it.
  4463. if (DestType.getQualifiers().hasObjCLifetime()) {
  4464. Sequence.AddZeroInitializationStep(Entity.getType());
  4465. return;
  4466. }
  4467. }
  4468. /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
  4469. /// which enumerates all conversion functions and performs overload resolution
  4470. /// to select the best.
  4471. static void TryUserDefinedConversion(Sema &S,
  4472. QualType DestType,
  4473. const InitializationKind &Kind,
  4474. Expr *Initializer,
  4475. InitializationSequence &Sequence,
  4476. bool TopLevelOfInitList) {
  4477. assert(!DestType->isReferenceType() && "References are handled elsewhere");
  4478. QualType SourceType = Initializer->getType();
  4479. assert((DestType->isRecordType() || SourceType->isRecordType()) &&
  4480. "Must have a class type to perform a user-defined conversion");
  4481. // Build the candidate set directly in the initialization sequence
  4482. // structure, so that it will persist if we fail.
  4483. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  4484. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4485. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  4486. // Determine whether we are allowed to call explicit constructors or
  4487. // explicit conversion operators.
  4488. bool AllowExplicit = Kind.AllowExplicit();
  4489. if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
  4490. // The type we're converting to is a class type. Enumerate its constructors
  4491. // to see if there is a suitable conversion.
  4492. CXXRecordDecl *DestRecordDecl
  4493. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  4494. // Try to complete the type we're converting to.
  4495. if (S.isCompleteType(Kind.getLocation(), DestType)) {
  4496. for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
  4497. auto Info = getConstructorInfo(D);
  4498. if (!Info.Constructor)
  4499. continue;
  4500. if (!Info.Constructor->isInvalidDecl() &&
  4501. Info.Constructor->isConvertingConstructor(AllowExplicit)) {
  4502. if (Info.ConstructorTmpl)
  4503. S.AddTemplateOverloadCandidate(
  4504. Info.ConstructorTmpl, Info.FoundDecl,
  4505. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  4506. /*SuppressUserConversions=*/true,
  4507. /*PartialOverloading*/ false, AllowExplicit);
  4508. else
  4509. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  4510. Initializer, CandidateSet,
  4511. /*SuppressUserConversions=*/true,
  4512. /*PartialOverloading*/ false, AllowExplicit);
  4513. }
  4514. }
  4515. }
  4516. }
  4517. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4518. if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
  4519. // The type we're converting from is a class type, enumerate its conversion
  4520. // functions.
  4521. // We can only enumerate the conversion functions for a complete type; if
  4522. // the type isn't complete, simply skip this step.
  4523. if (S.isCompleteType(DeclLoc, SourceType)) {
  4524. CXXRecordDecl *SourceRecordDecl
  4525. = cast<CXXRecordDecl>(SourceRecordType->getDecl());
  4526. const auto &Conversions =
  4527. SourceRecordDecl->getVisibleConversionFunctions();
  4528. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4529. NamedDecl *D = *I;
  4530. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4531. if (isa<UsingShadowDecl>(D))
  4532. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4533. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4534. CXXConversionDecl *Conv;
  4535. if (ConvTemplate)
  4536. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4537. else
  4538. Conv = cast<CXXConversionDecl>(D);
  4539. if (AllowExplicit || !Conv->isExplicit()) {
  4540. if (ConvTemplate)
  4541. S.AddTemplateConversionCandidate(
  4542. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  4543. CandidateSet, AllowExplicit, AllowExplicit);
  4544. else
  4545. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  4546. DestType, CandidateSet, AllowExplicit,
  4547. AllowExplicit);
  4548. }
  4549. }
  4550. }
  4551. }
  4552. // Perform overload resolution. If it fails, return the failed result.
  4553. OverloadCandidateSet::iterator Best;
  4554. if (OverloadingResult Result
  4555. = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4556. Sequence.SetOverloadFailure(
  4557. InitializationSequence::FK_UserConversionOverloadFailed,
  4558. Result);
  4559. return;
  4560. }
  4561. FunctionDecl *Function = Best->Function;
  4562. Function->setReferenced();
  4563. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4564. if (isa<CXXConstructorDecl>(Function)) {
  4565. // Add the user-defined conversion step. Any cv-qualification conversion is
  4566. // subsumed by the initialization. Per DR5, the created temporary is of the
  4567. // cv-unqualified type of the destination.
  4568. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  4569. DestType.getUnqualifiedType(),
  4570. HadMultipleCandidates);
  4571. // C++14 and before:
  4572. // - if the function is a constructor, the call initializes a temporary
  4573. // of the cv-unqualified version of the destination type. The [...]
  4574. // temporary [...] is then used to direct-initialize, according to the
  4575. // rules above, the object that is the destination of the
  4576. // copy-initialization.
  4577. // Note that this just performs a simple object copy from the temporary.
  4578. //
  4579. // C++17:
  4580. // - if the function is a constructor, the call is a prvalue of the
  4581. // cv-unqualified version of the destination type whose return object
  4582. // is initialized by the constructor. The call is used to
  4583. // direct-initialize, according to the rules above, the object that
  4584. // is the destination of the copy-initialization.
  4585. // Therefore we need to do nothing further.
  4586. //
  4587. // FIXME: Mark this copy as extraneous.
  4588. if (!S.getLangOpts().CPlusPlus17)
  4589. Sequence.AddFinalCopy(DestType);
  4590. else if (DestType.hasQualifiers())
  4591. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  4592. return;
  4593. }
  4594. // Add the user-defined conversion step that calls the conversion function.
  4595. QualType ConvType = Function->getCallResultType();
  4596. Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
  4597. HadMultipleCandidates);
  4598. if (ConvType->getAs<RecordType>()) {
  4599. // The call is used to direct-initialize [...] the object that is the
  4600. // destination of the copy-initialization.
  4601. //
  4602. // In C++17, this does not call a constructor if we enter /17.6.1:
  4603. // - If the initializer expression is a prvalue and the cv-unqualified
  4604. // version of the source type is the same as the class of the
  4605. // destination [... do not make an extra copy]
  4606. //
  4607. // FIXME: Mark this copy as extraneous.
  4608. if (!S.getLangOpts().CPlusPlus17 ||
  4609. Function->getReturnType()->isReferenceType() ||
  4610. !S.Context.hasSameUnqualifiedType(ConvType, DestType))
  4611. Sequence.AddFinalCopy(DestType);
  4612. else if (!S.Context.hasSameType(ConvType, DestType))
  4613. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  4614. return;
  4615. }
  4616. // If the conversion following the call to the conversion function
  4617. // is interesting, add it as a separate step.
  4618. if (Best->FinalConversion.First || Best->FinalConversion.Second ||
  4619. Best->FinalConversion.Third) {
  4620. ImplicitConversionSequence ICS;
  4621. ICS.setStandard();
  4622. ICS.Standard = Best->FinalConversion;
  4623. Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  4624. }
  4625. }
  4626. /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
  4627. /// a function with a pointer return type contains a 'return false;' statement.
  4628. /// In C++11, 'false' is not a null pointer, so this breaks the build of any
  4629. /// code using that header.
  4630. ///
  4631. /// Work around this by treating 'return false;' as zero-initializing the result
  4632. /// if it's used in a pointer-returning function in a system header.
  4633. static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
  4634. const InitializedEntity &Entity,
  4635. const Expr *Init) {
  4636. return S.getLangOpts().CPlusPlus11 &&
  4637. Entity.getKind() == InitializedEntity::EK_Result &&
  4638. Entity.getType()->isPointerType() &&
  4639. isa<CXXBoolLiteralExpr>(Init) &&
  4640. !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
  4641. S.getSourceManager().isInSystemHeader(Init->getExprLoc());
  4642. }
  4643. /// The non-zero enum values here are indexes into diagnostic alternatives.
  4644. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
  4645. /// Determines whether this expression is an acceptable ICR source.
  4646. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
  4647. bool isAddressOf, bool &isWeakAccess) {
  4648. // Skip parens.
  4649. e = e->IgnoreParens();
  4650. // Skip address-of nodes.
  4651. if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  4652. if (op->getOpcode() == UO_AddrOf)
  4653. return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
  4654. isWeakAccess);
  4655. // Skip certain casts.
  4656. } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
  4657. switch (ce->getCastKind()) {
  4658. case CK_Dependent:
  4659. case CK_BitCast:
  4660. case CK_LValueBitCast:
  4661. case CK_NoOp:
  4662. return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
  4663. case CK_ArrayToPointerDecay:
  4664. return IIK_nonscalar;
  4665. case CK_NullToPointer:
  4666. return IIK_okay;
  4667. default:
  4668. break;
  4669. }
  4670. // If we have a declaration reference, it had better be a local variable.
  4671. } else if (isa<DeclRefExpr>(e)) {
  4672. // set isWeakAccess to true, to mean that there will be an implicit
  4673. // load which requires a cleanup.
  4674. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  4675. isWeakAccess = true;
  4676. if (!isAddressOf) return IIK_nonlocal;
  4677. VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
  4678. if (!var) return IIK_nonlocal;
  4679. return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
  4680. // If we have a conditional operator, check both sides.
  4681. } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
  4682. if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
  4683. isWeakAccess))
  4684. return iik;
  4685. return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
  4686. // These are never scalar.
  4687. } else if (isa<ArraySubscriptExpr>(e)) {
  4688. return IIK_nonscalar;
  4689. // Otherwise, it needs to be a null pointer constant.
  4690. } else {
  4691. return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
  4692. ? IIK_okay : IIK_nonlocal);
  4693. }
  4694. return IIK_nonlocal;
  4695. }
  4696. /// Check whether the given expression is a valid operand for an
  4697. /// indirect copy/restore.
  4698. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
  4699. assert(src->isRValue());
  4700. bool isWeakAccess = false;
  4701. InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
  4702. // If isWeakAccess to true, there will be an implicit
  4703. // load which requires a cleanup.
  4704. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
  4705. S.Cleanup.setExprNeedsCleanups(true);
  4706. if (iik == IIK_okay) return;
  4707. S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
  4708. << ((unsigned) iik - 1) // shift index into diagnostic explanations
  4709. << src->getSourceRange();
  4710. }
  4711. /// Determine whether we have compatible array types for the
  4712. /// purposes of GNU by-copy array initialization.
  4713. static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
  4714. const ArrayType *Source) {
  4715. // If the source and destination array types are equivalent, we're
  4716. // done.
  4717. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
  4718. return true;
  4719. // Make sure that the element types are the same.
  4720. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
  4721. return false;
  4722. // The only mismatch we allow is when the destination is an
  4723. // incomplete array type and the source is a constant array type.
  4724. return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
  4725. }
  4726. static bool tryObjCWritebackConversion(Sema &S,
  4727. InitializationSequence &Sequence,
  4728. const InitializedEntity &Entity,
  4729. Expr *Initializer) {
  4730. bool ArrayDecay = false;
  4731. QualType ArgType = Initializer->getType();
  4732. QualType ArgPointee;
  4733. if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
  4734. ArrayDecay = true;
  4735. ArgPointee = ArgArrayType->getElementType();
  4736. ArgType = S.Context.getPointerType(ArgPointee);
  4737. }
  4738. // Handle write-back conversion.
  4739. QualType ConvertedArgType;
  4740. if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
  4741. ConvertedArgType))
  4742. return false;
  4743. // We should copy unless we're passing to an argument explicitly
  4744. // marked 'out'.
  4745. bool ShouldCopy = true;
  4746. if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  4747. ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  4748. // Do we need an lvalue conversion?
  4749. if (ArrayDecay || Initializer->isGLValue()) {
  4750. ImplicitConversionSequence ICS;
  4751. ICS.setStandard();
  4752. ICS.Standard.setAsIdentityConversion();
  4753. QualType ResultType;
  4754. if (ArrayDecay) {
  4755. ICS.Standard.First = ICK_Array_To_Pointer;
  4756. ResultType = S.Context.getPointerType(ArgPointee);
  4757. } else {
  4758. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  4759. ResultType = Initializer->getType().getNonLValueExprType(S.Context);
  4760. }
  4761. Sequence.AddConversionSequenceStep(ICS, ResultType);
  4762. }
  4763. Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  4764. return true;
  4765. }
  4766. static bool TryOCLSamplerInitialization(Sema &S,
  4767. InitializationSequence &Sequence,
  4768. QualType DestType,
  4769. Expr *Initializer) {
  4770. if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
  4771. (!Initializer->isIntegerConstantExpr(S.Context) &&
  4772. !Initializer->getType()->isSamplerT()))
  4773. return false;
  4774. Sequence.AddOCLSamplerInitStep(DestType);
  4775. return true;
  4776. }
  4777. static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
  4778. return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
  4779. (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
  4780. }
  4781. static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
  4782. InitializationSequence &Sequence,
  4783. QualType DestType,
  4784. Expr *Initializer) {
  4785. if (!S.getLangOpts().OpenCL)
  4786. return false;
  4787. //
  4788. // OpenCL 1.2 spec, s6.12.10
  4789. //
  4790. // The event argument can also be used to associate the
  4791. // async_work_group_copy with a previous async copy allowing
  4792. // an event to be shared by multiple async copies; otherwise
  4793. // event should be zero.
  4794. //
  4795. if (DestType->isEventT() || DestType->isQueueT()) {
  4796. if (!IsZeroInitializer(Initializer, S))
  4797. return false;
  4798. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  4799. return true;
  4800. }
  4801. // We should allow zero initialization for all types defined in the
  4802. // cl_intel_device_side_avc_motion_estimation extension, except
  4803. // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
  4804. if (S.getOpenCLOptions().isEnabled(
  4805. "cl_intel_device_side_avc_motion_estimation") &&
  4806. DestType->isOCLIntelSubgroupAVCType()) {
  4807. if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
  4808. DestType->isOCLIntelSubgroupAVCMceResultType())
  4809. return false;
  4810. if (!IsZeroInitializer(Initializer, S))
  4811. return false;
  4812. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  4813. return true;
  4814. }
  4815. return false;
  4816. }
  4817. InitializationSequence::InitializationSequence(Sema &S,
  4818. const InitializedEntity &Entity,
  4819. const InitializationKind &Kind,
  4820. MultiExprArg Args,
  4821. bool TopLevelOfInitList,
  4822. bool TreatUnavailableAsInvalid)
  4823. : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
  4824. InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
  4825. TreatUnavailableAsInvalid);
  4826. }
  4827. /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
  4828. /// address of that function, this returns true. Otherwise, it returns false.
  4829. static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
  4830. auto *DRE = dyn_cast<DeclRefExpr>(E);
  4831. if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
  4832. return false;
  4833. return !S.checkAddressOfFunctionIsAvailable(
  4834. cast<FunctionDecl>(DRE->getDecl()));
  4835. }
  4836. /// Determine whether we can perform an elementwise array copy for this kind
  4837. /// of entity.
  4838. static bool canPerformArrayCopy(const InitializedEntity &Entity) {
  4839. switch (Entity.getKind()) {
  4840. case InitializedEntity::EK_LambdaCapture:
  4841. // C++ [expr.prim.lambda]p24:
  4842. // For array members, the array elements are direct-initialized in
  4843. // increasing subscript order.
  4844. return true;
  4845. case InitializedEntity::EK_Variable:
  4846. // C++ [dcl.decomp]p1:
  4847. // [...] each element is copy-initialized or direct-initialized from the
  4848. // corresponding element of the assignment-expression [...]
  4849. return isa<DecompositionDecl>(Entity.getDecl());
  4850. case InitializedEntity::EK_Member:
  4851. // C++ [class.copy.ctor]p14:
  4852. // - if the member is an array, each element is direct-initialized with
  4853. // the corresponding subobject of x
  4854. return Entity.isImplicitMemberInitializer();
  4855. case InitializedEntity::EK_ArrayElement:
  4856. // All the above cases are intended to apply recursively, even though none
  4857. // of them actually say that.
  4858. if (auto *E = Entity.getParent())
  4859. return canPerformArrayCopy(*E);
  4860. break;
  4861. default:
  4862. break;
  4863. }
  4864. return false;
  4865. }
  4866. void InitializationSequence::InitializeFrom(Sema &S,
  4867. const InitializedEntity &Entity,
  4868. const InitializationKind &Kind,
  4869. MultiExprArg Args,
  4870. bool TopLevelOfInitList,
  4871. bool TreatUnavailableAsInvalid) {
  4872. ASTContext &Context = S.Context;
  4873. // Eliminate non-overload placeholder types in the arguments. We
  4874. // need to do this before checking whether types are dependent
  4875. // because lowering a pseudo-object expression might well give us
  4876. // something of dependent type.
  4877. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  4878. if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
  4879. // FIXME: should we be doing this here?
  4880. ExprResult result = S.CheckPlaceholderExpr(Args[I]);
  4881. if (result.isInvalid()) {
  4882. SetFailed(FK_PlaceholderType);
  4883. return;
  4884. }
  4885. Args[I] = result.get();
  4886. }
  4887. // C++0x [dcl.init]p16:
  4888. // The semantics of initializers are as follows. The destination type is
  4889. // the type of the object or reference being initialized and the source
  4890. // type is the type of the initializer expression. The source type is not
  4891. // defined when the initializer is a braced-init-list or when it is a
  4892. // parenthesized list of expressions.
  4893. QualType DestType = Entity.getType();
  4894. if (DestType->isDependentType() ||
  4895. Expr::hasAnyTypeDependentArguments(Args)) {
  4896. SequenceKind = DependentSequence;
  4897. return;
  4898. }
  4899. // Almost everything is a normal sequence.
  4900. setSequenceKind(NormalSequence);
  4901. QualType SourceType;
  4902. Expr *Initializer = nullptr;
  4903. if (Args.size() == 1) {
  4904. Initializer = Args[0];
  4905. if (S.getLangOpts().ObjC) {
  4906. if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
  4907. DestType, Initializer->getType(),
  4908. Initializer) ||
  4909. S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
  4910. Args[0] = Initializer;
  4911. }
  4912. if (!isa<InitListExpr>(Initializer))
  4913. SourceType = Initializer->getType();
  4914. }
  4915. // - If the initializer is a (non-parenthesized) braced-init-list, the
  4916. // object is list-initialized (8.5.4).
  4917. if (Kind.getKind() != InitializationKind::IK_Direct) {
  4918. if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
  4919. TryListInitialization(S, Entity, Kind, InitList, *this,
  4920. TreatUnavailableAsInvalid);
  4921. return;
  4922. }
  4923. }
  4924. // - If the destination type is a reference type, see 8.5.3.
  4925. if (DestType->isReferenceType()) {
  4926. // C++0x [dcl.init.ref]p1:
  4927. // A variable declared to be a T& or T&&, that is, "reference to type T"
  4928. // (8.3.2), shall be initialized by an object, or function, of type T or
  4929. // by an object that can be converted into a T.
  4930. // (Therefore, multiple arguments are not permitted.)
  4931. if (Args.size() != 1)
  4932. SetFailed(FK_TooManyInitsForReference);
  4933. // C++17 [dcl.init.ref]p5:
  4934. // A reference [...] is initialized by an expression [...] as follows:
  4935. // If the initializer is not an expression, presumably we should reject,
  4936. // but the standard fails to actually say so.
  4937. else if (isa<InitListExpr>(Args[0]))
  4938. SetFailed(FK_ParenthesizedListInitForReference);
  4939. else
  4940. TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
  4941. return;
  4942. }
  4943. // - If the initializer is (), the object is value-initialized.
  4944. if (Kind.getKind() == InitializationKind::IK_Value ||
  4945. (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
  4946. TryValueInitialization(S, Entity, Kind, *this);
  4947. return;
  4948. }
  4949. // Handle default initialization.
  4950. if (Kind.getKind() == InitializationKind::IK_Default) {
  4951. TryDefaultInitialization(S, Entity, Kind, *this);
  4952. return;
  4953. }
  4954. // - If the destination type is an array of characters, an array of
  4955. // char16_t, an array of char32_t, or an array of wchar_t, and the
  4956. // initializer is a string literal, see 8.5.2.
  4957. // - Otherwise, if the destination type is an array, the program is
  4958. // ill-formed.
  4959. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
  4960. if (Initializer && isa<VariableArrayType>(DestAT)) {
  4961. SetFailed(FK_VariableLengthArrayHasInitializer);
  4962. return;
  4963. }
  4964. if (Initializer) {
  4965. switch (IsStringInit(Initializer, DestAT, Context)) {
  4966. case SIF_None:
  4967. TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
  4968. return;
  4969. case SIF_NarrowStringIntoWideChar:
  4970. SetFailed(FK_NarrowStringIntoWideCharArray);
  4971. return;
  4972. case SIF_WideStringIntoChar:
  4973. SetFailed(FK_WideStringIntoCharArray);
  4974. return;
  4975. case SIF_IncompatWideStringIntoWideChar:
  4976. SetFailed(FK_IncompatWideStringIntoWideChar);
  4977. return;
  4978. case SIF_PlainStringIntoUTF8Char:
  4979. SetFailed(FK_PlainStringIntoUTF8Char);
  4980. return;
  4981. case SIF_UTF8StringIntoPlainChar:
  4982. SetFailed(FK_UTF8StringIntoPlainChar);
  4983. return;
  4984. case SIF_Other:
  4985. break;
  4986. }
  4987. }
  4988. // Some kinds of initialization permit an array to be initialized from
  4989. // another array of the same type, and perform elementwise initialization.
  4990. if (Initializer && isa<ConstantArrayType>(DestAT) &&
  4991. S.Context.hasSameUnqualifiedType(Initializer->getType(),
  4992. Entity.getType()) &&
  4993. canPerformArrayCopy(Entity)) {
  4994. // If source is a prvalue, use it directly.
  4995. if (Initializer->getValueKind() == VK_RValue) {
  4996. AddArrayInitStep(DestType, /*IsGNUExtension*/false);
  4997. return;
  4998. }
  4999. // Emit element-at-a-time copy loop.
  5000. InitializedEntity Element =
  5001. InitializedEntity::InitializeElement(S.Context, 0, Entity);
  5002. QualType InitEltT =
  5003. Context.getAsArrayType(Initializer->getType())->getElementType();
  5004. OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
  5005. Initializer->getValueKind(),
  5006. Initializer->getObjectKind());
  5007. Expr *OVEAsExpr = &OVE;
  5008. InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
  5009. TreatUnavailableAsInvalid);
  5010. if (!Failed())
  5011. AddArrayInitLoopStep(Entity.getType(), InitEltT);
  5012. return;
  5013. }
  5014. // Note: as an GNU C extension, we allow initialization of an
  5015. // array from a compound literal that creates an array of the same
  5016. // type, so long as the initializer has no side effects.
  5017. if (!S.getLangOpts().CPlusPlus && Initializer &&
  5018. isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
  5019. Initializer->getType()->isArrayType()) {
  5020. const ArrayType *SourceAT
  5021. = Context.getAsArrayType(Initializer->getType());
  5022. if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
  5023. SetFailed(FK_ArrayTypeMismatch);
  5024. else if (Initializer->HasSideEffects(S.Context))
  5025. SetFailed(FK_NonConstantArrayInit);
  5026. else {
  5027. AddArrayInitStep(DestType, /*IsGNUExtension*/true);
  5028. }
  5029. }
  5030. // Note: as a GNU C++ extension, we allow list-initialization of a
  5031. // class member of array type from a parenthesized initializer list.
  5032. else if (S.getLangOpts().CPlusPlus &&
  5033. Entity.getKind() == InitializedEntity::EK_Member &&
  5034. Initializer && isa<InitListExpr>(Initializer)) {
  5035. TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
  5036. *this, TreatUnavailableAsInvalid);
  5037. AddParenthesizedArrayInitStep(DestType);
  5038. } else if (DestAT->getElementType()->isCharType())
  5039. SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
  5040. else if (IsWideCharCompatible(DestAT->getElementType(), Context))
  5041. SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
  5042. else
  5043. SetFailed(FK_ArrayNeedsInitList);
  5044. return;
  5045. }
  5046. // Determine whether we should consider writeback conversions for
  5047. // Objective-C ARC.
  5048. bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
  5049. Entity.isParameterKind();
  5050. if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
  5051. return;
  5052. // We're at the end of the line for C: it's either a write-back conversion
  5053. // or it's a C assignment. There's no need to check anything else.
  5054. if (!S.getLangOpts().CPlusPlus) {
  5055. // If allowed, check whether this is an Objective-C writeback conversion.
  5056. if (allowObjCWritebackConversion &&
  5057. tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
  5058. return;
  5059. }
  5060. if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
  5061. return;
  5062. // Handle initialization in C
  5063. AddCAssignmentStep(DestType);
  5064. MaybeProduceObjCObject(S, *this, Entity);
  5065. return;
  5066. }
  5067. assert(S.getLangOpts().CPlusPlus);
  5068. // - If the destination type is a (possibly cv-qualified) class type:
  5069. if (DestType->isRecordType()) {
  5070. // - If the initialization is direct-initialization, or if it is
  5071. // copy-initialization where the cv-unqualified version of the
  5072. // source type is the same class as, or a derived class of, the
  5073. // class of the destination, constructors are considered. [...]
  5074. if (Kind.getKind() == InitializationKind::IK_Direct ||
  5075. (Kind.getKind() == InitializationKind::IK_Copy &&
  5076. (Context.hasSameUnqualifiedType(SourceType, DestType) ||
  5077. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
  5078. TryConstructorInitialization(S, Entity, Kind, Args,
  5079. DestType, DestType, *this);
  5080. // - Otherwise (i.e., for the remaining copy-initialization cases),
  5081. // user-defined conversion sequences that can convert from the source
  5082. // type to the destination type or (when a conversion function is
  5083. // used) to a derived class thereof are enumerated as described in
  5084. // 13.3.1.4, and the best one is chosen through overload resolution
  5085. // (13.3).
  5086. else
  5087. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5088. TopLevelOfInitList);
  5089. return;
  5090. }
  5091. assert(Args.size() >= 1 && "Zero-argument case handled above");
  5092. // The remaining cases all need a source type.
  5093. if (Args.size() > 1) {
  5094. SetFailed(FK_TooManyInitsForScalar);
  5095. return;
  5096. } else if (isa<InitListExpr>(Args[0])) {
  5097. SetFailed(FK_ParenthesizedListInitForScalar);
  5098. return;
  5099. }
  5100. // - Otherwise, if the source type is a (possibly cv-qualified) class
  5101. // type, conversion functions are considered.
  5102. if (!SourceType.isNull() && SourceType->isRecordType()) {
  5103. // For a conversion to _Atomic(T) from either T or a class type derived
  5104. // from T, initialize the T object then convert to _Atomic type.
  5105. bool NeedAtomicConversion = false;
  5106. if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
  5107. if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
  5108. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
  5109. Atomic->getValueType())) {
  5110. DestType = Atomic->getValueType();
  5111. NeedAtomicConversion = true;
  5112. }
  5113. }
  5114. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5115. TopLevelOfInitList);
  5116. MaybeProduceObjCObject(S, *this, Entity);
  5117. if (!Failed() && NeedAtomicConversion)
  5118. AddAtomicConversionStep(Entity.getType());
  5119. return;
  5120. }
  5121. // - Otherwise, the initial value of the object being initialized is the
  5122. // (possibly converted) value of the initializer expression. Standard
  5123. // conversions (Clause 4) will be used, if necessary, to convert the
  5124. // initializer expression to the cv-unqualified version of the
  5125. // destination type; no user-defined conversions are considered.
  5126. ImplicitConversionSequence ICS
  5127. = S.TryImplicitConversion(Initializer, DestType,
  5128. /*SuppressUserConversions*/true,
  5129. /*AllowExplicitConversions*/ false,
  5130. /*InOverloadResolution*/ false,
  5131. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  5132. allowObjCWritebackConversion);
  5133. if (ICS.isStandard() &&
  5134. ICS.Standard.Second == ICK_Writeback_Conversion) {
  5135. // Objective-C ARC writeback conversion.
  5136. // We should copy unless we're passing to an argument explicitly
  5137. // marked 'out'.
  5138. bool ShouldCopy = true;
  5139. if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  5140. ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  5141. // If there was an lvalue adjustment, add it as a separate conversion.
  5142. if (ICS.Standard.First == ICK_Array_To_Pointer ||
  5143. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5144. ImplicitConversionSequence LvalueICS;
  5145. LvalueICS.setStandard();
  5146. LvalueICS.Standard.setAsIdentityConversion();
  5147. LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
  5148. LvalueICS.Standard.First = ICS.Standard.First;
  5149. AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
  5150. }
  5151. AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
  5152. } else if (ICS.isBad()) {
  5153. DeclAccessPair dap;
  5154. if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
  5155. AddZeroInitializationStep(Entity.getType());
  5156. } else if (Initializer->getType() == Context.OverloadTy &&
  5157. !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
  5158. false, dap))
  5159. SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  5160. else if (Initializer->getType()->isFunctionType() &&
  5161. isExprAnUnaddressableFunction(S, Initializer))
  5162. SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
  5163. else
  5164. SetFailed(InitializationSequence::FK_ConversionFailed);
  5165. } else {
  5166. AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  5167. MaybeProduceObjCObject(S, *this, Entity);
  5168. }
  5169. }
  5170. InitializationSequence::~InitializationSequence() {
  5171. for (auto &S : Steps)
  5172. S.Destroy();
  5173. }
  5174. //===----------------------------------------------------------------------===//
  5175. // Perform initialization
  5176. //===----------------------------------------------------------------------===//
  5177. static Sema::AssignmentAction
  5178. getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
  5179. switch(Entity.getKind()) {
  5180. case InitializedEntity::EK_Variable:
  5181. case InitializedEntity::EK_New:
  5182. case InitializedEntity::EK_Exception:
  5183. case InitializedEntity::EK_Base:
  5184. case InitializedEntity::EK_Delegating:
  5185. return Sema::AA_Initializing;
  5186. case InitializedEntity::EK_Parameter:
  5187. if (Entity.getDecl() &&
  5188. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5189. return Sema::AA_Sending;
  5190. return Sema::AA_Passing;
  5191. case InitializedEntity::EK_Parameter_CF_Audited:
  5192. if (Entity.getDecl() &&
  5193. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5194. return Sema::AA_Sending;
  5195. return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
  5196. case InitializedEntity::EK_Result:
  5197. case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
  5198. return Sema::AA_Returning;
  5199. case InitializedEntity::EK_Temporary:
  5200. case InitializedEntity::EK_RelatedResult:
  5201. // FIXME: Can we tell apart casting vs. converting?
  5202. return Sema::AA_Casting;
  5203. case InitializedEntity::EK_Member:
  5204. case InitializedEntity::EK_Binding:
  5205. case InitializedEntity::EK_ArrayElement:
  5206. case InitializedEntity::EK_VectorElement:
  5207. case InitializedEntity::EK_ComplexElement:
  5208. case InitializedEntity::EK_BlockElement:
  5209. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5210. case InitializedEntity::EK_LambdaCapture:
  5211. case InitializedEntity::EK_CompoundLiteralInit:
  5212. return Sema::AA_Initializing;
  5213. }
  5214. llvm_unreachable("Invalid EntityKind!");
  5215. }
  5216. /// Whether we should bind a created object as a temporary when
  5217. /// initializing the given entity.
  5218. static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
  5219. switch (Entity.getKind()) {
  5220. case InitializedEntity::EK_ArrayElement:
  5221. case InitializedEntity::EK_Member:
  5222. case InitializedEntity::EK_Result:
  5223. case InitializedEntity::EK_StmtExprResult:
  5224. case InitializedEntity::EK_New:
  5225. case InitializedEntity::EK_Variable:
  5226. case InitializedEntity::EK_Base:
  5227. case InitializedEntity::EK_Delegating:
  5228. case InitializedEntity::EK_VectorElement:
  5229. case InitializedEntity::EK_ComplexElement:
  5230. case InitializedEntity::EK_Exception:
  5231. case InitializedEntity::EK_BlockElement:
  5232. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5233. case InitializedEntity::EK_LambdaCapture:
  5234. case InitializedEntity::EK_CompoundLiteralInit:
  5235. return false;
  5236. case InitializedEntity::EK_Parameter:
  5237. case InitializedEntity::EK_Parameter_CF_Audited:
  5238. case InitializedEntity::EK_Temporary:
  5239. case InitializedEntity::EK_RelatedResult:
  5240. case InitializedEntity::EK_Binding:
  5241. return true;
  5242. }
  5243. llvm_unreachable("missed an InitializedEntity kind?");
  5244. }
  5245. /// Whether the given entity, when initialized with an object
  5246. /// created for that initialization, requires destruction.
  5247. static bool shouldDestroyEntity(const InitializedEntity &Entity) {
  5248. switch (Entity.getKind()) {
  5249. case InitializedEntity::EK_Result:
  5250. case InitializedEntity::EK_StmtExprResult:
  5251. case InitializedEntity::EK_New:
  5252. case InitializedEntity::EK_Base:
  5253. case InitializedEntity::EK_Delegating:
  5254. case InitializedEntity::EK_VectorElement:
  5255. case InitializedEntity::EK_ComplexElement:
  5256. case InitializedEntity::EK_BlockElement:
  5257. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5258. case InitializedEntity::EK_LambdaCapture:
  5259. return false;
  5260. case InitializedEntity::EK_Member:
  5261. case InitializedEntity::EK_Binding:
  5262. case InitializedEntity::EK_Variable:
  5263. case InitializedEntity::EK_Parameter:
  5264. case InitializedEntity::EK_Parameter_CF_Audited:
  5265. case InitializedEntity::EK_Temporary:
  5266. case InitializedEntity::EK_ArrayElement:
  5267. case InitializedEntity::EK_Exception:
  5268. case InitializedEntity::EK_CompoundLiteralInit:
  5269. case InitializedEntity::EK_RelatedResult:
  5270. return true;
  5271. }
  5272. llvm_unreachable("missed an InitializedEntity kind?");
  5273. }
  5274. /// Get the location at which initialization diagnostics should appear.
  5275. static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
  5276. Expr *Initializer) {
  5277. switch (Entity.getKind()) {
  5278. case InitializedEntity::EK_Result:
  5279. case InitializedEntity::EK_StmtExprResult:
  5280. return Entity.getReturnLoc();
  5281. case InitializedEntity::EK_Exception:
  5282. return Entity.getThrowLoc();
  5283. case InitializedEntity::EK_Variable:
  5284. case InitializedEntity::EK_Binding:
  5285. return Entity.getDecl()->getLocation();
  5286. case InitializedEntity::EK_LambdaCapture:
  5287. return Entity.getCaptureLoc();
  5288. case InitializedEntity::EK_ArrayElement:
  5289. case InitializedEntity::EK_Member:
  5290. case InitializedEntity::EK_Parameter:
  5291. case InitializedEntity::EK_Parameter_CF_Audited:
  5292. case InitializedEntity::EK_Temporary:
  5293. case InitializedEntity::EK_New:
  5294. case InitializedEntity::EK_Base:
  5295. case InitializedEntity::EK_Delegating:
  5296. case InitializedEntity::EK_VectorElement:
  5297. case InitializedEntity::EK_ComplexElement:
  5298. case InitializedEntity::EK_BlockElement:
  5299. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5300. case InitializedEntity::EK_CompoundLiteralInit:
  5301. case InitializedEntity::EK_RelatedResult:
  5302. return Initializer->getBeginLoc();
  5303. }
  5304. llvm_unreachable("missed an InitializedEntity kind?");
  5305. }
  5306. /// Make a (potentially elidable) temporary copy of the object
  5307. /// provided by the given initializer by calling the appropriate copy
  5308. /// constructor.
  5309. ///
  5310. /// \param S The Sema object used for type-checking.
  5311. ///
  5312. /// \param T The type of the temporary object, which must either be
  5313. /// the type of the initializer expression or a superclass thereof.
  5314. ///
  5315. /// \param Entity The entity being initialized.
  5316. ///
  5317. /// \param CurInit The initializer expression.
  5318. ///
  5319. /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
  5320. /// is permitted in C++03 (but not C++0x) when binding a reference to
  5321. /// an rvalue.
  5322. ///
  5323. /// \returns An expression that copies the initializer expression into
  5324. /// a temporary object, or an error expression if a copy could not be
  5325. /// created.
  5326. static ExprResult CopyObject(Sema &S,
  5327. QualType T,
  5328. const InitializedEntity &Entity,
  5329. ExprResult CurInit,
  5330. bool IsExtraneousCopy) {
  5331. if (CurInit.isInvalid())
  5332. return CurInit;
  5333. // Determine which class type we're copying to.
  5334. Expr *CurInitExpr = (Expr *)CurInit.get();
  5335. CXXRecordDecl *Class = nullptr;
  5336. if (const RecordType *Record = T->getAs<RecordType>())
  5337. Class = cast<CXXRecordDecl>(Record->getDecl());
  5338. if (!Class)
  5339. return CurInit;
  5340. SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
  5341. // Make sure that the type we are copying is complete.
  5342. if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
  5343. return CurInit;
  5344. // Perform overload resolution using the class's constructors. Per
  5345. // C++11 [dcl.init]p16, second bullet for class types, this initialization
  5346. // is direct-initialization.
  5347. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5348. DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
  5349. OverloadCandidateSet::iterator Best;
  5350. switch (ResolveConstructorOverload(
  5351. S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
  5352. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  5353. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  5354. /*SecondStepOfCopyInit=*/true)) {
  5355. case OR_Success:
  5356. break;
  5357. case OR_No_Viable_Function:
  5358. CandidateSet.NoteCandidates(
  5359. PartialDiagnosticAt(
  5360. Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
  5361. ? diag::ext_rvalue_to_reference_temp_copy_no_viable
  5362. : diag::err_temp_copy_no_viable)
  5363. << (int)Entity.getKind() << CurInitExpr->getType()
  5364. << CurInitExpr->getSourceRange()),
  5365. S, OCD_AllCandidates, CurInitExpr);
  5366. if (!IsExtraneousCopy || S.isSFINAEContext())
  5367. return ExprError();
  5368. return CurInit;
  5369. case OR_Ambiguous:
  5370. CandidateSet.NoteCandidates(
  5371. PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
  5372. << (int)Entity.getKind()
  5373. << CurInitExpr->getType()
  5374. << CurInitExpr->getSourceRange()),
  5375. S, OCD_ViableCandidates, CurInitExpr);
  5376. return ExprError();
  5377. case OR_Deleted:
  5378. S.Diag(Loc, diag::err_temp_copy_deleted)
  5379. << (int)Entity.getKind() << CurInitExpr->getType()
  5380. << CurInitExpr->getSourceRange();
  5381. S.NoteDeletedFunction(Best->Function);
  5382. return ExprError();
  5383. }
  5384. bool HadMultipleCandidates = CandidateSet.size() > 1;
  5385. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  5386. SmallVector<Expr*, 8> ConstructorArgs;
  5387. CurInit.get(); // Ownership transferred into MultiExprArg, below.
  5388. S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
  5389. IsExtraneousCopy);
  5390. if (IsExtraneousCopy) {
  5391. // If this is a totally extraneous copy for C++03 reference
  5392. // binding purposes, just return the original initialization
  5393. // expression. We don't generate an (elided) copy operation here
  5394. // because doing so would require us to pass down a flag to avoid
  5395. // infinite recursion, where each step adds another extraneous,
  5396. // elidable copy.
  5397. // Instantiate the default arguments of any extra parameters in
  5398. // the selected copy constructor, as if we were going to create a
  5399. // proper call to the copy constructor.
  5400. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
  5401. ParmVarDecl *Parm = Constructor->getParamDecl(I);
  5402. if (S.RequireCompleteType(Loc, Parm->getType(),
  5403. diag::err_call_incomplete_argument))
  5404. break;
  5405. // Build the default argument expression; we don't actually care
  5406. // if this succeeds or not, because this routine will complain
  5407. // if there was a problem.
  5408. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
  5409. }
  5410. return CurInitExpr;
  5411. }
  5412. // Determine the arguments required to actually perform the
  5413. // constructor call (we might have derived-to-base conversions, or
  5414. // the copy constructor may have default arguments).
  5415. if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
  5416. return ExprError();
  5417. // C++0x [class.copy]p32:
  5418. // When certain criteria are met, an implementation is allowed to
  5419. // omit the copy/move construction of a class object, even if the
  5420. // copy/move constructor and/or destructor for the object have
  5421. // side effects. [...]
  5422. // - when a temporary class object that has not been bound to a
  5423. // reference (12.2) would be copied/moved to a class object
  5424. // with the same cv-unqualified type, the copy/move operation
  5425. // can be omitted by constructing the temporary object
  5426. // directly into the target of the omitted copy/move
  5427. //
  5428. // Note that the other three bullets are handled elsewhere. Copy
  5429. // elision for return statements and throw expressions are handled as part
  5430. // of constructor initialization, while copy elision for exception handlers
  5431. // is handled by the run-time.
  5432. //
  5433. // FIXME: If the function parameter is not the same type as the temporary, we
  5434. // should still be able to elide the copy, but we don't have a way to
  5435. // represent in the AST how much should be elided in this case.
  5436. bool Elidable =
  5437. CurInitExpr->isTemporaryObject(S.Context, Class) &&
  5438. S.Context.hasSameUnqualifiedType(
  5439. Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
  5440. CurInitExpr->getType());
  5441. // Actually perform the constructor call.
  5442. CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
  5443. Elidable,
  5444. ConstructorArgs,
  5445. HadMultipleCandidates,
  5446. /*ListInit*/ false,
  5447. /*StdInitListInit*/ false,
  5448. /*ZeroInit*/ false,
  5449. CXXConstructExpr::CK_Complete,
  5450. SourceRange());
  5451. // If we're supposed to bind temporaries, do so.
  5452. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
  5453. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  5454. return CurInit;
  5455. }
  5456. /// Check whether elidable copy construction for binding a reference to
  5457. /// a temporary would have succeeded if we were building in C++98 mode, for
  5458. /// -Wc++98-compat.
  5459. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  5460. const InitializedEntity &Entity,
  5461. Expr *CurInitExpr) {
  5462. assert(S.getLangOpts().CPlusPlus11);
  5463. const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
  5464. if (!Record)
  5465. return;
  5466. SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
  5467. if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
  5468. return;
  5469. // Find constructors which would have been considered.
  5470. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5471. DeclContext::lookup_result Ctors =
  5472. S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
  5473. // Perform overload resolution.
  5474. OverloadCandidateSet::iterator Best;
  5475. OverloadingResult OR = ResolveConstructorOverload(
  5476. S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
  5477. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  5478. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  5479. /*SecondStepOfCopyInit=*/true);
  5480. PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
  5481. << OR << (int)Entity.getKind() << CurInitExpr->getType()
  5482. << CurInitExpr->getSourceRange();
  5483. switch (OR) {
  5484. case OR_Success:
  5485. S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
  5486. Best->FoundDecl, Entity, Diag);
  5487. // FIXME: Check default arguments as far as that's possible.
  5488. break;
  5489. case OR_No_Viable_Function:
  5490. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  5491. OCD_AllCandidates, CurInitExpr);
  5492. break;
  5493. case OR_Ambiguous:
  5494. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  5495. OCD_ViableCandidates, CurInitExpr);
  5496. break;
  5497. case OR_Deleted:
  5498. S.Diag(Loc, Diag);
  5499. S.NoteDeletedFunction(Best->Function);
  5500. break;
  5501. }
  5502. }
  5503. void InitializationSequence::PrintInitLocationNote(Sema &S,
  5504. const InitializedEntity &Entity) {
  5505. if (Entity.isParameterKind() && Entity.getDecl()) {
  5506. if (Entity.getDecl()->getLocation().isInvalid())
  5507. return;
  5508. if (Entity.getDecl()->getDeclName())
  5509. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
  5510. << Entity.getDecl()->getDeclName();
  5511. else
  5512. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
  5513. }
  5514. else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
  5515. Entity.getMethodDecl())
  5516. S.Diag(Entity.getMethodDecl()->getLocation(),
  5517. diag::note_method_return_type_change)
  5518. << Entity.getMethodDecl()->getDeclName();
  5519. }
  5520. /// Returns true if the parameters describe a constructor initialization of
  5521. /// an explicit temporary object, e.g. "Point(x, y)".
  5522. static bool isExplicitTemporary(const InitializedEntity &Entity,
  5523. const InitializationKind &Kind,
  5524. unsigned NumArgs) {
  5525. switch (Entity.getKind()) {
  5526. case InitializedEntity::EK_Temporary:
  5527. case InitializedEntity::EK_CompoundLiteralInit:
  5528. case InitializedEntity::EK_RelatedResult:
  5529. break;
  5530. default:
  5531. return false;
  5532. }
  5533. switch (Kind.getKind()) {
  5534. case InitializationKind::IK_DirectList:
  5535. return true;
  5536. // FIXME: Hack to work around cast weirdness.
  5537. case InitializationKind::IK_Direct:
  5538. case InitializationKind::IK_Value:
  5539. return NumArgs != 1;
  5540. default:
  5541. return false;
  5542. }
  5543. }
  5544. static ExprResult
  5545. PerformConstructorInitialization(Sema &S,
  5546. const InitializedEntity &Entity,
  5547. const InitializationKind &Kind,
  5548. MultiExprArg Args,
  5549. const InitializationSequence::Step& Step,
  5550. bool &ConstructorInitRequiresZeroInit,
  5551. bool IsListInitialization,
  5552. bool IsStdInitListInitialization,
  5553. SourceLocation LBraceLoc,
  5554. SourceLocation RBraceLoc) {
  5555. unsigned NumArgs = Args.size();
  5556. CXXConstructorDecl *Constructor
  5557. = cast<CXXConstructorDecl>(Step.Function.Function);
  5558. bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
  5559. // Build a call to the selected constructor.
  5560. SmallVector<Expr*, 8> ConstructorArgs;
  5561. SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
  5562. ? Kind.getEqualLoc()
  5563. : Kind.getLocation();
  5564. if (Kind.getKind() == InitializationKind::IK_Default) {
  5565. // Force even a trivial, implicit default constructor to be
  5566. // semantically checked. We do this explicitly because we don't build
  5567. // the definition for completely trivial constructors.
  5568. assert(Constructor->getParent() && "No parent class for constructor.");
  5569. if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  5570. Constructor->isTrivial() && !Constructor->isUsed(false))
  5571. S.DefineImplicitDefaultConstructor(Loc, Constructor);
  5572. }
  5573. ExprResult CurInit((Expr *)nullptr);
  5574. // C++ [over.match.copy]p1:
  5575. // - When initializing a temporary to be bound to the first parameter
  5576. // of a constructor that takes a reference to possibly cv-qualified
  5577. // T as its first argument, called with a single argument in the
  5578. // context of direct-initialization, explicit conversion functions
  5579. // are also considered.
  5580. bool AllowExplicitConv =
  5581. Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
  5582. hasCopyOrMoveCtorParam(S.Context,
  5583. getConstructorInfo(Step.Function.FoundDecl));
  5584. // Determine the arguments required to actually perform the constructor
  5585. // call.
  5586. if (S.CompleteConstructorCall(Constructor, Args,
  5587. Loc, ConstructorArgs,
  5588. AllowExplicitConv,
  5589. IsListInitialization))
  5590. return ExprError();
  5591. if (isExplicitTemporary(Entity, Kind, NumArgs)) {
  5592. // An explicitly-constructed temporary, e.g., X(1, 2).
  5593. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  5594. return ExprError();
  5595. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  5596. if (!TSInfo)
  5597. TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
  5598. SourceRange ParenOrBraceRange =
  5599. (Kind.getKind() == InitializationKind::IK_DirectList)
  5600. ? SourceRange(LBraceLoc, RBraceLoc)
  5601. : Kind.getParenOrBraceRange();
  5602. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
  5603. Step.Function.FoundDecl.getDecl())) {
  5604. Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
  5605. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  5606. return ExprError();
  5607. }
  5608. S.MarkFunctionReferenced(Loc, Constructor);
  5609. CurInit = CXXTemporaryObjectExpr::Create(
  5610. S.Context, Constructor,
  5611. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  5612. ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
  5613. IsListInitialization, IsStdInitListInitialization,
  5614. ConstructorInitRequiresZeroInit);
  5615. } else {
  5616. CXXConstructExpr::ConstructionKind ConstructKind =
  5617. CXXConstructExpr::CK_Complete;
  5618. if (Entity.getKind() == InitializedEntity::EK_Base) {
  5619. ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
  5620. CXXConstructExpr::CK_VirtualBase :
  5621. CXXConstructExpr::CK_NonVirtualBase;
  5622. } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
  5623. ConstructKind = CXXConstructExpr::CK_Delegating;
  5624. }
  5625. // Only get the parenthesis or brace range if it is a list initialization or
  5626. // direct construction.
  5627. SourceRange ParenOrBraceRange;
  5628. if (IsListInitialization)
  5629. ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
  5630. else if (Kind.getKind() == InitializationKind::IK_Direct)
  5631. ParenOrBraceRange = Kind.getParenOrBraceRange();
  5632. // If the entity allows NRVO, mark the construction as elidable
  5633. // unconditionally.
  5634. if (Entity.allowsNRVO())
  5635. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  5636. Step.Function.FoundDecl,
  5637. Constructor, /*Elidable=*/true,
  5638. ConstructorArgs,
  5639. HadMultipleCandidates,
  5640. IsListInitialization,
  5641. IsStdInitListInitialization,
  5642. ConstructorInitRequiresZeroInit,
  5643. ConstructKind,
  5644. ParenOrBraceRange);
  5645. else
  5646. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  5647. Step.Function.FoundDecl,
  5648. Constructor,
  5649. ConstructorArgs,
  5650. HadMultipleCandidates,
  5651. IsListInitialization,
  5652. IsStdInitListInitialization,
  5653. ConstructorInitRequiresZeroInit,
  5654. ConstructKind,
  5655. ParenOrBraceRange);
  5656. }
  5657. if (CurInit.isInvalid())
  5658. return ExprError();
  5659. // Only check access if all of that succeeded.
  5660. S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
  5661. if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
  5662. return ExprError();
  5663. if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
  5664. if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
  5665. return ExprError();
  5666. if (shouldBindAsTemporary(Entity))
  5667. CurInit = S.MaybeBindToTemporary(CurInit.get());
  5668. return CurInit;
  5669. }
  5670. namespace {
  5671. enum LifetimeKind {
  5672. /// The lifetime of a temporary bound to this entity ends at the end of the
  5673. /// full-expression, and that's (probably) fine.
  5674. LK_FullExpression,
  5675. /// The lifetime of a temporary bound to this entity is extended to the
  5676. /// lifeitme of the entity itself.
  5677. LK_Extended,
  5678. /// The lifetime of a temporary bound to this entity probably ends too soon,
  5679. /// because the entity is allocated in a new-expression.
  5680. LK_New,
  5681. /// The lifetime of a temporary bound to this entity ends too soon, because
  5682. /// the entity is a return object.
  5683. LK_Return,
  5684. /// The lifetime of a temporary bound to this entity ends too soon, because
  5685. /// the entity is the result of a statement expression.
  5686. LK_StmtExprResult,
  5687. /// This is a mem-initializer: if it would extend a temporary (other than via
  5688. /// a default member initializer), the program is ill-formed.
  5689. LK_MemInitializer,
  5690. };
  5691. using LifetimeResult =
  5692. llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
  5693. }
  5694. /// Determine the declaration which an initialized entity ultimately refers to,
  5695. /// for the purpose of lifetime-extending a temporary bound to a reference in
  5696. /// the initialization of \p Entity.
  5697. static LifetimeResult getEntityLifetime(
  5698. const InitializedEntity *Entity,
  5699. const InitializedEntity *InitField = nullptr) {
  5700. // C++11 [class.temporary]p5:
  5701. switch (Entity->getKind()) {
  5702. case InitializedEntity::EK_Variable:
  5703. // The temporary [...] persists for the lifetime of the reference
  5704. return {Entity, LK_Extended};
  5705. case InitializedEntity::EK_Member:
  5706. // For subobjects, we look at the complete object.
  5707. if (Entity->getParent())
  5708. return getEntityLifetime(Entity->getParent(), Entity);
  5709. // except:
  5710. // C++17 [class.base.init]p8:
  5711. // A temporary expression bound to a reference member in a
  5712. // mem-initializer is ill-formed.
  5713. // C++17 [class.base.init]p11:
  5714. // A temporary expression bound to a reference member from a
  5715. // default member initializer is ill-formed.
  5716. //
  5717. // The context of p11 and its example suggest that it's only the use of a
  5718. // default member initializer from a constructor that makes the program
  5719. // ill-formed, not its mere existence, and that it can even be used by
  5720. // aggregate initialization.
  5721. return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
  5722. : LK_MemInitializer};
  5723. case InitializedEntity::EK_Binding:
  5724. // Per [dcl.decomp]p3, the binding is treated as a variable of reference
  5725. // type.
  5726. return {Entity, LK_Extended};
  5727. case InitializedEntity::EK_Parameter:
  5728. case InitializedEntity::EK_Parameter_CF_Audited:
  5729. // -- A temporary bound to a reference parameter in a function call
  5730. // persists until the completion of the full-expression containing
  5731. // the call.
  5732. return {nullptr, LK_FullExpression};
  5733. case InitializedEntity::EK_Result:
  5734. // -- The lifetime of a temporary bound to the returned value in a
  5735. // function return statement is not extended; the temporary is
  5736. // destroyed at the end of the full-expression in the return statement.
  5737. return {nullptr, LK_Return};
  5738. case InitializedEntity::EK_StmtExprResult:
  5739. // FIXME: Should we lifetime-extend through the result of a statement
  5740. // expression?
  5741. return {nullptr, LK_StmtExprResult};
  5742. case InitializedEntity::EK_New:
  5743. // -- A temporary bound to a reference in a new-initializer persists
  5744. // until the completion of the full-expression containing the
  5745. // new-initializer.
  5746. return {nullptr, LK_New};
  5747. case InitializedEntity::EK_Temporary:
  5748. case InitializedEntity::EK_CompoundLiteralInit:
  5749. case InitializedEntity::EK_RelatedResult:
  5750. // We don't yet know the storage duration of the surrounding temporary.
  5751. // Assume it's got full-expression duration for now, it will patch up our
  5752. // storage duration if that's not correct.
  5753. return {nullptr, LK_FullExpression};
  5754. case InitializedEntity::EK_ArrayElement:
  5755. // For subobjects, we look at the complete object.
  5756. return getEntityLifetime(Entity->getParent(), InitField);
  5757. case InitializedEntity::EK_Base:
  5758. // For subobjects, we look at the complete object.
  5759. if (Entity->getParent())
  5760. return getEntityLifetime(Entity->getParent(), InitField);
  5761. return {InitField, LK_MemInitializer};
  5762. case InitializedEntity::EK_Delegating:
  5763. // We can reach this case for aggregate initialization in a constructor:
  5764. // struct A { int &&r; };
  5765. // struct B : A { B() : A{0} {} };
  5766. // In this case, use the outermost field decl as the context.
  5767. return {InitField, LK_MemInitializer};
  5768. case InitializedEntity::EK_BlockElement:
  5769. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5770. case InitializedEntity::EK_LambdaCapture:
  5771. case InitializedEntity::EK_VectorElement:
  5772. case InitializedEntity::EK_ComplexElement:
  5773. return {nullptr, LK_FullExpression};
  5774. case InitializedEntity::EK_Exception:
  5775. // FIXME: Can we diagnose lifetime problems with exceptions?
  5776. return {nullptr, LK_FullExpression};
  5777. }
  5778. llvm_unreachable("unknown entity kind");
  5779. }
  5780. namespace {
  5781. enum ReferenceKind {
  5782. /// Lifetime would be extended by a reference binding to a temporary.
  5783. RK_ReferenceBinding,
  5784. /// Lifetime would be extended by a std::initializer_list object binding to
  5785. /// its backing array.
  5786. RK_StdInitializerList,
  5787. };
  5788. /// A temporary or local variable. This will be one of:
  5789. /// * A MaterializeTemporaryExpr.
  5790. /// * A DeclRefExpr whose declaration is a local.
  5791. /// * An AddrLabelExpr.
  5792. /// * A BlockExpr for a block with captures.
  5793. using Local = Expr*;
  5794. /// Expressions we stepped over when looking for the local state. Any steps
  5795. /// that would inhibit lifetime extension or take us out of subexpressions of
  5796. /// the initializer are included.
  5797. struct IndirectLocalPathEntry {
  5798. enum EntryKind {
  5799. DefaultInit,
  5800. AddressOf,
  5801. VarInit,
  5802. LValToRVal,
  5803. LifetimeBoundCall,
  5804. } Kind;
  5805. Expr *E;
  5806. const Decl *D = nullptr;
  5807. IndirectLocalPathEntry() {}
  5808. IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
  5809. IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
  5810. : Kind(K), E(E), D(D) {}
  5811. };
  5812. using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
  5813. struct RevertToOldSizeRAII {
  5814. IndirectLocalPath &Path;
  5815. unsigned OldSize = Path.size();
  5816. RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
  5817. ~RevertToOldSizeRAII() { Path.resize(OldSize); }
  5818. };
  5819. using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
  5820. ReferenceKind RK)>;
  5821. }
  5822. static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
  5823. for (auto E : Path)
  5824. if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
  5825. return true;
  5826. return false;
  5827. }
  5828. static bool pathContainsInit(IndirectLocalPath &Path) {
  5829. return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
  5830. return E.Kind == IndirectLocalPathEntry::DefaultInit ||
  5831. E.Kind == IndirectLocalPathEntry::VarInit;
  5832. });
  5833. }
  5834. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  5835. Expr *Init, LocalVisitor Visit,
  5836. bool RevisitSubinits);
  5837. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  5838. Expr *Init, ReferenceKind RK,
  5839. LocalVisitor Visit);
  5840. static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
  5841. const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
  5842. if (!TSI)
  5843. return false;
  5844. // Don't declare this variable in the second operand of the for-statement;
  5845. // GCC miscompiles that by ending its lifetime before evaluating the
  5846. // third operand. See gcc.gnu.org/PR86769.
  5847. AttributedTypeLoc ATL;
  5848. for (TypeLoc TL = TSI->getTypeLoc();
  5849. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5850. TL = ATL.getModifiedLoc()) {
  5851. if (ATL.getAttrAs<LifetimeBoundAttr>())
  5852. return true;
  5853. }
  5854. return false;
  5855. }
  5856. static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
  5857. LocalVisitor Visit) {
  5858. const FunctionDecl *Callee;
  5859. ArrayRef<Expr*> Args;
  5860. if (auto *CE = dyn_cast<CallExpr>(Call)) {
  5861. Callee = CE->getDirectCallee();
  5862. Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
  5863. } else {
  5864. auto *CCE = cast<CXXConstructExpr>(Call);
  5865. Callee = CCE->getConstructor();
  5866. Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
  5867. }
  5868. if (!Callee)
  5869. return;
  5870. Expr *ObjectArg = nullptr;
  5871. if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
  5872. ObjectArg = Args[0];
  5873. Args = Args.slice(1);
  5874. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
  5875. ObjectArg = MCE->getImplicitObjectArgument();
  5876. }
  5877. auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
  5878. Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
  5879. if (Arg->isGLValue())
  5880. visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
  5881. Visit);
  5882. else
  5883. visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
  5884. Path.pop_back();
  5885. };
  5886. if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
  5887. VisitLifetimeBoundArg(Callee, ObjectArg);
  5888. for (unsigned I = 0,
  5889. N = std::min<unsigned>(Callee->getNumParams(), Args.size());
  5890. I != N; ++I) {
  5891. if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
  5892. VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
  5893. }
  5894. }
  5895. /// Visit the locals that would be reachable through a reference bound to the
  5896. /// glvalue expression \c Init.
  5897. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  5898. Expr *Init, ReferenceKind RK,
  5899. LocalVisitor Visit) {
  5900. RevertToOldSizeRAII RAII(Path);
  5901. // Walk past any constructs which we can lifetime-extend across.
  5902. Expr *Old;
  5903. do {
  5904. Old = Init;
  5905. if (auto *FE = dyn_cast<FullExpr>(Init))
  5906. Init = FE->getSubExpr();
  5907. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  5908. // If this is just redundant braces around an initializer, step over it.
  5909. if (ILE->isTransparent())
  5910. Init = ILE->getInit(0);
  5911. }
  5912. // Step over any subobject adjustments; we may have a materialized
  5913. // temporary inside them.
  5914. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  5915. // Per current approach for DR1376, look through casts to reference type
  5916. // when performing lifetime extension.
  5917. if (CastExpr *CE = dyn_cast<CastExpr>(Init))
  5918. if (CE->getSubExpr()->isGLValue())
  5919. Init = CE->getSubExpr();
  5920. // Per the current approach for DR1299, look through array element access
  5921. // on array glvalues when performing lifetime extension.
  5922. if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
  5923. Init = ASE->getBase();
  5924. auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
  5925. if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
  5926. Init = ICE->getSubExpr();
  5927. else
  5928. // We can't lifetime extend through this but we might still find some
  5929. // retained temporaries.
  5930. return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
  5931. }
  5932. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  5933. // constructor inherits one as an implicit mem-initializer.
  5934. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  5935. Path.push_back(
  5936. {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  5937. Init = DIE->getExpr();
  5938. }
  5939. } while (Init != Old);
  5940. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  5941. if (Visit(Path, Local(MTE), RK))
  5942. visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
  5943. true);
  5944. }
  5945. if (isa<CallExpr>(Init))
  5946. return visitLifetimeBoundArguments(Path, Init, Visit);
  5947. switch (Init->getStmtClass()) {
  5948. case Stmt::DeclRefExprClass: {
  5949. // If we find the name of a local non-reference parameter, we could have a
  5950. // lifetime problem.
  5951. auto *DRE = cast<DeclRefExpr>(Init);
  5952. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  5953. if (VD && VD->hasLocalStorage() &&
  5954. !DRE->refersToEnclosingVariableOrCapture()) {
  5955. if (!VD->getType()->isReferenceType()) {
  5956. Visit(Path, Local(DRE), RK);
  5957. } else if (isa<ParmVarDecl>(DRE->getDecl())) {
  5958. // The lifetime of a reference parameter is unknown; assume it's OK
  5959. // for now.
  5960. break;
  5961. } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
  5962. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  5963. visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
  5964. RK_ReferenceBinding, Visit);
  5965. }
  5966. }
  5967. break;
  5968. }
  5969. case Stmt::UnaryOperatorClass: {
  5970. // The only unary operator that make sense to handle here
  5971. // is Deref. All others don't resolve to a "name." This includes
  5972. // handling all sorts of rvalues passed to a unary operator.
  5973. const UnaryOperator *U = cast<UnaryOperator>(Init);
  5974. if (U->getOpcode() == UO_Deref)
  5975. visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
  5976. break;
  5977. }
  5978. case Stmt::OMPArraySectionExprClass: {
  5979. visitLocalsRetainedByInitializer(
  5980. Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
  5981. break;
  5982. }
  5983. case Stmt::ConditionalOperatorClass:
  5984. case Stmt::BinaryConditionalOperatorClass: {
  5985. auto *C = cast<AbstractConditionalOperator>(Init);
  5986. if (!C->getTrueExpr()->getType()->isVoidType())
  5987. visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
  5988. if (!C->getFalseExpr()->getType()->isVoidType())
  5989. visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
  5990. break;
  5991. }
  5992. // FIXME: Visit the left-hand side of an -> or ->*.
  5993. default:
  5994. break;
  5995. }
  5996. }
  5997. /// Visit the locals that would be reachable through an object initialized by
  5998. /// the prvalue expression \c Init.
  5999. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  6000. Expr *Init, LocalVisitor Visit,
  6001. bool RevisitSubinits) {
  6002. RevertToOldSizeRAII RAII(Path);
  6003. Expr *Old;
  6004. do {
  6005. Old = Init;
  6006. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  6007. // constructor inherits one as an implicit mem-initializer.
  6008. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  6009. Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  6010. Init = DIE->getExpr();
  6011. }
  6012. if (auto *FE = dyn_cast<FullExpr>(Init))
  6013. Init = FE->getSubExpr();
  6014. // Dig out the expression which constructs the extended temporary.
  6015. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  6016. if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
  6017. Init = BTE->getSubExpr();
  6018. Init = Init->IgnoreParens();
  6019. // Step over value-preserving rvalue casts.
  6020. if (auto *CE = dyn_cast<CastExpr>(Init)) {
  6021. switch (CE->getCastKind()) {
  6022. case CK_LValueToRValue:
  6023. // If we can match the lvalue to a const object, we can look at its
  6024. // initializer.
  6025. Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
  6026. return visitLocalsRetainedByReferenceBinding(
  6027. Path, Init, RK_ReferenceBinding,
  6028. [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
  6029. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  6030. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6031. if (VD && VD->getType().isConstQualified() && VD->getInit() &&
  6032. !isVarOnPath(Path, VD)) {
  6033. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  6034. visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
  6035. }
  6036. } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
  6037. if (MTE->getType().isConstQualified())
  6038. visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
  6039. Visit, true);
  6040. }
  6041. return false;
  6042. });
  6043. // We assume that objects can be retained by pointers cast to integers,
  6044. // but not if the integer is cast to floating-point type or to _Complex.
  6045. // We assume that casts to 'bool' do not preserve enough information to
  6046. // retain a local object.
  6047. case CK_NoOp:
  6048. case CK_BitCast:
  6049. case CK_BaseToDerived:
  6050. case CK_DerivedToBase:
  6051. case CK_UncheckedDerivedToBase:
  6052. case CK_Dynamic:
  6053. case CK_ToUnion:
  6054. case CK_UserDefinedConversion:
  6055. case CK_ConstructorConversion:
  6056. case CK_IntegralToPointer:
  6057. case CK_PointerToIntegral:
  6058. case CK_VectorSplat:
  6059. case CK_IntegralCast:
  6060. case CK_CPointerToObjCPointerCast:
  6061. case CK_BlockPointerToObjCPointerCast:
  6062. case CK_AnyPointerToBlockPointerCast:
  6063. case CK_AddressSpaceConversion:
  6064. break;
  6065. case CK_ArrayToPointerDecay:
  6066. // Model array-to-pointer decay as taking the address of the array
  6067. // lvalue.
  6068. Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
  6069. return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
  6070. RK_ReferenceBinding, Visit);
  6071. default:
  6072. return;
  6073. }
  6074. Init = CE->getSubExpr();
  6075. }
  6076. } while (Old != Init);
  6077. // C++17 [dcl.init.list]p6:
  6078. // initializing an initializer_list object from the array extends the
  6079. // lifetime of the array exactly like binding a reference to a temporary.
  6080. if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
  6081. return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
  6082. RK_StdInitializerList, Visit);
  6083. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  6084. // We already visited the elements of this initializer list while
  6085. // performing the initialization. Don't visit them again unless we've
  6086. // changed the lifetime of the initialized entity.
  6087. if (!RevisitSubinits)
  6088. return;
  6089. if (ILE->isTransparent())
  6090. return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
  6091. RevisitSubinits);
  6092. if (ILE->getType()->isArrayType()) {
  6093. for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
  6094. visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
  6095. RevisitSubinits);
  6096. return;
  6097. }
  6098. if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
  6099. assert(RD->isAggregate() && "aggregate init on non-aggregate");
  6100. // If we lifetime-extend a braced initializer which is initializing an
  6101. // aggregate, and that aggregate contains reference members which are
  6102. // bound to temporaries, those temporaries are also lifetime-extended.
  6103. if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
  6104. ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
  6105. visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
  6106. RK_ReferenceBinding, Visit);
  6107. else {
  6108. unsigned Index = 0;
  6109. for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
  6110. visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
  6111. RevisitSubinits);
  6112. for (const auto *I : RD->fields()) {
  6113. if (Index >= ILE->getNumInits())
  6114. break;
  6115. if (I->isUnnamedBitfield())
  6116. continue;
  6117. Expr *SubInit = ILE->getInit(Index);
  6118. if (I->getType()->isReferenceType())
  6119. visitLocalsRetainedByReferenceBinding(Path, SubInit,
  6120. RK_ReferenceBinding, Visit);
  6121. else
  6122. // This might be either aggregate-initialization of a member or
  6123. // initialization of a std::initializer_list object. Regardless,
  6124. // we should recursively lifetime-extend that initializer.
  6125. visitLocalsRetainedByInitializer(Path, SubInit, Visit,
  6126. RevisitSubinits);
  6127. ++Index;
  6128. }
  6129. }
  6130. }
  6131. return;
  6132. }
  6133. // The lifetime of an init-capture is that of the closure object constructed
  6134. // by a lambda-expression.
  6135. if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
  6136. for (Expr *E : LE->capture_inits()) {
  6137. if (!E)
  6138. continue;
  6139. if (E->isGLValue())
  6140. visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
  6141. Visit);
  6142. else
  6143. visitLocalsRetainedByInitializer(Path, E, Visit, true);
  6144. }
  6145. }
  6146. if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init))
  6147. return visitLifetimeBoundArguments(Path, Init, Visit);
  6148. switch (Init->getStmtClass()) {
  6149. case Stmt::UnaryOperatorClass: {
  6150. auto *UO = cast<UnaryOperator>(Init);
  6151. // If the initializer is the address of a local, we could have a lifetime
  6152. // problem.
  6153. if (UO->getOpcode() == UO_AddrOf) {
  6154. // If this is &rvalue, then it's ill-formed and we have already diagnosed
  6155. // it. Don't produce a redundant warning about the lifetime of the
  6156. // temporary.
  6157. if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
  6158. return;
  6159. Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
  6160. visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
  6161. RK_ReferenceBinding, Visit);
  6162. }
  6163. break;
  6164. }
  6165. case Stmt::BinaryOperatorClass: {
  6166. // Handle pointer arithmetic.
  6167. auto *BO = cast<BinaryOperator>(Init);
  6168. BinaryOperatorKind BOK = BO->getOpcode();
  6169. if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
  6170. break;
  6171. if (BO->getLHS()->getType()->isPointerType())
  6172. visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
  6173. else if (BO->getRHS()->getType()->isPointerType())
  6174. visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
  6175. break;
  6176. }
  6177. case Stmt::ConditionalOperatorClass:
  6178. case Stmt::BinaryConditionalOperatorClass: {
  6179. auto *C = cast<AbstractConditionalOperator>(Init);
  6180. // In C++, we can have a throw-expression operand, which has 'void' type
  6181. // and isn't interesting from a lifetime perspective.
  6182. if (!C->getTrueExpr()->getType()->isVoidType())
  6183. visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
  6184. if (!C->getFalseExpr()->getType()->isVoidType())
  6185. visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
  6186. break;
  6187. }
  6188. case Stmt::BlockExprClass:
  6189. if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
  6190. // This is a local block, whose lifetime is that of the function.
  6191. Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
  6192. }
  6193. break;
  6194. case Stmt::AddrLabelExprClass:
  6195. // We want to warn if the address of a label would escape the function.
  6196. Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
  6197. break;
  6198. default:
  6199. break;
  6200. }
  6201. }
  6202. /// Determine whether this is an indirect path to a temporary that we are
  6203. /// supposed to lifetime-extend along (but don't).
  6204. static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
  6205. for (auto Elem : Path) {
  6206. if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
  6207. return false;
  6208. }
  6209. return true;
  6210. }
  6211. /// Find the range for the first interesting entry in the path at or after I.
  6212. static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
  6213. Expr *E) {
  6214. for (unsigned N = Path.size(); I != N; ++I) {
  6215. switch (Path[I].Kind) {
  6216. case IndirectLocalPathEntry::AddressOf:
  6217. case IndirectLocalPathEntry::LValToRVal:
  6218. case IndirectLocalPathEntry::LifetimeBoundCall:
  6219. // These exist primarily to mark the path as not permitting or
  6220. // supporting lifetime extension.
  6221. break;
  6222. case IndirectLocalPathEntry::DefaultInit:
  6223. case IndirectLocalPathEntry::VarInit:
  6224. return Path[I].E->getSourceRange();
  6225. }
  6226. }
  6227. return E->getSourceRange();
  6228. }
  6229. void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
  6230. Expr *Init) {
  6231. LifetimeResult LR = getEntityLifetime(&Entity);
  6232. LifetimeKind LK = LR.getInt();
  6233. const InitializedEntity *ExtendingEntity = LR.getPointer();
  6234. // If this entity doesn't have an interesting lifetime, don't bother looking
  6235. // for temporaries within its initializer.
  6236. if (LK == LK_FullExpression)
  6237. return;
  6238. auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
  6239. ReferenceKind RK) -> bool {
  6240. SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
  6241. SourceLocation DiagLoc = DiagRange.getBegin();
  6242. switch (LK) {
  6243. case LK_FullExpression:
  6244. llvm_unreachable("already handled this");
  6245. case LK_Extended: {
  6246. auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
  6247. if (!MTE) {
  6248. // The initialized entity has lifetime beyond the full-expression,
  6249. // and the local entity does too, so don't warn.
  6250. //
  6251. // FIXME: We should consider warning if a static / thread storage
  6252. // duration variable retains an automatic storage duration local.
  6253. return false;
  6254. }
  6255. // Lifetime-extend the temporary.
  6256. if (Path.empty()) {
  6257. // Update the storage duration of the materialized temporary.
  6258. // FIXME: Rebuild the expression instead of mutating it.
  6259. MTE->setExtendingDecl(ExtendingEntity->getDecl(),
  6260. ExtendingEntity->allocateManglingNumber());
  6261. // Also visit the temporaries lifetime-extended by this initializer.
  6262. return true;
  6263. }
  6264. if (shouldLifetimeExtendThroughPath(Path)) {
  6265. // We're supposed to lifetime-extend the temporary along this path (per
  6266. // the resolution of DR1815), but we don't support that yet.
  6267. //
  6268. // FIXME: Properly handle this situation. Perhaps the easiest approach
  6269. // would be to clone the initializer expression on each use that would
  6270. // lifetime extend its temporaries.
  6271. Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
  6272. << RK << DiagRange;
  6273. } else {
  6274. // If the path goes through the initialization of a variable or field,
  6275. // it can't possibly reach a temporary created in this full-expression.
  6276. // We will have already diagnosed any problems with the initializer.
  6277. if (pathContainsInit(Path))
  6278. return false;
  6279. Diag(DiagLoc, diag::warn_dangling_variable)
  6280. << RK << !Entity.getParent()
  6281. << ExtendingEntity->getDecl()->isImplicit()
  6282. << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
  6283. }
  6284. break;
  6285. }
  6286. case LK_MemInitializer: {
  6287. if (isa<MaterializeTemporaryExpr>(L)) {
  6288. // Under C++ DR1696, if a mem-initializer (or a default member
  6289. // initializer used by the absence of one) would lifetime-extend a
  6290. // temporary, the program is ill-formed.
  6291. if (auto *ExtendingDecl =
  6292. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  6293. bool IsSubobjectMember = ExtendingEntity != &Entity;
  6294. Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
  6295. ? diag::err_dangling_member
  6296. : diag::warn_dangling_member)
  6297. << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
  6298. // Don't bother adding a note pointing to the field if we're inside
  6299. // its default member initializer; our primary diagnostic points to
  6300. // the same place in that case.
  6301. if (Path.empty() ||
  6302. Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
  6303. Diag(ExtendingDecl->getLocation(),
  6304. diag::note_lifetime_extending_member_declared_here)
  6305. << RK << IsSubobjectMember;
  6306. }
  6307. } else {
  6308. // We have a mem-initializer but no particular field within it; this
  6309. // is either a base class or a delegating initializer directly
  6310. // initializing the base-class from something that doesn't live long
  6311. // enough.
  6312. //
  6313. // FIXME: Warn on this.
  6314. return false;
  6315. }
  6316. } else {
  6317. // Paths via a default initializer can only occur during error recovery
  6318. // (there's no other way that a default initializer can refer to a
  6319. // local). Don't produce a bogus warning on those cases.
  6320. if (pathContainsInit(Path))
  6321. return false;
  6322. auto *DRE = dyn_cast<DeclRefExpr>(L);
  6323. auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
  6324. if (!VD) {
  6325. // A member was initialized to a local block.
  6326. // FIXME: Warn on this.
  6327. return false;
  6328. }
  6329. if (auto *Member =
  6330. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  6331. bool IsPointer = Member->getType()->isAnyPointerType();
  6332. Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  6333. : diag::warn_bind_ref_member_to_parameter)
  6334. << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
  6335. Diag(Member->getLocation(),
  6336. diag::note_ref_or_ptr_member_declared_here)
  6337. << (unsigned)IsPointer;
  6338. }
  6339. }
  6340. break;
  6341. }
  6342. case LK_New:
  6343. if (isa<MaterializeTemporaryExpr>(L)) {
  6344. Diag(DiagLoc, RK == RK_ReferenceBinding
  6345. ? diag::warn_new_dangling_reference
  6346. : diag::warn_new_dangling_initializer_list)
  6347. << !Entity.getParent() << DiagRange;
  6348. } else {
  6349. // We can't determine if the allocation outlives the local declaration.
  6350. return false;
  6351. }
  6352. break;
  6353. case LK_Return:
  6354. case LK_StmtExprResult:
  6355. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  6356. // We can't determine if the local variable outlives the statement
  6357. // expression.
  6358. if (LK == LK_StmtExprResult)
  6359. return false;
  6360. Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
  6361. << Entity.getType()->isReferenceType() << DRE->getDecl()
  6362. << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
  6363. } else if (isa<BlockExpr>(L)) {
  6364. Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
  6365. } else if (isa<AddrLabelExpr>(L)) {
  6366. // Don't warn when returning a label from a statement expression.
  6367. // Leaving the scope doesn't end its lifetime.
  6368. if (LK == LK_StmtExprResult)
  6369. return false;
  6370. Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
  6371. } else {
  6372. Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
  6373. << Entity.getType()->isReferenceType() << DiagRange;
  6374. }
  6375. break;
  6376. }
  6377. for (unsigned I = 0; I != Path.size(); ++I) {
  6378. auto Elem = Path[I];
  6379. switch (Elem.Kind) {
  6380. case IndirectLocalPathEntry::AddressOf:
  6381. case IndirectLocalPathEntry::LValToRVal:
  6382. // These exist primarily to mark the path as not permitting or
  6383. // supporting lifetime extension.
  6384. break;
  6385. case IndirectLocalPathEntry::LifetimeBoundCall:
  6386. // FIXME: Consider adding a note for this.
  6387. break;
  6388. case IndirectLocalPathEntry::DefaultInit: {
  6389. auto *FD = cast<FieldDecl>(Elem.D);
  6390. Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
  6391. << FD << nextPathEntryRange(Path, I + 1, L);
  6392. break;
  6393. }
  6394. case IndirectLocalPathEntry::VarInit:
  6395. const VarDecl *VD = cast<VarDecl>(Elem.D);
  6396. Diag(VD->getLocation(), diag::note_local_var_initializer)
  6397. << VD->getType()->isReferenceType()
  6398. << VD->isImplicit() << VD->getDeclName()
  6399. << nextPathEntryRange(Path, I + 1, L);
  6400. break;
  6401. }
  6402. }
  6403. // We didn't lifetime-extend, so don't go any further; we don't need more
  6404. // warnings or errors on inner temporaries within this one's initializer.
  6405. return false;
  6406. };
  6407. llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
  6408. if (Init->isGLValue())
  6409. visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
  6410. TemporaryVisitor);
  6411. else
  6412. visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
  6413. }
  6414. static void DiagnoseNarrowingInInitList(Sema &S,
  6415. const ImplicitConversionSequence &ICS,
  6416. QualType PreNarrowingType,
  6417. QualType EntityType,
  6418. const Expr *PostInit);
  6419. /// Provide warnings when std::move is used on construction.
  6420. static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
  6421. bool IsReturnStmt) {
  6422. if (!InitExpr)
  6423. return;
  6424. if (S.inTemplateInstantiation())
  6425. return;
  6426. QualType DestType = InitExpr->getType();
  6427. if (!DestType->isRecordType())
  6428. return;
  6429. unsigned DiagID = 0;
  6430. if (IsReturnStmt) {
  6431. const CXXConstructExpr *CCE =
  6432. dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
  6433. if (!CCE || CCE->getNumArgs() != 1)
  6434. return;
  6435. if (!CCE->getConstructor()->isCopyOrMoveConstructor())
  6436. return;
  6437. InitExpr = CCE->getArg(0)->IgnoreImpCasts();
  6438. }
  6439. // Find the std::move call and get the argument.
  6440. const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
  6441. if (!CE || !CE->isCallToStdMove())
  6442. return;
  6443. const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
  6444. if (IsReturnStmt) {
  6445. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
  6446. if (!DRE || DRE->refersToEnclosingVariableOrCapture())
  6447. return;
  6448. const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6449. if (!VD || !VD->hasLocalStorage())
  6450. return;
  6451. // __block variables are not moved implicitly.
  6452. if (VD->hasAttr<BlocksAttr>())
  6453. return;
  6454. QualType SourceType = VD->getType();
  6455. if (!SourceType->isRecordType())
  6456. return;
  6457. if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
  6458. return;
  6459. }
  6460. // If we're returning a function parameter, copy elision
  6461. // is not possible.
  6462. if (isa<ParmVarDecl>(VD))
  6463. DiagID = diag::warn_redundant_move_on_return;
  6464. else
  6465. DiagID = diag::warn_pessimizing_move_on_return;
  6466. } else {
  6467. DiagID = diag::warn_pessimizing_move_on_initialization;
  6468. const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
  6469. if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
  6470. return;
  6471. }
  6472. S.Diag(CE->getBeginLoc(), DiagID);
  6473. // Get all the locations for a fix-it. Don't emit the fix-it if any location
  6474. // is within a macro.
  6475. SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
  6476. if (CallBegin.isMacroID())
  6477. return;
  6478. SourceLocation RParen = CE->getRParenLoc();
  6479. if (RParen.isMacroID())
  6480. return;
  6481. SourceLocation LParen;
  6482. SourceLocation ArgLoc = Arg->getBeginLoc();
  6483. // Special testing for the argument location. Since the fix-it needs the
  6484. // location right before the argument, the argument location can be in a
  6485. // macro only if it is at the beginning of the macro.
  6486. while (ArgLoc.isMacroID() &&
  6487. S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
  6488. ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
  6489. }
  6490. if (LParen.isMacroID())
  6491. return;
  6492. LParen = ArgLoc.getLocWithOffset(-1);
  6493. S.Diag(CE->getBeginLoc(), diag::note_remove_move)
  6494. << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
  6495. << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
  6496. }
  6497. static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
  6498. // Check to see if we are dereferencing a null pointer. If so, this is
  6499. // undefined behavior, so warn about it. This only handles the pattern
  6500. // "*null", which is a very syntactic check.
  6501. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  6502. if (UO->getOpcode() == UO_Deref &&
  6503. UO->getSubExpr()->IgnoreParenCasts()->
  6504. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
  6505. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  6506. S.PDiag(diag::warn_binding_null_to_reference)
  6507. << UO->getSubExpr()->getSourceRange());
  6508. }
  6509. }
  6510. MaterializeTemporaryExpr *
  6511. Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
  6512. bool BoundToLvalueReference) {
  6513. auto MTE = new (Context)
  6514. MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
  6515. // Order an ExprWithCleanups for lifetime marks.
  6516. //
  6517. // TODO: It'll be good to have a single place to check the access of the
  6518. // destructor and generate ExprWithCleanups for various uses. Currently these
  6519. // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
  6520. // but there may be a chance to merge them.
  6521. Cleanup.setExprNeedsCleanups(false);
  6522. return MTE;
  6523. }
  6524. ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
  6525. // In C++98, we don't want to implicitly create an xvalue.
  6526. // FIXME: This means that AST consumers need to deal with "prvalues" that
  6527. // denote materialized temporaries. Maybe we should add another ValueKind
  6528. // for "xvalue pretending to be a prvalue" for C++98 support.
  6529. if (!E->isRValue() || !getLangOpts().CPlusPlus11)
  6530. return E;
  6531. // C++1z [conv.rval]/1: T shall be a complete type.
  6532. // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
  6533. // If so, we should check for a non-abstract class type here too.
  6534. QualType T = E->getType();
  6535. if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
  6536. return ExprError();
  6537. return CreateMaterializeTemporaryExpr(E->getType(), E, false);
  6538. }
  6539. ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
  6540. ExprValueKind VK,
  6541. CheckedConversionKind CCK) {
  6542. CastKind CK = CK_NoOp;
  6543. if (VK == VK_RValue) {
  6544. auto PointeeTy = Ty->getPointeeType();
  6545. auto ExprPointeeTy = E->getType()->getPointeeType();
  6546. if (!PointeeTy.isNull() &&
  6547. PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
  6548. CK = CK_AddressSpaceConversion;
  6549. } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
  6550. CK = CK_AddressSpaceConversion;
  6551. }
  6552. return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
  6553. }
  6554. ExprResult InitializationSequence::Perform(Sema &S,
  6555. const InitializedEntity &Entity,
  6556. const InitializationKind &Kind,
  6557. MultiExprArg Args,
  6558. QualType *ResultType) {
  6559. if (Failed()) {
  6560. Diagnose(S, Entity, Kind, Args);
  6561. return ExprError();
  6562. }
  6563. if (!ZeroInitializationFixit.empty()) {
  6564. unsigned DiagID = diag::err_default_init_const;
  6565. if (Decl *D = Entity.getDecl())
  6566. if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
  6567. DiagID = diag::ext_default_init_const;
  6568. // The initialization would have succeeded with this fixit. Since the fixit
  6569. // is on the error, we need to build a valid AST in this case, so this isn't
  6570. // handled in the Failed() branch above.
  6571. QualType DestType = Entity.getType();
  6572. S.Diag(Kind.getLocation(), DiagID)
  6573. << DestType << (bool)DestType->getAs<RecordType>()
  6574. << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
  6575. ZeroInitializationFixit);
  6576. }
  6577. if (getKind() == DependentSequence) {
  6578. // If the declaration is a non-dependent, incomplete array type
  6579. // that has an initializer, then its type will be completed once
  6580. // the initializer is instantiated.
  6581. if (ResultType && !Entity.getType()->isDependentType() &&
  6582. Args.size() == 1) {
  6583. QualType DeclType = Entity.getType();
  6584. if (const IncompleteArrayType *ArrayT
  6585. = S.Context.getAsIncompleteArrayType(DeclType)) {
  6586. // FIXME: We don't currently have the ability to accurately
  6587. // compute the length of an initializer list without
  6588. // performing full type-checking of the initializer list
  6589. // (since we have to determine where braces are implicitly
  6590. // introduced and such). So, we fall back to making the array
  6591. // type a dependently-sized array type with no specified
  6592. // bound.
  6593. if (isa<InitListExpr>((Expr *)Args[0])) {
  6594. SourceRange Brackets;
  6595. // Scavange the location of the brackets from the entity, if we can.
  6596. if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
  6597. if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
  6598. TypeLoc TL = TInfo->getTypeLoc();
  6599. if (IncompleteArrayTypeLoc ArrayLoc =
  6600. TL.getAs<IncompleteArrayTypeLoc>())
  6601. Brackets = ArrayLoc.getBracketsRange();
  6602. }
  6603. }
  6604. *ResultType
  6605. = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
  6606. /*NumElts=*/nullptr,
  6607. ArrayT->getSizeModifier(),
  6608. ArrayT->getIndexTypeCVRQualifiers(),
  6609. Brackets);
  6610. }
  6611. }
  6612. }
  6613. if (Kind.getKind() == InitializationKind::IK_Direct &&
  6614. !Kind.isExplicitCast()) {
  6615. // Rebuild the ParenListExpr.
  6616. SourceRange ParenRange = Kind.getParenOrBraceRange();
  6617. return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
  6618. Args);
  6619. }
  6620. assert(Kind.getKind() == InitializationKind::IK_Copy ||
  6621. Kind.isExplicitCast() ||
  6622. Kind.getKind() == InitializationKind::IK_DirectList);
  6623. return ExprResult(Args[0]);
  6624. }
  6625. // No steps means no initialization.
  6626. if (Steps.empty())
  6627. return ExprResult((Expr *)nullptr);
  6628. if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
  6629. Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  6630. !Entity.isParameterKind()) {
  6631. // Produce a C++98 compatibility warning if we are initializing a reference
  6632. // from an initializer list. For parameters, we produce a better warning
  6633. // elsewhere.
  6634. Expr *Init = Args[0];
  6635. S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
  6636. << Init->getSourceRange();
  6637. }
  6638. // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
  6639. QualType ETy = Entity.getType();
  6640. Qualifiers TyQualifiers = ETy.getQualifiers();
  6641. bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
  6642. TyQualifiers.getAddressSpace() == LangAS::opencl_global;
  6643. if (S.getLangOpts().OpenCLVersion >= 200 &&
  6644. ETy->isAtomicType() && !HasGlobalAS &&
  6645. Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
  6646. S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
  6647. << 1
  6648. << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
  6649. return ExprError();
  6650. }
  6651. QualType DestType = Entity.getType().getNonReferenceType();
  6652. // FIXME: Ugly hack around the fact that Entity.getType() is not
  6653. // the same as Entity.getDecl()->getType() in cases involving type merging,
  6654. // and we want latter when it makes sense.
  6655. if (ResultType)
  6656. *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
  6657. Entity.getType();
  6658. ExprResult CurInit((Expr *)nullptr);
  6659. SmallVector<Expr*, 4> ArrayLoopCommonExprs;
  6660. // For initialization steps that start with a single initializer,
  6661. // grab the only argument out the Args and place it into the "current"
  6662. // initializer.
  6663. switch (Steps.front().Kind) {
  6664. case SK_ResolveAddressOfOverloadedFunction:
  6665. case SK_CastDerivedToBaseRValue:
  6666. case SK_CastDerivedToBaseXValue:
  6667. case SK_CastDerivedToBaseLValue:
  6668. case SK_BindReference:
  6669. case SK_BindReferenceToTemporary:
  6670. case SK_FinalCopy:
  6671. case SK_ExtraneousCopyToTemporary:
  6672. case SK_UserConversion:
  6673. case SK_QualificationConversionLValue:
  6674. case SK_QualificationConversionXValue:
  6675. case SK_QualificationConversionRValue:
  6676. case SK_AtomicConversion:
  6677. case SK_ConversionSequence:
  6678. case SK_ConversionSequenceNoNarrowing:
  6679. case SK_ListInitialization:
  6680. case SK_UnwrapInitList:
  6681. case SK_RewrapInitList:
  6682. case SK_CAssignment:
  6683. case SK_StringInit:
  6684. case SK_ObjCObjectConversion:
  6685. case SK_ArrayLoopIndex:
  6686. case SK_ArrayLoopInit:
  6687. case SK_ArrayInit:
  6688. case SK_GNUArrayInit:
  6689. case SK_ParenthesizedArrayInit:
  6690. case SK_PassByIndirectCopyRestore:
  6691. case SK_PassByIndirectRestore:
  6692. case SK_ProduceObjCObject:
  6693. case SK_StdInitializerList:
  6694. case SK_OCLSamplerInit:
  6695. case SK_OCLZeroOpaqueType: {
  6696. assert(Args.size() == 1);
  6697. CurInit = Args[0];
  6698. if (!CurInit.get()) return ExprError();
  6699. break;
  6700. }
  6701. case SK_ConstructorInitialization:
  6702. case SK_ConstructorInitializationFromList:
  6703. case SK_StdInitializerListConstructorCall:
  6704. case SK_ZeroInitialization:
  6705. break;
  6706. }
  6707. // Promote from an unevaluated context to an unevaluated list context in
  6708. // C++11 list-initialization; we need to instantiate entities usable in
  6709. // constant expressions here in order to perform narrowing checks =(
  6710. EnterExpressionEvaluationContext Evaluated(
  6711. S, EnterExpressionEvaluationContext::InitList,
  6712. CurInit.get() && isa<InitListExpr>(CurInit.get()));
  6713. // C++ [class.abstract]p2:
  6714. // no objects of an abstract class can be created except as subobjects
  6715. // of a class derived from it
  6716. auto checkAbstractType = [&](QualType T) -> bool {
  6717. if (Entity.getKind() == InitializedEntity::EK_Base ||
  6718. Entity.getKind() == InitializedEntity::EK_Delegating)
  6719. return false;
  6720. return S.RequireNonAbstractType(Kind.getLocation(), T,
  6721. diag::err_allocation_of_abstract_type);
  6722. };
  6723. // Walk through the computed steps for the initialization sequence,
  6724. // performing the specified conversions along the way.
  6725. bool ConstructorInitRequiresZeroInit = false;
  6726. for (step_iterator Step = step_begin(), StepEnd = step_end();
  6727. Step != StepEnd; ++Step) {
  6728. if (CurInit.isInvalid())
  6729. return ExprError();
  6730. QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
  6731. switch (Step->Kind) {
  6732. case SK_ResolveAddressOfOverloadedFunction:
  6733. // Overload resolution determined which function invoke; update the
  6734. // initializer to reflect that choice.
  6735. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
  6736. if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
  6737. return ExprError();
  6738. CurInit = S.FixOverloadedFunctionReference(CurInit,
  6739. Step->Function.FoundDecl,
  6740. Step->Function.Function);
  6741. break;
  6742. case SK_CastDerivedToBaseRValue:
  6743. case SK_CastDerivedToBaseXValue:
  6744. case SK_CastDerivedToBaseLValue: {
  6745. // We have a derived-to-base cast that produces either an rvalue or an
  6746. // lvalue. Perform that cast.
  6747. CXXCastPath BasePath;
  6748. // Casts to inaccessible base classes are allowed with C-style casts.
  6749. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
  6750. if (S.CheckDerivedToBaseConversion(
  6751. SourceType, Step->Type, CurInit.get()->getBeginLoc(),
  6752. CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
  6753. return ExprError();
  6754. ExprValueKind VK =
  6755. Step->Kind == SK_CastDerivedToBaseLValue ?
  6756. VK_LValue :
  6757. (Step->Kind == SK_CastDerivedToBaseXValue ?
  6758. VK_XValue :
  6759. VK_RValue);
  6760. CurInit =
  6761. ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
  6762. CurInit.get(), &BasePath, VK);
  6763. break;
  6764. }
  6765. case SK_BindReference:
  6766. // Reference binding does not have any corresponding ASTs.
  6767. // Check exception specifications
  6768. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  6769. return ExprError();
  6770. // We don't check for e.g. function pointers here, since address
  6771. // availability checks should only occur when the function first decays
  6772. // into a pointer or reference.
  6773. if (CurInit.get()->getType()->isFunctionProtoType()) {
  6774. if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
  6775. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  6776. if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  6777. DRE->getBeginLoc()))
  6778. return ExprError();
  6779. }
  6780. }
  6781. }
  6782. CheckForNullPointerDereference(S, CurInit.get());
  6783. break;
  6784. case SK_BindReferenceToTemporary: {
  6785. // Make sure the "temporary" is actually an rvalue.
  6786. assert(CurInit.get()->isRValue() && "not a temporary");
  6787. // Check exception specifications
  6788. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  6789. return ExprError();
  6790. // Materialize the temporary into memory.
  6791. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  6792. Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
  6793. CurInit = MTE;
  6794. // If we're extending this temporary to automatic storage duration -- we
  6795. // need to register its cleanup during the full-expression's cleanups.
  6796. if (MTE->getStorageDuration() == SD_Automatic &&
  6797. MTE->getType().isDestructedType())
  6798. S.Cleanup.setExprNeedsCleanups(true);
  6799. break;
  6800. }
  6801. case SK_FinalCopy:
  6802. if (checkAbstractType(Step->Type))
  6803. return ExprError();
  6804. // If the overall initialization is initializing a temporary, we already
  6805. // bound our argument if it was necessary to do so. If not (if we're
  6806. // ultimately initializing a non-temporary), our argument needs to be
  6807. // bound since it's initializing a function parameter.
  6808. // FIXME: This is a mess. Rationalize temporary destruction.
  6809. if (!shouldBindAsTemporary(Entity))
  6810. CurInit = S.MaybeBindToTemporary(CurInit.get());
  6811. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  6812. /*IsExtraneousCopy=*/false);
  6813. break;
  6814. case SK_ExtraneousCopyToTemporary:
  6815. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  6816. /*IsExtraneousCopy=*/true);
  6817. break;
  6818. case SK_UserConversion: {
  6819. // We have a user-defined conversion that invokes either a constructor
  6820. // or a conversion function.
  6821. CastKind CastKind;
  6822. FunctionDecl *Fn = Step->Function.Function;
  6823. DeclAccessPair FoundFn = Step->Function.FoundDecl;
  6824. bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
  6825. bool CreatedObject = false;
  6826. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
  6827. // Build a call to the selected constructor.
  6828. SmallVector<Expr*, 8> ConstructorArgs;
  6829. SourceLocation Loc = CurInit.get()->getBeginLoc();
  6830. // Determine the arguments required to actually perform the constructor
  6831. // call.
  6832. Expr *Arg = CurInit.get();
  6833. if (S.CompleteConstructorCall(Constructor,
  6834. MultiExprArg(&Arg, 1),
  6835. Loc, ConstructorArgs))
  6836. return ExprError();
  6837. // Build an expression that constructs a temporary.
  6838. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
  6839. FoundFn, Constructor,
  6840. ConstructorArgs,
  6841. HadMultipleCandidates,
  6842. /*ListInit*/ false,
  6843. /*StdInitListInit*/ false,
  6844. /*ZeroInit*/ false,
  6845. CXXConstructExpr::CK_Complete,
  6846. SourceRange());
  6847. if (CurInit.isInvalid())
  6848. return ExprError();
  6849. S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
  6850. Entity);
  6851. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  6852. return ExprError();
  6853. CastKind = CK_ConstructorConversion;
  6854. CreatedObject = true;
  6855. } else {
  6856. // Build a call to the conversion function.
  6857. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
  6858. S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
  6859. FoundFn);
  6860. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  6861. return ExprError();
  6862. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
  6863. HadMultipleCandidates);
  6864. if (CurInit.isInvalid())
  6865. return ExprError();
  6866. CastKind = CK_UserDefinedConversion;
  6867. CreatedObject = Conversion->getReturnType()->isRecordType();
  6868. }
  6869. if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
  6870. return ExprError();
  6871. CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
  6872. CastKind, CurInit.get(), nullptr,
  6873. CurInit.get()->getValueKind());
  6874. if (shouldBindAsTemporary(Entity))
  6875. // The overall entity is temporary, so this expression should be
  6876. // destroyed at the end of its full-expression.
  6877. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  6878. else if (CreatedObject && shouldDestroyEntity(Entity)) {
  6879. // The object outlasts the full-expression, but we need to prepare for
  6880. // a destructor being run on it.
  6881. // FIXME: It makes no sense to do this here. This should happen
  6882. // regardless of how we initialized the entity.
  6883. QualType T = CurInit.get()->getType();
  6884. if (const RecordType *Record = T->getAs<RecordType>()) {
  6885. CXXDestructorDecl *Destructor
  6886. = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
  6887. S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
  6888. S.PDiag(diag::err_access_dtor_temp) << T);
  6889. S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
  6890. if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
  6891. return ExprError();
  6892. }
  6893. }
  6894. break;
  6895. }
  6896. case SK_QualificationConversionLValue:
  6897. case SK_QualificationConversionXValue:
  6898. case SK_QualificationConversionRValue: {
  6899. // Perform a qualification conversion; these can never go wrong.
  6900. ExprValueKind VK =
  6901. Step->Kind == SK_QualificationConversionLValue
  6902. ? VK_LValue
  6903. : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
  6904. : VK_RValue);
  6905. CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
  6906. break;
  6907. }
  6908. case SK_AtomicConversion: {
  6909. assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
  6910. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  6911. CK_NonAtomicToAtomic, VK_RValue);
  6912. break;
  6913. }
  6914. case SK_ConversionSequence:
  6915. case SK_ConversionSequenceNoNarrowing: {
  6916. if (const auto *FromPtrType =
  6917. CurInit.get()->getType()->getAs<PointerType>()) {
  6918. if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
  6919. if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  6920. !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  6921. S.Diag(CurInit.get()->getExprLoc(),
  6922. diag::warn_noderef_to_dereferenceable_pointer)
  6923. << CurInit.get()->getSourceRange();
  6924. }
  6925. }
  6926. }
  6927. Sema::CheckedConversionKind CCK
  6928. = Kind.isCStyleCast()? Sema::CCK_CStyleCast
  6929. : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
  6930. : Kind.isExplicitCast()? Sema::CCK_OtherCast
  6931. : Sema::CCK_ImplicitConversion;
  6932. ExprResult CurInitExprRes =
  6933. S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
  6934. getAssignmentAction(Entity), CCK);
  6935. if (CurInitExprRes.isInvalid())
  6936. return ExprError();
  6937. S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
  6938. CurInit = CurInitExprRes;
  6939. if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
  6940. S.getLangOpts().CPlusPlus)
  6941. DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
  6942. CurInit.get());
  6943. break;
  6944. }
  6945. case SK_ListInitialization: {
  6946. if (checkAbstractType(Step->Type))
  6947. return ExprError();
  6948. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  6949. // If we're not initializing the top-level entity, we need to create an
  6950. // InitializeTemporary entity for our target type.
  6951. QualType Ty = Step->Type;
  6952. bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
  6953. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
  6954. InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
  6955. InitListChecker PerformInitList(S, InitEntity,
  6956. InitList, Ty, /*VerifyOnly=*/false,
  6957. /*TreatUnavailableAsInvalid=*/false);
  6958. if (PerformInitList.HadError())
  6959. return ExprError();
  6960. // Hack: We must update *ResultType if available in order to set the
  6961. // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  6962. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  6963. if (ResultType &&
  6964. ResultType->getNonReferenceType()->isIncompleteArrayType()) {
  6965. if ((*ResultType)->isRValueReferenceType())
  6966. Ty = S.Context.getRValueReferenceType(Ty);
  6967. else if ((*ResultType)->isLValueReferenceType())
  6968. Ty = S.Context.getLValueReferenceType(Ty,
  6969. (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
  6970. *ResultType = Ty;
  6971. }
  6972. InitListExpr *StructuredInitList =
  6973. PerformInitList.getFullyStructuredList();
  6974. CurInit.get();
  6975. CurInit = shouldBindAsTemporary(InitEntity)
  6976. ? S.MaybeBindToTemporary(StructuredInitList)
  6977. : StructuredInitList;
  6978. break;
  6979. }
  6980. case SK_ConstructorInitializationFromList: {
  6981. if (checkAbstractType(Step->Type))
  6982. return ExprError();
  6983. // When an initializer list is passed for a parameter of type "reference
  6984. // to object", we don't get an EK_Temporary entity, but instead an
  6985. // EK_Parameter entity with reference type.
  6986. // FIXME: This is a hack. What we really should do is create a user
  6987. // conversion step for this case, but this makes it considerably more
  6988. // complicated. For now, this will do.
  6989. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  6990. Entity.getType().getNonReferenceType());
  6991. bool UseTemporary = Entity.getType()->isReferenceType();
  6992. assert(Args.size() == 1 && "expected a single argument for list init");
  6993. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  6994. S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
  6995. << InitList->getSourceRange();
  6996. MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
  6997. CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
  6998. Entity,
  6999. Kind, Arg, *Step,
  7000. ConstructorInitRequiresZeroInit,
  7001. /*IsListInitialization*/true,
  7002. /*IsStdInitListInit*/false,
  7003. InitList->getLBraceLoc(),
  7004. InitList->getRBraceLoc());
  7005. break;
  7006. }
  7007. case SK_UnwrapInitList:
  7008. CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
  7009. break;
  7010. case SK_RewrapInitList: {
  7011. Expr *E = CurInit.get();
  7012. InitListExpr *Syntactic = Step->WrappingSyntacticList;
  7013. InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
  7014. Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
  7015. ILE->setSyntacticForm(Syntactic);
  7016. ILE->setType(E->getType());
  7017. ILE->setValueKind(E->getValueKind());
  7018. CurInit = ILE;
  7019. break;
  7020. }
  7021. case SK_ConstructorInitialization:
  7022. case SK_StdInitializerListConstructorCall: {
  7023. if (checkAbstractType(Step->Type))
  7024. return ExprError();
  7025. // When an initializer list is passed for a parameter of type "reference
  7026. // to object", we don't get an EK_Temporary entity, but instead an
  7027. // EK_Parameter entity with reference type.
  7028. // FIXME: This is a hack. What we really should do is create a user
  7029. // conversion step for this case, but this makes it considerably more
  7030. // complicated. For now, this will do.
  7031. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  7032. Entity.getType().getNonReferenceType());
  7033. bool UseTemporary = Entity.getType()->isReferenceType();
  7034. bool IsStdInitListInit =
  7035. Step->Kind == SK_StdInitializerListConstructorCall;
  7036. Expr *Source = CurInit.get();
  7037. SourceRange Range = Kind.hasParenOrBraceRange()
  7038. ? Kind.getParenOrBraceRange()
  7039. : SourceRange();
  7040. CurInit = PerformConstructorInitialization(
  7041. S, UseTemporary ? TempEntity : Entity, Kind,
  7042. Source ? MultiExprArg(Source) : Args, *Step,
  7043. ConstructorInitRequiresZeroInit,
  7044. /*IsListInitialization*/ IsStdInitListInit,
  7045. /*IsStdInitListInitialization*/ IsStdInitListInit,
  7046. /*LBraceLoc*/ Range.getBegin(),
  7047. /*RBraceLoc*/ Range.getEnd());
  7048. break;
  7049. }
  7050. case SK_ZeroInitialization: {
  7051. step_iterator NextStep = Step;
  7052. ++NextStep;
  7053. if (NextStep != StepEnd &&
  7054. (NextStep->Kind == SK_ConstructorInitialization ||
  7055. NextStep->Kind == SK_ConstructorInitializationFromList)) {
  7056. // The need for zero-initialization is recorded directly into
  7057. // the call to the object's constructor within the next step.
  7058. ConstructorInitRequiresZeroInit = true;
  7059. } else if (Kind.getKind() == InitializationKind::IK_Value &&
  7060. S.getLangOpts().CPlusPlus &&
  7061. !Kind.isImplicitValueInit()) {
  7062. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  7063. if (!TSInfo)
  7064. TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
  7065. Kind.getRange().getBegin());
  7066. CurInit = new (S.Context) CXXScalarValueInitExpr(
  7067. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  7068. Kind.getRange().getEnd());
  7069. } else {
  7070. CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
  7071. }
  7072. break;
  7073. }
  7074. case SK_CAssignment: {
  7075. QualType SourceType = CurInit.get()->getType();
  7076. // Save off the initial CurInit in case we need to emit a diagnostic
  7077. ExprResult InitialCurInit = CurInit;
  7078. ExprResult Result = CurInit;
  7079. Sema::AssignConvertType ConvTy =
  7080. S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
  7081. Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
  7082. if (Result.isInvalid())
  7083. return ExprError();
  7084. CurInit = Result;
  7085. // If this is a call, allow conversion to a transparent union.
  7086. ExprResult CurInitExprRes = CurInit;
  7087. if (ConvTy != Sema::Compatible &&
  7088. Entity.isParameterKind() &&
  7089. S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
  7090. == Sema::Compatible)
  7091. ConvTy = Sema::Compatible;
  7092. if (CurInitExprRes.isInvalid())
  7093. return ExprError();
  7094. CurInit = CurInitExprRes;
  7095. bool Complained;
  7096. if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
  7097. Step->Type, SourceType,
  7098. InitialCurInit.get(),
  7099. getAssignmentAction(Entity, true),
  7100. &Complained)) {
  7101. PrintInitLocationNote(S, Entity);
  7102. return ExprError();
  7103. } else if (Complained)
  7104. PrintInitLocationNote(S, Entity);
  7105. break;
  7106. }
  7107. case SK_StringInit: {
  7108. QualType Ty = Step->Type;
  7109. CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
  7110. S.Context.getAsArrayType(Ty), S);
  7111. break;
  7112. }
  7113. case SK_ObjCObjectConversion:
  7114. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7115. CK_ObjCObjectLValueCast,
  7116. CurInit.get()->getValueKind());
  7117. break;
  7118. case SK_ArrayLoopIndex: {
  7119. Expr *Cur = CurInit.get();
  7120. Expr *BaseExpr = new (S.Context)
  7121. OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
  7122. Cur->getValueKind(), Cur->getObjectKind(), Cur);
  7123. Expr *IndexExpr =
  7124. new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
  7125. CurInit = S.CreateBuiltinArraySubscriptExpr(
  7126. BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
  7127. ArrayLoopCommonExprs.push_back(BaseExpr);
  7128. break;
  7129. }
  7130. case SK_ArrayLoopInit: {
  7131. assert(!ArrayLoopCommonExprs.empty() &&
  7132. "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
  7133. Expr *Common = ArrayLoopCommonExprs.pop_back_val();
  7134. CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
  7135. CurInit.get());
  7136. break;
  7137. }
  7138. case SK_GNUArrayInit:
  7139. // Okay: we checked everything before creating this step. Note that
  7140. // this is a GNU extension.
  7141. S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
  7142. << Step->Type << CurInit.get()->getType()
  7143. << CurInit.get()->getSourceRange();
  7144. updateGNUCompoundLiteralRValue(CurInit.get());
  7145. LLVM_FALLTHROUGH;
  7146. case SK_ArrayInit:
  7147. // If the destination type is an incomplete array type, update the
  7148. // type accordingly.
  7149. if (ResultType) {
  7150. if (const IncompleteArrayType *IncompleteDest
  7151. = S.Context.getAsIncompleteArrayType(Step->Type)) {
  7152. if (const ConstantArrayType *ConstantSource
  7153. = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
  7154. *ResultType = S.Context.getConstantArrayType(
  7155. IncompleteDest->getElementType(),
  7156. ConstantSource->getSize(),
  7157. ArrayType::Normal, 0);
  7158. }
  7159. }
  7160. }
  7161. break;
  7162. case SK_ParenthesizedArrayInit:
  7163. // Okay: we checked everything before creating this step. Note that
  7164. // this is a GNU extension.
  7165. S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
  7166. << CurInit.get()->getSourceRange();
  7167. break;
  7168. case SK_PassByIndirectCopyRestore:
  7169. case SK_PassByIndirectRestore:
  7170. checkIndirectCopyRestoreSource(S, CurInit.get());
  7171. CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
  7172. CurInit.get(), Step->Type,
  7173. Step->Kind == SK_PassByIndirectCopyRestore);
  7174. break;
  7175. case SK_ProduceObjCObject:
  7176. CurInit =
  7177. ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
  7178. CurInit.get(), nullptr, VK_RValue);
  7179. break;
  7180. case SK_StdInitializerList: {
  7181. S.Diag(CurInit.get()->getExprLoc(),
  7182. diag::warn_cxx98_compat_initializer_list_init)
  7183. << CurInit.get()->getSourceRange();
  7184. // Materialize the temporary into memory.
  7185. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  7186. CurInit.get()->getType(), CurInit.get(),
  7187. /*BoundToLvalueReference=*/false);
  7188. // Wrap it in a construction of a std::initializer_list<T>.
  7189. CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
  7190. // Bind the result, in case the library has given initializer_list a
  7191. // non-trivial destructor.
  7192. if (shouldBindAsTemporary(Entity))
  7193. CurInit = S.MaybeBindToTemporary(CurInit.get());
  7194. break;
  7195. }
  7196. case SK_OCLSamplerInit: {
  7197. // Sampler initialization have 5 cases:
  7198. // 1. function argument passing
  7199. // 1a. argument is a file-scope variable
  7200. // 1b. argument is a function-scope variable
  7201. // 1c. argument is one of caller function's parameters
  7202. // 2. variable initialization
  7203. // 2a. initializing a file-scope variable
  7204. // 2b. initializing a function-scope variable
  7205. //
  7206. // For file-scope variables, since they cannot be initialized by function
  7207. // call of __translate_sampler_initializer in LLVM IR, their references
  7208. // need to be replaced by a cast from their literal initializers to
  7209. // sampler type. Since sampler variables can only be used in function
  7210. // calls as arguments, we only need to replace them when handling the
  7211. // argument passing.
  7212. assert(Step->Type->isSamplerT() &&
  7213. "Sampler initialization on non-sampler type.");
  7214. Expr *Init = CurInit.get();
  7215. QualType SourceType = Init->getType();
  7216. // Case 1
  7217. if (Entity.isParameterKind()) {
  7218. if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
  7219. S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
  7220. << SourceType;
  7221. break;
  7222. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
  7223. auto Var = cast<VarDecl>(DRE->getDecl());
  7224. // Case 1b and 1c
  7225. // No cast from integer to sampler is needed.
  7226. if (!Var->hasGlobalStorage()) {
  7227. CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
  7228. CK_LValueToRValue, Init,
  7229. /*BasePath=*/nullptr, VK_RValue);
  7230. break;
  7231. }
  7232. // Case 1a
  7233. // For function call with a file-scope sampler variable as argument,
  7234. // get the integer literal.
  7235. // Do not diagnose if the file-scope variable does not have initializer
  7236. // since this has already been diagnosed when parsing the variable
  7237. // declaration.
  7238. if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
  7239. break;
  7240. Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
  7241. Var->getInit()))->getSubExpr();
  7242. SourceType = Init->getType();
  7243. }
  7244. } else {
  7245. // Case 2
  7246. // Check initializer is 32 bit integer constant.
  7247. // If the initializer is taken from global variable, do not diagnose since
  7248. // this has already been done when parsing the variable declaration.
  7249. if (!Init->isConstantInitializer(S.Context, false))
  7250. break;
  7251. if (!SourceType->isIntegerType() ||
  7252. 32 != S.Context.getIntWidth(SourceType)) {
  7253. S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
  7254. << SourceType;
  7255. break;
  7256. }
  7257. Expr::EvalResult EVResult;
  7258. Init->EvaluateAsInt(EVResult, S.Context);
  7259. llvm::APSInt Result = EVResult.Val.getInt();
  7260. const uint64_t SamplerValue = Result.getLimitedValue();
  7261. // 32-bit value of sampler's initializer is interpreted as
  7262. // bit-field with the following structure:
  7263. // |unspecified|Filter|Addressing Mode| Normalized Coords|
  7264. // |31 6|5 4|3 1| 0|
  7265. // This structure corresponds to enum values of sampler properties
  7266. // defined in SPIR spec v1.2 and also opencl-c.h
  7267. unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
  7268. unsigned FilterMode = (0x30 & SamplerValue) >> 4;
  7269. if (FilterMode != 1 && FilterMode != 2 &&
  7270. !S.getOpenCLOptions().isEnabled(
  7271. "cl_intel_device_side_avc_motion_estimation"))
  7272. S.Diag(Kind.getLocation(),
  7273. diag::warn_sampler_initializer_invalid_bits)
  7274. << "Filter Mode";
  7275. if (AddressingMode > 4)
  7276. S.Diag(Kind.getLocation(),
  7277. diag::warn_sampler_initializer_invalid_bits)
  7278. << "Addressing Mode";
  7279. }
  7280. // Cases 1a, 2a and 2b
  7281. // Insert cast from integer to sampler.
  7282. CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
  7283. CK_IntToOCLSampler);
  7284. break;
  7285. }
  7286. case SK_OCLZeroOpaqueType: {
  7287. assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
  7288. Step->Type->isOCLIntelSubgroupAVCType()) &&
  7289. "Wrong type for initialization of OpenCL opaque type.");
  7290. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7291. CK_ZeroToOCLOpaqueType,
  7292. CurInit.get()->getValueKind());
  7293. break;
  7294. }
  7295. }
  7296. }
  7297. // Check whether the initializer has a shorter lifetime than the initialized
  7298. // entity, and if not, either lifetime-extend or warn as appropriate.
  7299. if (auto *Init = CurInit.get())
  7300. S.checkInitializerLifetime(Entity, Init);
  7301. // Diagnose non-fatal problems with the completed initialization.
  7302. if (Entity.getKind() == InitializedEntity::EK_Member &&
  7303. cast<FieldDecl>(Entity.getDecl())->isBitField())
  7304. S.CheckBitFieldInitialization(Kind.getLocation(),
  7305. cast<FieldDecl>(Entity.getDecl()),
  7306. CurInit.get());
  7307. // Check for std::move on construction.
  7308. if (const Expr *E = CurInit.get()) {
  7309. CheckMoveOnConstruction(S, E,
  7310. Entity.getKind() == InitializedEntity::EK_Result);
  7311. }
  7312. return CurInit;
  7313. }
  7314. /// Somewhere within T there is an uninitialized reference subobject.
  7315. /// Dig it out and diagnose it.
  7316. static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
  7317. QualType T) {
  7318. if (T->isReferenceType()) {
  7319. S.Diag(Loc, diag::err_reference_without_init)
  7320. << T.getNonReferenceType();
  7321. return true;
  7322. }
  7323. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  7324. if (!RD || !RD->hasUninitializedReferenceMember())
  7325. return false;
  7326. for (const auto *FI : RD->fields()) {
  7327. if (FI->isUnnamedBitfield())
  7328. continue;
  7329. if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
  7330. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  7331. return true;
  7332. }
  7333. }
  7334. for (const auto &BI : RD->bases()) {
  7335. if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
  7336. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  7337. return true;
  7338. }
  7339. }
  7340. return false;
  7341. }
  7342. //===----------------------------------------------------------------------===//
  7343. // Diagnose initialization failures
  7344. //===----------------------------------------------------------------------===//
  7345. /// Emit notes associated with an initialization that failed due to a
  7346. /// "simple" conversion failure.
  7347. static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
  7348. Expr *op) {
  7349. QualType destType = entity.getType();
  7350. if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
  7351. op->getType()->isObjCObjectPointerType()) {
  7352. // Emit a possible note about the conversion failing because the
  7353. // operand is a message send with a related result type.
  7354. S.EmitRelatedResultTypeNote(op);
  7355. // Emit a possible note about a return failing because we're
  7356. // expecting a related result type.
  7357. if (entity.getKind() == InitializedEntity::EK_Result)
  7358. S.EmitRelatedResultTypeNoteForReturn(destType);
  7359. }
  7360. }
  7361. static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
  7362. InitListExpr *InitList) {
  7363. QualType DestType = Entity.getType();
  7364. QualType E;
  7365. if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
  7366. QualType ArrayType = S.Context.getConstantArrayType(
  7367. E.withConst(),
  7368. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  7369. InitList->getNumInits()),
  7370. clang::ArrayType::Normal, 0);
  7371. InitializedEntity HiddenArray =
  7372. InitializedEntity::InitializeTemporary(ArrayType);
  7373. return diagnoseListInit(S, HiddenArray, InitList);
  7374. }
  7375. if (DestType->isReferenceType()) {
  7376. // A list-initialization failure for a reference means that we tried to
  7377. // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
  7378. // inner initialization failed.
  7379. QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
  7380. diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
  7381. SourceLocation Loc = InitList->getBeginLoc();
  7382. if (auto *D = Entity.getDecl())
  7383. Loc = D->getLocation();
  7384. S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
  7385. return;
  7386. }
  7387. InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
  7388. /*VerifyOnly=*/false,
  7389. /*TreatUnavailableAsInvalid=*/false);
  7390. assert(DiagnoseInitList.HadError() &&
  7391. "Inconsistent init list check result.");
  7392. }
  7393. bool InitializationSequence::Diagnose(Sema &S,
  7394. const InitializedEntity &Entity,
  7395. const InitializationKind &Kind,
  7396. ArrayRef<Expr *> Args) {
  7397. if (!Failed())
  7398. return false;
  7399. // When we want to diagnose only one element of a braced-init-list,
  7400. // we need to factor it out.
  7401. Expr *OnlyArg;
  7402. if (Args.size() == 1) {
  7403. auto *List = dyn_cast<InitListExpr>(Args[0]);
  7404. if (List && List->getNumInits() == 1)
  7405. OnlyArg = List->getInit(0);
  7406. else
  7407. OnlyArg = Args[0];
  7408. }
  7409. else
  7410. OnlyArg = nullptr;
  7411. QualType DestType = Entity.getType();
  7412. switch (Failure) {
  7413. case FK_TooManyInitsForReference:
  7414. // FIXME: Customize for the initialized entity?
  7415. if (Args.empty()) {
  7416. // Dig out the reference subobject which is uninitialized and diagnose it.
  7417. // If this is value-initialization, this could be nested some way within
  7418. // the target type.
  7419. assert(Kind.getKind() == InitializationKind::IK_Value ||
  7420. DestType->isReferenceType());
  7421. bool Diagnosed =
  7422. DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
  7423. assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
  7424. (void)Diagnosed;
  7425. } else // FIXME: diagnostic below could be better!
  7426. S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
  7427. << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  7428. break;
  7429. case FK_ParenthesizedListInitForReference:
  7430. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  7431. << 1 << Entity.getType() << Args[0]->getSourceRange();
  7432. break;
  7433. case FK_ArrayNeedsInitList:
  7434. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
  7435. break;
  7436. case FK_ArrayNeedsInitListOrStringLiteral:
  7437. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
  7438. break;
  7439. case FK_ArrayNeedsInitListOrWideStringLiteral:
  7440. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
  7441. break;
  7442. case FK_NarrowStringIntoWideCharArray:
  7443. S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
  7444. break;
  7445. case FK_WideStringIntoCharArray:
  7446. S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
  7447. break;
  7448. case FK_IncompatWideStringIntoWideChar:
  7449. S.Diag(Kind.getLocation(),
  7450. diag::err_array_init_incompat_wide_string_into_wchar);
  7451. break;
  7452. case FK_PlainStringIntoUTF8Char:
  7453. S.Diag(Kind.getLocation(),
  7454. diag::err_array_init_plain_string_into_char8_t);
  7455. S.Diag(Args.front()->getBeginLoc(),
  7456. diag::note_array_init_plain_string_into_char8_t)
  7457. << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
  7458. break;
  7459. case FK_UTF8StringIntoPlainChar:
  7460. S.Diag(Kind.getLocation(),
  7461. diag::err_array_init_utf8_string_into_char)
  7462. << S.getLangOpts().CPlusPlus2a;
  7463. break;
  7464. case FK_ArrayTypeMismatch:
  7465. case FK_NonConstantArrayInit:
  7466. S.Diag(Kind.getLocation(),
  7467. (Failure == FK_ArrayTypeMismatch
  7468. ? diag::err_array_init_different_type
  7469. : diag::err_array_init_non_constant_array))
  7470. << DestType.getNonReferenceType()
  7471. << OnlyArg->getType()
  7472. << Args[0]->getSourceRange();
  7473. break;
  7474. case FK_VariableLengthArrayHasInitializer:
  7475. S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
  7476. << Args[0]->getSourceRange();
  7477. break;
  7478. case FK_AddressOfOverloadFailed: {
  7479. DeclAccessPair Found;
  7480. S.ResolveAddressOfOverloadedFunction(OnlyArg,
  7481. DestType.getNonReferenceType(),
  7482. true,
  7483. Found);
  7484. break;
  7485. }
  7486. case FK_AddressOfUnaddressableFunction: {
  7487. auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
  7488. S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  7489. OnlyArg->getBeginLoc());
  7490. break;
  7491. }
  7492. case FK_ReferenceInitOverloadFailed:
  7493. case FK_UserConversionOverloadFailed:
  7494. switch (FailedOverloadResult) {
  7495. case OR_Ambiguous:
  7496. FailedCandidateSet.NoteCandidates(
  7497. PartialDiagnosticAt(
  7498. Kind.getLocation(),
  7499. Failure == FK_UserConversionOverloadFailed
  7500. ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
  7501. << OnlyArg->getType() << DestType
  7502. << Args[0]->getSourceRange())
  7503. : (S.PDiag(diag::err_ref_init_ambiguous)
  7504. << DestType << OnlyArg->getType()
  7505. << Args[0]->getSourceRange())),
  7506. S, OCD_ViableCandidates, Args);
  7507. break;
  7508. case OR_No_Viable_Function: {
  7509. auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
  7510. if (!S.RequireCompleteType(Kind.getLocation(),
  7511. DestType.getNonReferenceType(),
  7512. diag::err_typecheck_nonviable_condition_incomplete,
  7513. OnlyArg->getType(), Args[0]->getSourceRange()))
  7514. S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
  7515. << (Entity.getKind() == InitializedEntity::EK_Result)
  7516. << OnlyArg->getType() << Args[0]->getSourceRange()
  7517. << DestType.getNonReferenceType();
  7518. FailedCandidateSet.NoteCandidates(S, Args, Cands);
  7519. break;
  7520. }
  7521. case OR_Deleted: {
  7522. S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
  7523. << OnlyArg->getType() << DestType.getNonReferenceType()
  7524. << Args[0]->getSourceRange();
  7525. OverloadCandidateSet::iterator Best;
  7526. OverloadingResult Ovl
  7527. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  7528. if (Ovl == OR_Deleted) {
  7529. S.NoteDeletedFunction(Best->Function);
  7530. } else {
  7531. llvm_unreachable("Inconsistent overload resolution?");
  7532. }
  7533. break;
  7534. }
  7535. case OR_Success:
  7536. llvm_unreachable("Conversion did not fail!");
  7537. }
  7538. break;
  7539. case FK_NonConstLValueReferenceBindingToTemporary:
  7540. if (isa<InitListExpr>(Args[0])) {
  7541. S.Diag(Kind.getLocation(),
  7542. diag::err_lvalue_reference_bind_to_initlist)
  7543. << DestType.getNonReferenceType().isVolatileQualified()
  7544. << DestType.getNonReferenceType()
  7545. << Args[0]->getSourceRange();
  7546. break;
  7547. }
  7548. LLVM_FALLTHROUGH;
  7549. case FK_NonConstLValueReferenceBindingToUnrelated:
  7550. S.Diag(Kind.getLocation(),
  7551. Failure == FK_NonConstLValueReferenceBindingToTemporary
  7552. ? diag::err_lvalue_reference_bind_to_temporary
  7553. : diag::err_lvalue_reference_bind_to_unrelated)
  7554. << DestType.getNonReferenceType().isVolatileQualified()
  7555. << DestType.getNonReferenceType()
  7556. << OnlyArg->getType()
  7557. << Args[0]->getSourceRange();
  7558. break;
  7559. case FK_NonConstLValueReferenceBindingToBitfield: {
  7560. // We don't necessarily have an unambiguous source bit-field.
  7561. FieldDecl *BitField = Args[0]->getSourceBitField();
  7562. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
  7563. << DestType.isVolatileQualified()
  7564. << (BitField ? BitField->getDeclName() : DeclarationName())
  7565. << (BitField != nullptr)
  7566. << Args[0]->getSourceRange();
  7567. if (BitField)
  7568. S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
  7569. break;
  7570. }
  7571. case FK_NonConstLValueReferenceBindingToVectorElement:
  7572. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
  7573. << DestType.isVolatileQualified()
  7574. << Args[0]->getSourceRange();
  7575. break;
  7576. case FK_RValueReferenceBindingToLValue:
  7577. S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
  7578. << DestType.getNonReferenceType() << OnlyArg->getType()
  7579. << Args[0]->getSourceRange();
  7580. break;
  7581. case FK_ReferenceAddrspaceMismatchTemporary:
  7582. S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
  7583. << DestType << Args[0]->getSourceRange();
  7584. break;
  7585. case FK_ReferenceInitDropsQualifiers: {
  7586. QualType SourceType = OnlyArg->getType();
  7587. QualType NonRefType = DestType.getNonReferenceType();
  7588. Qualifiers DroppedQualifiers =
  7589. SourceType.getQualifiers() - NonRefType.getQualifiers();
  7590. if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
  7591. SourceType.getQualifiers()))
  7592. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  7593. << NonRefType << SourceType << 1 /*addr space*/
  7594. << Args[0]->getSourceRange();
  7595. else
  7596. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  7597. << NonRefType << SourceType << 0 /*cv quals*/
  7598. << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
  7599. << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
  7600. break;
  7601. }
  7602. case FK_ReferenceInitFailed:
  7603. S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
  7604. << DestType.getNonReferenceType()
  7605. << DestType.getNonReferenceType()->isIncompleteType()
  7606. << OnlyArg->isLValue()
  7607. << OnlyArg->getType()
  7608. << Args[0]->getSourceRange();
  7609. emitBadConversionNotes(S, Entity, Args[0]);
  7610. break;
  7611. case FK_ConversionFailed: {
  7612. QualType FromType = OnlyArg->getType();
  7613. PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
  7614. << (int)Entity.getKind()
  7615. << DestType
  7616. << OnlyArg->isLValue()
  7617. << FromType
  7618. << Args[0]->getSourceRange();
  7619. S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
  7620. S.Diag(Kind.getLocation(), PDiag);
  7621. emitBadConversionNotes(S, Entity, Args[0]);
  7622. break;
  7623. }
  7624. case FK_ConversionFromPropertyFailed:
  7625. // No-op. This error has already been reported.
  7626. break;
  7627. case FK_TooManyInitsForScalar: {
  7628. SourceRange R;
  7629. auto *InitList = dyn_cast<InitListExpr>(Args[0]);
  7630. if (InitList && InitList->getNumInits() >= 1) {
  7631. R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
  7632. } else {
  7633. assert(Args.size() > 1 && "Expected multiple initializers!");
  7634. R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
  7635. }
  7636. R.setBegin(S.getLocForEndOfToken(R.getBegin()));
  7637. if (Kind.isCStyleOrFunctionalCast())
  7638. S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
  7639. << R;
  7640. else
  7641. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  7642. << /*scalar=*/2 << R;
  7643. break;
  7644. }
  7645. case FK_ParenthesizedListInitForScalar:
  7646. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  7647. << 0 << Entity.getType() << Args[0]->getSourceRange();
  7648. break;
  7649. case FK_ReferenceBindingToInitList:
  7650. S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
  7651. << DestType.getNonReferenceType() << Args[0]->getSourceRange();
  7652. break;
  7653. case FK_InitListBadDestinationType:
  7654. S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
  7655. << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
  7656. break;
  7657. case FK_ListConstructorOverloadFailed:
  7658. case FK_ConstructorOverloadFailed: {
  7659. SourceRange ArgsRange;
  7660. if (Args.size())
  7661. ArgsRange =
  7662. SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  7663. if (Failure == FK_ListConstructorOverloadFailed) {
  7664. assert(Args.size() == 1 &&
  7665. "List construction from other than 1 argument.");
  7666. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  7667. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  7668. }
  7669. // FIXME: Using "DestType" for the entity we're printing is probably
  7670. // bad.
  7671. switch (FailedOverloadResult) {
  7672. case OR_Ambiguous:
  7673. FailedCandidateSet.NoteCandidates(
  7674. PartialDiagnosticAt(Kind.getLocation(),
  7675. S.PDiag(diag::err_ovl_ambiguous_init)
  7676. << DestType << ArgsRange),
  7677. S, OCD_ViableCandidates, Args);
  7678. break;
  7679. case OR_No_Viable_Function:
  7680. if (Kind.getKind() == InitializationKind::IK_Default &&
  7681. (Entity.getKind() == InitializedEntity::EK_Base ||
  7682. Entity.getKind() == InitializedEntity::EK_Member) &&
  7683. isa<CXXConstructorDecl>(S.CurContext)) {
  7684. // This is implicit default initialization of a member or
  7685. // base within a constructor. If no viable function was
  7686. // found, notify the user that they need to explicitly
  7687. // initialize this base/member.
  7688. CXXConstructorDecl *Constructor
  7689. = cast<CXXConstructorDecl>(S.CurContext);
  7690. const CXXRecordDecl *InheritedFrom = nullptr;
  7691. if (auto Inherited = Constructor->getInheritedConstructor())
  7692. InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
  7693. if (Entity.getKind() == InitializedEntity::EK_Base) {
  7694. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  7695. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  7696. << S.Context.getTypeDeclType(Constructor->getParent())
  7697. << /*base=*/0
  7698. << Entity.getType()
  7699. << InheritedFrom;
  7700. RecordDecl *BaseDecl
  7701. = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
  7702. ->getDecl();
  7703. S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  7704. << S.Context.getTagDeclType(BaseDecl);
  7705. } else {
  7706. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  7707. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  7708. << S.Context.getTypeDeclType(Constructor->getParent())
  7709. << /*member=*/1
  7710. << Entity.getName()
  7711. << InheritedFrom;
  7712. S.Diag(Entity.getDecl()->getLocation(),
  7713. diag::note_member_declared_at);
  7714. if (const RecordType *Record
  7715. = Entity.getType()->getAs<RecordType>())
  7716. S.Diag(Record->getDecl()->getLocation(),
  7717. diag::note_previous_decl)
  7718. << S.Context.getTagDeclType(Record->getDecl());
  7719. }
  7720. break;
  7721. }
  7722. FailedCandidateSet.NoteCandidates(
  7723. PartialDiagnosticAt(
  7724. Kind.getLocation(),
  7725. S.PDiag(diag::err_ovl_no_viable_function_in_init)
  7726. << DestType << ArgsRange),
  7727. S, OCD_AllCandidates, Args);
  7728. break;
  7729. case OR_Deleted: {
  7730. OverloadCandidateSet::iterator Best;
  7731. OverloadingResult Ovl
  7732. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  7733. if (Ovl != OR_Deleted) {
  7734. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  7735. << DestType << ArgsRange;
  7736. llvm_unreachable("Inconsistent overload resolution?");
  7737. break;
  7738. }
  7739. // If this is a defaulted or implicitly-declared function, then
  7740. // it was implicitly deleted. Make it clear that the deletion was
  7741. // implicit.
  7742. if (S.isImplicitlyDeleted(Best->Function))
  7743. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
  7744. << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
  7745. << DestType << ArgsRange;
  7746. else
  7747. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  7748. << DestType << ArgsRange;
  7749. S.NoteDeletedFunction(Best->Function);
  7750. break;
  7751. }
  7752. case OR_Success:
  7753. llvm_unreachable("Conversion did not fail!");
  7754. }
  7755. }
  7756. break;
  7757. case FK_DefaultInitOfConst:
  7758. if (Entity.getKind() == InitializedEntity::EK_Member &&
  7759. isa<CXXConstructorDecl>(S.CurContext)) {
  7760. // This is implicit default-initialization of a const member in
  7761. // a constructor. Complain that it needs to be explicitly
  7762. // initialized.
  7763. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
  7764. S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
  7765. << (Constructor->getInheritedConstructor() ? 2 :
  7766. Constructor->isImplicit() ? 1 : 0)
  7767. << S.Context.getTypeDeclType(Constructor->getParent())
  7768. << /*const=*/1
  7769. << Entity.getName();
  7770. S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
  7771. << Entity.getName();
  7772. } else {
  7773. S.Diag(Kind.getLocation(), diag::err_default_init_const)
  7774. << DestType << (bool)DestType->getAs<RecordType>();
  7775. }
  7776. break;
  7777. case FK_Incomplete:
  7778. S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
  7779. diag::err_init_incomplete_type);
  7780. break;
  7781. case FK_ListInitializationFailed: {
  7782. // Run the init list checker again to emit diagnostics.
  7783. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  7784. diagnoseListInit(S, Entity, InitList);
  7785. break;
  7786. }
  7787. case FK_PlaceholderType: {
  7788. // FIXME: Already diagnosed!
  7789. break;
  7790. }
  7791. case FK_ExplicitConstructor: {
  7792. S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
  7793. << Args[0]->getSourceRange();
  7794. OverloadCandidateSet::iterator Best;
  7795. OverloadingResult Ovl
  7796. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  7797. (void)Ovl;
  7798. assert(Ovl == OR_Success && "Inconsistent overload resolution");
  7799. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  7800. S.Diag(CtorDecl->getLocation(),
  7801. diag::note_explicit_ctor_deduction_guide_here) << false;
  7802. break;
  7803. }
  7804. }
  7805. PrintInitLocationNote(S, Entity);
  7806. return true;
  7807. }
  7808. void InitializationSequence::dump(raw_ostream &OS) const {
  7809. switch (SequenceKind) {
  7810. case FailedSequence: {
  7811. OS << "Failed sequence: ";
  7812. switch (Failure) {
  7813. case FK_TooManyInitsForReference:
  7814. OS << "too many initializers for reference";
  7815. break;
  7816. case FK_ParenthesizedListInitForReference:
  7817. OS << "parenthesized list init for reference";
  7818. break;
  7819. case FK_ArrayNeedsInitList:
  7820. OS << "array requires initializer list";
  7821. break;
  7822. case FK_AddressOfUnaddressableFunction:
  7823. OS << "address of unaddressable function was taken";
  7824. break;
  7825. case FK_ArrayNeedsInitListOrStringLiteral:
  7826. OS << "array requires initializer list or string literal";
  7827. break;
  7828. case FK_ArrayNeedsInitListOrWideStringLiteral:
  7829. OS << "array requires initializer list or wide string literal";
  7830. break;
  7831. case FK_NarrowStringIntoWideCharArray:
  7832. OS << "narrow string into wide char array";
  7833. break;
  7834. case FK_WideStringIntoCharArray:
  7835. OS << "wide string into char array";
  7836. break;
  7837. case FK_IncompatWideStringIntoWideChar:
  7838. OS << "incompatible wide string into wide char array";
  7839. break;
  7840. case FK_PlainStringIntoUTF8Char:
  7841. OS << "plain string literal into char8_t array";
  7842. break;
  7843. case FK_UTF8StringIntoPlainChar:
  7844. OS << "u8 string literal into char array";
  7845. break;
  7846. case FK_ArrayTypeMismatch:
  7847. OS << "array type mismatch";
  7848. break;
  7849. case FK_NonConstantArrayInit:
  7850. OS << "non-constant array initializer";
  7851. break;
  7852. case FK_AddressOfOverloadFailed:
  7853. OS << "address of overloaded function failed";
  7854. break;
  7855. case FK_ReferenceInitOverloadFailed:
  7856. OS << "overload resolution for reference initialization failed";
  7857. break;
  7858. case FK_NonConstLValueReferenceBindingToTemporary:
  7859. OS << "non-const lvalue reference bound to temporary";
  7860. break;
  7861. case FK_NonConstLValueReferenceBindingToBitfield:
  7862. OS << "non-const lvalue reference bound to bit-field";
  7863. break;
  7864. case FK_NonConstLValueReferenceBindingToVectorElement:
  7865. OS << "non-const lvalue reference bound to vector element";
  7866. break;
  7867. case FK_NonConstLValueReferenceBindingToUnrelated:
  7868. OS << "non-const lvalue reference bound to unrelated type";
  7869. break;
  7870. case FK_RValueReferenceBindingToLValue:
  7871. OS << "rvalue reference bound to an lvalue";
  7872. break;
  7873. case FK_ReferenceInitDropsQualifiers:
  7874. OS << "reference initialization drops qualifiers";
  7875. break;
  7876. case FK_ReferenceAddrspaceMismatchTemporary:
  7877. OS << "reference with mismatching address space bound to temporary";
  7878. break;
  7879. case FK_ReferenceInitFailed:
  7880. OS << "reference initialization failed";
  7881. break;
  7882. case FK_ConversionFailed:
  7883. OS << "conversion failed";
  7884. break;
  7885. case FK_ConversionFromPropertyFailed:
  7886. OS << "conversion from property failed";
  7887. break;
  7888. case FK_TooManyInitsForScalar:
  7889. OS << "too many initializers for scalar";
  7890. break;
  7891. case FK_ParenthesizedListInitForScalar:
  7892. OS << "parenthesized list init for reference";
  7893. break;
  7894. case FK_ReferenceBindingToInitList:
  7895. OS << "referencing binding to initializer list";
  7896. break;
  7897. case FK_InitListBadDestinationType:
  7898. OS << "initializer list for non-aggregate, non-scalar type";
  7899. break;
  7900. case FK_UserConversionOverloadFailed:
  7901. OS << "overloading failed for user-defined conversion";
  7902. break;
  7903. case FK_ConstructorOverloadFailed:
  7904. OS << "constructor overloading failed";
  7905. break;
  7906. case FK_DefaultInitOfConst:
  7907. OS << "default initialization of a const variable";
  7908. break;
  7909. case FK_Incomplete:
  7910. OS << "initialization of incomplete type";
  7911. break;
  7912. case FK_ListInitializationFailed:
  7913. OS << "list initialization checker failure";
  7914. break;
  7915. case FK_VariableLengthArrayHasInitializer:
  7916. OS << "variable length array has an initializer";
  7917. break;
  7918. case FK_PlaceholderType:
  7919. OS << "initializer expression isn't contextually valid";
  7920. break;
  7921. case FK_ListConstructorOverloadFailed:
  7922. OS << "list constructor overloading failed";
  7923. break;
  7924. case FK_ExplicitConstructor:
  7925. OS << "list copy initialization chose explicit constructor";
  7926. break;
  7927. }
  7928. OS << '\n';
  7929. return;
  7930. }
  7931. case DependentSequence:
  7932. OS << "Dependent sequence\n";
  7933. return;
  7934. case NormalSequence:
  7935. OS << "Normal sequence: ";
  7936. break;
  7937. }
  7938. for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
  7939. if (S != step_begin()) {
  7940. OS << " -> ";
  7941. }
  7942. switch (S->Kind) {
  7943. case SK_ResolveAddressOfOverloadedFunction:
  7944. OS << "resolve address of overloaded function";
  7945. break;
  7946. case SK_CastDerivedToBaseRValue:
  7947. OS << "derived-to-base (rvalue)";
  7948. break;
  7949. case SK_CastDerivedToBaseXValue:
  7950. OS << "derived-to-base (xvalue)";
  7951. break;
  7952. case SK_CastDerivedToBaseLValue:
  7953. OS << "derived-to-base (lvalue)";
  7954. break;
  7955. case SK_BindReference:
  7956. OS << "bind reference to lvalue";
  7957. break;
  7958. case SK_BindReferenceToTemporary:
  7959. OS << "bind reference to a temporary";
  7960. break;
  7961. case SK_FinalCopy:
  7962. OS << "final copy in class direct-initialization";
  7963. break;
  7964. case SK_ExtraneousCopyToTemporary:
  7965. OS << "extraneous C++03 copy to temporary";
  7966. break;
  7967. case SK_UserConversion:
  7968. OS << "user-defined conversion via " << *S->Function.Function;
  7969. break;
  7970. case SK_QualificationConversionRValue:
  7971. OS << "qualification conversion (rvalue)";
  7972. break;
  7973. case SK_QualificationConversionXValue:
  7974. OS << "qualification conversion (xvalue)";
  7975. break;
  7976. case SK_QualificationConversionLValue:
  7977. OS << "qualification conversion (lvalue)";
  7978. break;
  7979. case SK_AtomicConversion:
  7980. OS << "non-atomic-to-atomic conversion";
  7981. break;
  7982. case SK_ConversionSequence:
  7983. OS << "implicit conversion sequence (";
  7984. S->ICS->dump(); // FIXME: use OS
  7985. OS << ")";
  7986. break;
  7987. case SK_ConversionSequenceNoNarrowing:
  7988. OS << "implicit conversion sequence with narrowing prohibited (";
  7989. S->ICS->dump(); // FIXME: use OS
  7990. OS << ")";
  7991. break;
  7992. case SK_ListInitialization:
  7993. OS << "list aggregate initialization";
  7994. break;
  7995. case SK_UnwrapInitList:
  7996. OS << "unwrap reference initializer list";
  7997. break;
  7998. case SK_RewrapInitList:
  7999. OS << "rewrap reference initializer list";
  8000. break;
  8001. case SK_ConstructorInitialization:
  8002. OS << "constructor initialization";
  8003. break;
  8004. case SK_ConstructorInitializationFromList:
  8005. OS << "list initialization via constructor";
  8006. break;
  8007. case SK_ZeroInitialization:
  8008. OS << "zero initialization";
  8009. break;
  8010. case SK_CAssignment:
  8011. OS << "C assignment";
  8012. break;
  8013. case SK_StringInit:
  8014. OS << "string initialization";
  8015. break;
  8016. case SK_ObjCObjectConversion:
  8017. OS << "Objective-C object conversion";
  8018. break;
  8019. case SK_ArrayLoopIndex:
  8020. OS << "indexing for array initialization loop";
  8021. break;
  8022. case SK_ArrayLoopInit:
  8023. OS << "array initialization loop";
  8024. break;
  8025. case SK_ArrayInit:
  8026. OS << "array initialization";
  8027. break;
  8028. case SK_GNUArrayInit:
  8029. OS << "array initialization (GNU extension)";
  8030. break;
  8031. case SK_ParenthesizedArrayInit:
  8032. OS << "parenthesized array initialization";
  8033. break;
  8034. case SK_PassByIndirectCopyRestore:
  8035. OS << "pass by indirect copy and restore";
  8036. break;
  8037. case SK_PassByIndirectRestore:
  8038. OS << "pass by indirect restore";
  8039. break;
  8040. case SK_ProduceObjCObject:
  8041. OS << "Objective-C object retension";
  8042. break;
  8043. case SK_StdInitializerList:
  8044. OS << "std::initializer_list from initializer list";
  8045. break;
  8046. case SK_StdInitializerListConstructorCall:
  8047. OS << "list initialization from std::initializer_list";
  8048. break;
  8049. case SK_OCLSamplerInit:
  8050. OS << "OpenCL sampler_t from integer constant";
  8051. break;
  8052. case SK_OCLZeroOpaqueType:
  8053. OS << "OpenCL opaque type from zero";
  8054. break;
  8055. }
  8056. OS << " [" << S->Type.getAsString() << ']';
  8057. }
  8058. OS << '\n';
  8059. }
  8060. void InitializationSequence::dump() const {
  8061. dump(llvm::errs());
  8062. }
  8063. static bool NarrowingErrs(const LangOptions &L) {
  8064. return L.CPlusPlus11 &&
  8065. (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
  8066. }
  8067. static void DiagnoseNarrowingInInitList(Sema &S,
  8068. const ImplicitConversionSequence &ICS,
  8069. QualType PreNarrowingType,
  8070. QualType EntityType,
  8071. const Expr *PostInit) {
  8072. const StandardConversionSequence *SCS = nullptr;
  8073. switch (ICS.getKind()) {
  8074. case ImplicitConversionSequence::StandardConversion:
  8075. SCS = &ICS.Standard;
  8076. break;
  8077. case ImplicitConversionSequence::UserDefinedConversion:
  8078. SCS = &ICS.UserDefined.After;
  8079. break;
  8080. case ImplicitConversionSequence::AmbiguousConversion:
  8081. case ImplicitConversionSequence::EllipsisConversion:
  8082. case ImplicitConversionSequence::BadConversion:
  8083. return;
  8084. }
  8085. // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
  8086. APValue ConstantValue;
  8087. QualType ConstantType;
  8088. switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
  8089. ConstantType)) {
  8090. case NK_Not_Narrowing:
  8091. case NK_Dependent_Narrowing:
  8092. // No narrowing occurred.
  8093. return;
  8094. case NK_Type_Narrowing:
  8095. // This was a floating-to-integer conversion, which is always considered a
  8096. // narrowing conversion even if the value is a constant and can be
  8097. // represented exactly as an integer.
  8098. S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
  8099. ? diag::ext_init_list_type_narrowing
  8100. : diag::warn_init_list_type_narrowing)
  8101. << PostInit->getSourceRange()
  8102. << PreNarrowingType.getLocalUnqualifiedType()
  8103. << EntityType.getLocalUnqualifiedType();
  8104. break;
  8105. case NK_Constant_Narrowing:
  8106. // A constant value was narrowed.
  8107. S.Diag(PostInit->getBeginLoc(),
  8108. NarrowingErrs(S.getLangOpts())
  8109. ? diag::ext_init_list_constant_narrowing
  8110. : diag::warn_init_list_constant_narrowing)
  8111. << PostInit->getSourceRange()
  8112. << ConstantValue.getAsString(S.getASTContext(), ConstantType)
  8113. << EntityType.getLocalUnqualifiedType();
  8114. break;
  8115. case NK_Variable_Narrowing:
  8116. // A variable's value may have been narrowed.
  8117. S.Diag(PostInit->getBeginLoc(),
  8118. NarrowingErrs(S.getLangOpts())
  8119. ? diag::ext_init_list_variable_narrowing
  8120. : diag::warn_init_list_variable_narrowing)
  8121. << PostInit->getSourceRange()
  8122. << PreNarrowingType.getLocalUnqualifiedType()
  8123. << EntityType.getLocalUnqualifiedType();
  8124. break;
  8125. }
  8126. SmallString<128> StaticCast;
  8127. llvm::raw_svector_ostream OS(StaticCast);
  8128. OS << "static_cast<";
  8129. if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
  8130. // It's important to use the typedef's name if there is one so that the
  8131. // fixit doesn't break code using types like int64_t.
  8132. //
  8133. // FIXME: This will break if the typedef requires qualification. But
  8134. // getQualifiedNameAsString() includes non-machine-parsable components.
  8135. OS << *TT->getDecl();
  8136. } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
  8137. OS << BT->getName(S.getLangOpts());
  8138. else {
  8139. // Oops, we didn't find the actual type of the variable. Don't emit a fixit
  8140. // with a broken cast.
  8141. return;
  8142. }
  8143. OS << ">(";
  8144. S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
  8145. << PostInit->getSourceRange()
  8146. << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
  8147. << FixItHint::CreateInsertion(
  8148. S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
  8149. }
  8150. //===----------------------------------------------------------------------===//
  8151. // Initialization helper functions
  8152. //===----------------------------------------------------------------------===//
  8153. bool
  8154. Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
  8155. ExprResult Init) {
  8156. if (Init.isInvalid())
  8157. return false;
  8158. Expr *InitE = Init.get();
  8159. assert(InitE && "No initialization expression");
  8160. InitializationKind Kind =
  8161. InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
  8162. InitializationSequence Seq(*this, Entity, Kind, InitE);
  8163. return !Seq.Failed();
  8164. }
  8165. ExprResult
  8166. Sema::PerformCopyInitialization(const InitializedEntity &Entity,
  8167. SourceLocation EqualLoc,
  8168. ExprResult Init,
  8169. bool TopLevelOfInitList,
  8170. bool AllowExplicit) {
  8171. if (Init.isInvalid())
  8172. return ExprError();
  8173. Expr *InitE = Init.get();
  8174. assert(InitE && "No initialization expression?");
  8175. if (EqualLoc.isInvalid())
  8176. EqualLoc = InitE->getBeginLoc();
  8177. InitializationKind Kind = InitializationKind::CreateCopy(
  8178. InitE->getBeginLoc(), EqualLoc, AllowExplicit);
  8179. InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
  8180. // Prevent infinite recursion when performing parameter copy-initialization.
  8181. const bool ShouldTrackCopy =
  8182. Entity.isParameterKind() && Seq.isConstructorInitialization();
  8183. if (ShouldTrackCopy) {
  8184. if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
  8185. CurrentParameterCopyTypes.end()) {
  8186. Seq.SetOverloadFailure(
  8187. InitializationSequence::FK_ConstructorOverloadFailed,
  8188. OR_No_Viable_Function);
  8189. // Try to give a meaningful diagnostic note for the problematic
  8190. // constructor.
  8191. const auto LastStep = Seq.step_end() - 1;
  8192. assert(LastStep->Kind ==
  8193. InitializationSequence::SK_ConstructorInitialization);
  8194. const FunctionDecl *Function = LastStep->Function.Function;
  8195. auto Candidate =
  8196. llvm::find_if(Seq.getFailedCandidateSet(),
  8197. [Function](const OverloadCandidate &Candidate) -> bool {
  8198. return Candidate.Viable &&
  8199. Candidate.Function == Function &&
  8200. Candidate.Conversions.size() > 0;
  8201. });
  8202. if (Candidate != Seq.getFailedCandidateSet().end() &&
  8203. Function->getNumParams() > 0) {
  8204. Candidate->Viable = false;
  8205. Candidate->FailureKind = ovl_fail_bad_conversion;
  8206. Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
  8207. InitE,
  8208. Function->getParamDecl(0)->getType());
  8209. }
  8210. }
  8211. CurrentParameterCopyTypes.push_back(Entity.getType());
  8212. }
  8213. ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
  8214. if (ShouldTrackCopy)
  8215. CurrentParameterCopyTypes.pop_back();
  8216. return Result;
  8217. }
  8218. /// Determine whether RD is, or is derived from, a specialization of CTD.
  8219. static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
  8220. ClassTemplateDecl *CTD) {
  8221. auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
  8222. auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
  8223. return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
  8224. };
  8225. return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
  8226. }
  8227. QualType Sema::DeduceTemplateSpecializationFromInitializer(
  8228. TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
  8229. const InitializationKind &Kind, MultiExprArg Inits) {
  8230. auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
  8231. TSInfo->getType()->getContainedDeducedType());
  8232. assert(DeducedTST && "not a deduced template specialization type");
  8233. auto TemplateName = DeducedTST->getTemplateName();
  8234. if (TemplateName.isDependent())
  8235. return Context.DependentTy;
  8236. // We can only perform deduction for class templates.
  8237. auto *Template =
  8238. dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
  8239. if (!Template) {
  8240. Diag(Kind.getLocation(),
  8241. diag::err_deduced_non_class_template_specialization_type)
  8242. << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
  8243. if (auto *TD = TemplateName.getAsTemplateDecl())
  8244. Diag(TD->getLocation(), diag::note_template_decl_here);
  8245. return QualType();
  8246. }
  8247. // Can't deduce from dependent arguments.
  8248. if (Expr::hasAnyTypeDependentArguments(Inits)) {
  8249. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8250. diag::warn_cxx14_compat_class_template_argument_deduction)
  8251. << TSInfo->getTypeLoc().getSourceRange() << 0;
  8252. return Context.DependentTy;
  8253. }
  8254. // FIXME: Perform "exact type" matching first, per CWG discussion?
  8255. // Or implement this via an implied 'T(T) -> T' deduction guide?
  8256. // FIXME: Do we need/want a std::initializer_list<T> special case?
  8257. // Look up deduction guides, including those synthesized from constructors.
  8258. //
  8259. // C++1z [over.match.class.deduct]p1:
  8260. // A set of functions and function templates is formed comprising:
  8261. // - For each constructor of the class template designated by the
  8262. // template-name, a function template [...]
  8263. // - For each deduction-guide, a function or function template [...]
  8264. DeclarationNameInfo NameInfo(
  8265. Context.DeclarationNames.getCXXDeductionGuideName(Template),
  8266. TSInfo->getTypeLoc().getEndLoc());
  8267. LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
  8268. LookupQualifiedName(Guides, Template->getDeclContext());
  8269. // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
  8270. // clear on this, but they're not found by name so access does not apply.
  8271. Guides.suppressDiagnostics();
  8272. // Figure out if this is list-initialization.
  8273. InitListExpr *ListInit =
  8274. (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
  8275. ? dyn_cast<InitListExpr>(Inits[0])
  8276. : nullptr;
  8277. // C++1z [over.match.class.deduct]p1:
  8278. // Initialization and overload resolution are performed as described in
  8279. // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
  8280. // (as appropriate for the type of initialization performed) for an object
  8281. // of a hypothetical class type, where the selected functions and function
  8282. // templates are considered to be the constructors of that class type
  8283. //
  8284. // Since we know we're initializing a class type of a type unrelated to that
  8285. // of the initializer, this reduces to something fairly reasonable.
  8286. OverloadCandidateSet Candidates(Kind.getLocation(),
  8287. OverloadCandidateSet::CSK_Normal);
  8288. OverloadCandidateSet::iterator Best;
  8289. bool HasAnyDeductionGuide = false;
  8290. bool AllowExplicit = !Kind.isCopyInit() || ListInit;
  8291. auto tryToResolveOverload =
  8292. [&](bool OnlyListConstructors) -> OverloadingResult {
  8293. Candidates.clear(OverloadCandidateSet::CSK_Normal);
  8294. HasAnyDeductionGuide = false;
  8295. for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
  8296. NamedDecl *D = (*I)->getUnderlyingDecl();
  8297. if (D->isInvalidDecl())
  8298. continue;
  8299. auto *TD = dyn_cast<FunctionTemplateDecl>(D);
  8300. auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
  8301. TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
  8302. if (!GD)
  8303. continue;
  8304. if (!GD->isImplicit())
  8305. HasAnyDeductionGuide = true;
  8306. // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
  8307. // For copy-initialization, the candidate functions are all the
  8308. // converting constructors (12.3.1) of that class.
  8309. // C++ [over.match.copy]p1: (non-list copy-initialization from class)
  8310. // The converting constructors of T are candidate functions.
  8311. if (!AllowExplicit) {
  8312. // Only consider converting constructors.
  8313. if (GD->isExplicit())
  8314. continue;
  8315. // When looking for a converting constructor, deduction guides that
  8316. // could never be called with one argument are not interesting to
  8317. // check or note.
  8318. if (GD->getMinRequiredArguments() > 1 ||
  8319. (GD->getNumParams() == 0 && !GD->isVariadic()))
  8320. continue;
  8321. }
  8322. // C++ [over.match.list]p1.1: (first phase list initialization)
  8323. // Initially, the candidate functions are the initializer-list
  8324. // constructors of the class T
  8325. if (OnlyListConstructors && !isInitListConstructor(GD))
  8326. continue;
  8327. // C++ [over.match.list]p1.2: (second phase list initialization)
  8328. // the candidate functions are all the constructors of the class T
  8329. // C++ [over.match.ctor]p1: (all other cases)
  8330. // the candidate functions are all the constructors of the class of
  8331. // the object being initialized
  8332. // C++ [over.best.ics]p4:
  8333. // When [...] the constructor [...] is a candidate by
  8334. // - [over.match.copy] (in all cases)
  8335. // FIXME: The "second phase of [over.match.list] case can also
  8336. // theoretically happen here, but it's not clear whether we can
  8337. // ever have a parameter of the right type.
  8338. bool SuppressUserConversions = Kind.isCopyInit();
  8339. if (TD)
  8340. AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
  8341. Inits, Candidates, SuppressUserConversions,
  8342. /*PartialOverloading*/ false,
  8343. AllowExplicit);
  8344. else
  8345. AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
  8346. SuppressUserConversions,
  8347. /*PartialOverloading*/ false, AllowExplicit);
  8348. }
  8349. return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
  8350. };
  8351. OverloadingResult Result = OR_No_Viable_Function;
  8352. // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
  8353. // try initializer-list constructors.
  8354. if (ListInit) {
  8355. bool TryListConstructors = true;
  8356. // Try list constructors unless the list is empty and the class has one or
  8357. // more default constructors, in which case those constructors win.
  8358. if (!ListInit->getNumInits()) {
  8359. for (NamedDecl *D : Guides) {
  8360. auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
  8361. if (FD && FD->getMinRequiredArguments() == 0) {
  8362. TryListConstructors = false;
  8363. break;
  8364. }
  8365. }
  8366. } else if (ListInit->getNumInits() == 1) {
  8367. // C++ [over.match.class.deduct]:
  8368. // As an exception, the first phase in [over.match.list] (considering
  8369. // initializer-list constructors) is omitted if the initializer list
  8370. // consists of a single expression of type cv U, where U is a
  8371. // specialization of C or a class derived from a specialization of C.
  8372. Expr *E = ListInit->getInit(0);
  8373. auto *RD = E->getType()->getAsCXXRecordDecl();
  8374. if (!isa<InitListExpr>(E) && RD &&
  8375. isCompleteType(Kind.getLocation(), E->getType()) &&
  8376. isOrIsDerivedFromSpecializationOf(RD, Template))
  8377. TryListConstructors = false;
  8378. }
  8379. if (TryListConstructors)
  8380. Result = tryToResolveOverload(/*OnlyListConstructor*/true);
  8381. // Then unwrap the initializer list and try again considering all
  8382. // constructors.
  8383. Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
  8384. }
  8385. // If list-initialization fails, or if we're doing any other kind of
  8386. // initialization, we (eventually) consider constructors.
  8387. if (Result == OR_No_Viable_Function)
  8388. Result = tryToResolveOverload(/*OnlyListConstructor*/false);
  8389. switch (Result) {
  8390. case OR_Ambiguous:
  8391. // FIXME: For list-initialization candidates, it'd usually be better to
  8392. // list why they were not viable when given the initializer list itself as
  8393. // an argument.
  8394. Candidates.NoteCandidates(
  8395. PartialDiagnosticAt(
  8396. Kind.getLocation(),
  8397. PDiag(diag::err_deduced_class_template_ctor_ambiguous)
  8398. << TemplateName),
  8399. *this, OCD_ViableCandidates, Inits);
  8400. return QualType();
  8401. case OR_No_Viable_Function: {
  8402. CXXRecordDecl *Primary =
  8403. cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
  8404. bool Complete =
  8405. isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
  8406. Candidates.NoteCandidates(
  8407. PartialDiagnosticAt(
  8408. Kind.getLocation(),
  8409. PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
  8410. : diag::err_deduced_class_template_incomplete)
  8411. << TemplateName << !Guides.empty()),
  8412. *this, OCD_AllCandidates, Inits);
  8413. return QualType();
  8414. }
  8415. case OR_Deleted: {
  8416. Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
  8417. << TemplateName;
  8418. NoteDeletedFunction(Best->Function);
  8419. return QualType();
  8420. }
  8421. case OR_Success:
  8422. // C++ [over.match.list]p1:
  8423. // In copy-list-initialization, if an explicit constructor is chosen, the
  8424. // initialization is ill-formed.
  8425. if (Kind.isCopyInit() && ListInit &&
  8426. cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
  8427. bool IsDeductionGuide = !Best->Function->isImplicit();
  8428. Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
  8429. << TemplateName << IsDeductionGuide;
  8430. Diag(Best->Function->getLocation(),
  8431. diag::note_explicit_ctor_deduction_guide_here)
  8432. << IsDeductionGuide;
  8433. return QualType();
  8434. }
  8435. // Make sure we didn't select an unusable deduction guide, and mark it
  8436. // as referenced.
  8437. DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
  8438. MarkFunctionReferenced(Kind.getLocation(), Best->Function);
  8439. break;
  8440. }
  8441. // C++ [dcl.type.class.deduct]p1:
  8442. // The placeholder is replaced by the return type of the function selected
  8443. // by overload resolution for class template deduction.
  8444. QualType DeducedType =
  8445. SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
  8446. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8447. diag::warn_cxx14_compat_class_template_argument_deduction)
  8448. << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
  8449. // Warn if CTAD was used on a type that does not have any user-defined
  8450. // deduction guides.
  8451. if (!HasAnyDeductionGuide) {
  8452. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8453. diag::warn_ctad_maybe_unsupported)
  8454. << TemplateName;
  8455. Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
  8456. }
  8457. return DeducedType;
  8458. }