SemaInit.cpp 416 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594
  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/CharInfo.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Sema/Designator.h"
  22. #include "clang/Sema/Initialization.h"
  23. #include "clang/Sema/Lookup.h"
  24. #include "clang/Sema/SemaInternal.h"
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/ADT/PointerIntPair.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. using namespace clang;
  31. //===----------------------------------------------------------------------===//
  32. // Sema Initialization Checking
  33. //===----------------------------------------------------------------------===//
  34. /// Check whether T is compatible with a wide character type (wchar_t,
  35. /// char16_t or char32_t).
  36. static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
  37. if (Context.typesAreCompatible(Context.getWideCharType(), T))
  38. return true;
  39. if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
  40. return Context.typesAreCompatible(Context.Char16Ty, T) ||
  41. Context.typesAreCompatible(Context.Char32Ty, T);
  42. }
  43. return false;
  44. }
  45. enum StringInitFailureKind {
  46. SIF_None,
  47. SIF_NarrowStringIntoWideChar,
  48. SIF_WideStringIntoChar,
  49. SIF_IncompatWideStringIntoWideChar,
  50. SIF_UTF8StringIntoPlainChar,
  51. SIF_PlainStringIntoUTF8Char,
  52. SIF_Other
  53. };
  54. /// Check whether the array of type AT can be initialized by the Init
  55. /// expression by means of string initialization. Returns SIF_None if so,
  56. /// otherwise returns a StringInitFailureKind that describes why the
  57. /// initialization would not work.
  58. static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
  59. ASTContext &Context) {
  60. if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
  61. return SIF_Other;
  62. // See if this is a string literal or @encode.
  63. Init = Init->IgnoreParens();
  64. // Handle @encode, which is a narrow string.
  65. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
  66. return SIF_None;
  67. // Otherwise we can only handle string literals.
  68. StringLiteral *SL = dyn_cast<StringLiteral>(Init);
  69. if (!SL)
  70. return SIF_Other;
  71. const QualType ElemTy =
  72. Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
  73. auto IsCharOrUnsignedChar = [](const QualType &T) {
  74. const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
  75. return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
  76. };
  77. switch (SL->getKind()) {
  78. case StringLiteral::UTF8:
  79. // char8_t array can be initialized with a UTF-8 string.
  80. // - C++20 [dcl.init.string] (DR)
  81. // Additionally, an array of char or unsigned char may be initialized
  82. // by a UTF-8 string literal.
  83. if (ElemTy->isChar8Type() ||
  84. (Context.getLangOpts().Char8 &&
  85. IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
  86. return SIF_None;
  87. [[fallthrough]];
  88. case StringLiteral::Ordinary:
  89. // char array can be initialized with a narrow string.
  90. // Only allow char x[] = "foo"; not char x[] = L"foo";
  91. if (ElemTy->isCharType())
  92. return (SL->getKind() == StringLiteral::UTF8 &&
  93. Context.getLangOpts().Char8)
  94. ? SIF_UTF8StringIntoPlainChar
  95. : SIF_None;
  96. if (ElemTy->isChar8Type())
  97. return SIF_PlainStringIntoUTF8Char;
  98. if (IsWideCharCompatible(ElemTy, Context))
  99. return SIF_NarrowStringIntoWideChar;
  100. return SIF_Other;
  101. // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
  102. // "An array with element type compatible with a qualified or unqualified
  103. // version of wchar_t, char16_t, or char32_t may be initialized by a wide
  104. // string literal with the corresponding encoding prefix (L, u, or U,
  105. // respectively), optionally enclosed in braces.
  106. case StringLiteral::UTF16:
  107. if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
  108. return SIF_None;
  109. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  110. return SIF_WideStringIntoChar;
  111. if (IsWideCharCompatible(ElemTy, Context))
  112. return SIF_IncompatWideStringIntoWideChar;
  113. return SIF_Other;
  114. case StringLiteral::UTF32:
  115. if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
  116. return SIF_None;
  117. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  118. return SIF_WideStringIntoChar;
  119. if (IsWideCharCompatible(ElemTy, Context))
  120. return SIF_IncompatWideStringIntoWideChar;
  121. return SIF_Other;
  122. case StringLiteral::Wide:
  123. if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
  124. return SIF_None;
  125. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  126. return SIF_WideStringIntoChar;
  127. if (IsWideCharCompatible(ElemTy, Context))
  128. return SIF_IncompatWideStringIntoWideChar;
  129. return SIF_Other;
  130. }
  131. llvm_unreachable("missed a StringLiteral kind?");
  132. }
  133. static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
  134. ASTContext &Context) {
  135. const ArrayType *arrayType = Context.getAsArrayType(declType);
  136. if (!arrayType)
  137. return SIF_Other;
  138. return IsStringInit(init, arrayType, Context);
  139. }
  140. bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
  141. return ::IsStringInit(Init, AT, Context) == SIF_None;
  142. }
  143. /// Update the type of a string literal, including any surrounding parentheses,
  144. /// to match the type of the object which it is initializing.
  145. static void updateStringLiteralType(Expr *E, QualType Ty) {
  146. while (true) {
  147. E->setType(Ty);
  148. E->setValueKind(VK_PRValue);
  149. if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
  150. break;
  151. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  152. E = PE->getSubExpr();
  153. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  154. assert(UO->getOpcode() == UO_Extension);
  155. E = UO->getSubExpr();
  156. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  157. E = GSE->getResultExpr();
  158. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  159. E = CE->getChosenSubExpr();
  160. } else {
  161. llvm_unreachable("unexpected expr in string literal init");
  162. }
  163. }
  164. }
  165. /// Fix a compound literal initializing an array so it's correctly marked
  166. /// as an rvalue.
  167. static void updateGNUCompoundLiteralRValue(Expr *E) {
  168. while (true) {
  169. E->setValueKind(VK_PRValue);
  170. if (isa<CompoundLiteralExpr>(E)) {
  171. break;
  172. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  173. E = PE->getSubExpr();
  174. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  175. assert(UO->getOpcode() == UO_Extension);
  176. E = UO->getSubExpr();
  177. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  178. E = GSE->getResultExpr();
  179. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  180. E = CE->getChosenSubExpr();
  181. } else {
  182. llvm_unreachable("unexpected expr in array compound literal init");
  183. }
  184. }
  185. }
  186. static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
  187. Sema &S) {
  188. // Get the length of the string as parsed.
  189. auto *ConstantArrayTy =
  190. cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
  191. uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
  192. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  193. // C99 6.7.8p14. We have an array of character type with unknown size
  194. // being initialized to a string literal.
  195. llvm::APInt ConstVal(32, StrLength);
  196. // Return a new array type (C99 6.7.8p22).
  197. DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
  198. ConstVal, nullptr,
  199. ArrayType::Normal, 0);
  200. updateStringLiteralType(Str, DeclT);
  201. return;
  202. }
  203. const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
  204. // We have an array of character type with known size. However,
  205. // the size may be smaller or larger than the string we are initializing.
  206. // FIXME: Avoid truncation for 64-bit length strings.
  207. if (S.getLangOpts().CPlusPlus) {
  208. if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
  209. // For Pascal strings it's OK to strip off the terminating null character,
  210. // so the example below is valid:
  211. //
  212. // unsigned char a[2] = "\pa";
  213. if (SL->isPascal())
  214. StrLength--;
  215. }
  216. // [dcl.init.string]p2
  217. if (StrLength > CAT->getSize().getZExtValue())
  218. S.Diag(Str->getBeginLoc(),
  219. diag::err_initializer_string_for_char_array_too_long)
  220. << CAT->getSize().getZExtValue() << StrLength
  221. << Str->getSourceRange();
  222. } else {
  223. // C99 6.7.8p14.
  224. if (StrLength-1 > CAT->getSize().getZExtValue())
  225. S.Diag(Str->getBeginLoc(),
  226. diag::ext_initializer_string_for_char_array_too_long)
  227. << Str->getSourceRange();
  228. }
  229. // Set the type to the actual size that we are initializing. If we have
  230. // something like:
  231. // char x[1] = "foo";
  232. // then this will set the string literal's type to char[1].
  233. updateStringLiteralType(Str, DeclT);
  234. }
  235. //===----------------------------------------------------------------------===//
  236. // Semantic checking for initializer lists.
  237. //===----------------------------------------------------------------------===//
  238. namespace {
  239. /// Semantic checking for initializer lists.
  240. ///
  241. /// The InitListChecker class contains a set of routines that each
  242. /// handle the initialization of a certain kind of entity, e.g.,
  243. /// arrays, vectors, struct/union types, scalars, etc. The
  244. /// InitListChecker itself performs a recursive walk of the subobject
  245. /// structure of the type to be initialized, while stepping through
  246. /// the initializer list one element at a time. The IList and Index
  247. /// parameters to each of the Check* routines contain the active
  248. /// (syntactic) initializer list and the index into that initializer
  249. /// list that represents the current initializer. Each routine is
  250. /// responsible for moving that Index forward as it consumes elements.
  251. ///
  252. /// Each Check* routine also has a StructuredList/StructuredIndex
  253. /// arguments, which contains the current "structured" (semantic)
  254. /// initializer list and the index into that initializer list where we
  255. /// are copying initializers as we map them over to the semantic
  256. /// list. Once we have completed our recursive walk of the subobject
  257. /// structure, we will have constructed a full semantic initializer
  258. /// list.
  259. ///
  260. /// C99 designators cause changes in the initializer list traversal,
  261. /// because they make the initialization "jump" into a specific
  262. /// subobject and then continue the initialization from that
  263. /// point. CheckDesignatedInitializer() recursively steps into the
  264. /// designated subobject and manages backing out the recursion to
  265. /// initialize the subobjects after the one designated.
  266. ///
  267. /// If an initializer list contains any designators, we build a placeholder
  268. /// structured list even in 'verify only' mode, so that we can track which
  269. /// elements need 'empty' initializtion.
  270. class InitListChecker {
  271. Sema &SemaRef;
  272. bool hadError = false;
  273. bool VerifyOnly; // No diagnostics.
  274. bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
  275. bool InOverloadResolution;
  276. InitListExpr *FullyStructuredList = nullptr;
  277. NoInitExpr *DummyExpr = nullptr;
  278. NoInitExpr *getDummyInit() {
  279. if (!DummyExpr)
  280. DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
  281. return DummyExpr;
  282. }
  283. void CheckImplicitInitList(const InitializedEntity &Entity,
  284. InitListExpr *ParentIList, QualType T,
  285. unsigned &Index, InitListExpr *StructuredList,
  286. unsigned &StructuredIndex);
  287. void CheckExplicitInitList(const InitializedEntity &Entity,
  288. InitListExpr *IList, QualType &T,
  289. InitListExpr *StructuredList,
  290. bool TopLevelObject = false);
  291. void CheckListElementTypes(const InitializedEntity &Entity,
  292. InitListExpr *IList, QualType &DeclType,
  293. bool SubobjectIsDesignatorContext,
  294. unsigned &Index,
  295. InitListExpr *StructuredList,
  296. unsigned &StructuredIndex,
  297. bool TopLevelObject = false);
  298. void CheckSubElementType(const InitializedEntity &Entity,
  299. InitListExpr *IList, QualType ElemType,
  300. unsigned &Index,
  301. InitListExpr *StructuredList,
  302. unsigned &StructuredIndex,
  303. bool DirectlyDesignated = false);
  304. void CheckComplexType(const InitializedEntity &Entity,
  305. InitListExpr *IList, QualType DeclType,
  306. unsigned &Index,
  307. InitListExpr *StructuredList,
  308. unsigned &StructuredIndex);
  309. void CheckScalarType(const InitializedEntity &Entity,
  310. InitListExpr *IList, QualType DeclType,
  311. unsigned &Index,
  312. InitListExpr *StructuredList,
  313. unsigned &StructuredIndex);
  314. void CheckReferenceType(const InitializedEntity &Entity,
  315. InitListExpr *IList, QualType DeclType,
  316. unsigned &Index,
  317. InitListExpr *StructuredList,
  318. unsigned &StructuredIndex);
  319. void CheckVectorType(const InitializedEntity &Entity,
  320. InitListExpr *IList, QualType DeclType, unsigned &Index,
  321. InitListExpr *StructuredList,
  322. unsigned &StructuredIndex);
  323. void CheckStructUnionTypes(const InitializedEntity &Entity,
  324. InitListExpr *IList, QualType DeclType,
  325. CXXRecordDecl::base_class_range Bases,
  326. RecordDecl::field_iterator Field,
  327. bool SubobjectIsDesignatorContext, unsigned &Index,
  328. InitListExpr *StructuredList,
  329. unsigned &StructuredIndex,
  330. bool TopLevelObject = false);
  331. void CheckArrayType(const InitializedEntity &Entity,
  332. InitListExpr *IList, QualType &DeclType,
  333. llvm::APSInt elementIndex,
  334. bool SubobjectIsDesignatorContext, unsigned &Index,
  335. InitListExpr *StructuredList,
  336. unsigned &StructuredIndex);
  337. bool CheckDesignatedInitializer(const InitializedEntity &Entity,
  338. InitListExpr *IList, DesignatedInitExpr *DIE,
  339. unsigned DesigIdx,
  340. QualType &CurrentObjectType,
  341. RecordDecl::field_iterator *NextField,
  342. llvm::APSInt *NextElementIndex,
  343. unsigned &Index,
  344. InitListExpr *StructuredList,
  345. unsigned &StructuredIndex,
  346. bool FinishSubobjectInit,
  347. bool TopLevelObject);
  348. InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  349. QualType CurrentObjectType,
  350. InitListExpr *StructuredList,
  351. unsigned StructuredIndex,
  352. SourceRange InitRange,
  353. bool IsFullyOverwritten = false);
  354. void UpdateStructuredListElement(InitListExpr *StructuredList,
  355. unsigned &StructuredIndex,
  356. Expr *expr);
  357. InitListExpr *createInitListExpr(QualType CurrentObjectType,
  358. SourceRange InitRange,
  359. unsigned ExpectedNumInits);
  360. int numArrayElements(QualType DeclType);
  361. int numStructUnionElements(QualType DeclType);
  362. ExprResult PerformEmptyInit(SourceLocation Loc,
  363. const InitializedEntity &Entity);
  364. /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
  365. void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
  366. bool FullyOverwritten = true) {
  367. // Overriding an initializer via a designator is valid with C99 designated
  368. // initializers, but ill-formed with C++20 designated initializers.
  369. unsigned DiagID = SemaRef.getLangOpts().CPlusPlus
  370. ? diag::ext_initializer_overrides
  371. : diag::warn_initializer_overrides;
  372. if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
  373. // In overload resolution, we have to strictly enforce the rules, and so
  374. // don't allow any overriding of prior initializers. This matters for a
  375. // case such as:
  376. //
  377. // union U { int a, b; };
  378. // struct S { int a, b; };
  379. // void f(U), f(S);
  380. //
  381. // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
  382. // consistency, we disallow all overriding of prior initializers in
  383. // overload resolution, not only overriding of union members.
  384. hadError = true;
  385. } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
  386. // If we'll be keeping around the old initializer but overwriting part of
  387. // the object it initialized, and that object is not trivially
  388. // destructible, this can leak. Don't allow that, not even as an
  389. // extension.
  390. //
  391. // FIXME: It might be reasonable to allow this in cases where the part of
  392. // the initializer that we're overriding has trivial destruction.
  393. DiagID = diag::err_initializer_overrides_destructed;
  394. } else if (!OldInit->getSourceRange().isValid()) {
  395. // We need to check on source range validity because the previous
  396. // initializer does not have to be an explicit initializer. e.g.,
  397. //
  398. // struct P { int a, b; };
  399. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  400. //
  401. // There is an overwrite taking place because the first braced initializer
  402. // list "{ .a = 2 }" already provides value for .p.b (which is zero).
  403. //
  404. // Such overwrites are harmless, so we don't diagnose them. (Note that in
  405. // C++, this cannot be reached unless we've already seen and diagnosed a
  406. // different conformance issue, such as a mixture of designated and
  407. // non-designated initializers or a multi-level designator.)
  408. return;
  409. }
  410. if (!VerifyOnly) {
  411. SemaRef.Diag(NewInitRange.getBegin(), DiagID)
  412. << NewInitRange << FullyOverwritten << OldInit->getType();
  413. SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
  414. << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
  415. << OldInit->getSourceRange();
  416. }
  417. }
  418. // Explanation on the "FillWithNoInit" mode:
  419. //
  420. // Assume we have the following definitions (Case#1):
  421. // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
  422. // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
  423. //
  424. // l.lp.x[1][0..1] should not be filled with implicit initializers because the
  425. // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
  426. //
  427. // But if we have (Case#2):
  428. // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
  429. //
  430. // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
  431. // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
  432. //
  433. // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
  434. // in the InitListExpr, the "holes" in Case#1 are filled not with empty
  435. // initializers but with special "NoInitExpr" place holders, which tells the
  436. // CodeGen not to generate any initializers for these parts.
  437. void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
  438. const InitializedEntity &ParentEntity,
  439. InitListExpr *ILE, bool &RequiresSecondPass,
  440. bool FillWithNoInit);
  441. void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  442. const InitializedEntity &ParentEntity,
  443. InitListExpr *ILE, bool &RequiresSecondPass,
  444. bool FillWithNoInit = false);
  445. void FillInEmptyInitializations(const InitializedEntity &Entity,
  446. InitListExpr *ILE, bool &RequiresSecondPass,
  447. InitListExpr *OuterILE, unsigned OuterIndex,
  448. bool FillWithNoInit = false);
  449. bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
  450. Expr *InitExpr, FieldDecl *Field,
  451. bool TopLevelObject);
  452. void CheckEmptyInitializable(const InitializedEntity &Entity,
  453. SourceLocation Loc);
  454. public:
  455. InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
  456. QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
  457. bool InOverloadResolution = false);
  458. bool HadError() { return hadError; }
  459. // Retrieves the fully-structured initializer list used for
  460. // semantic analysis and code generation.
  461. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
  462. };
  463. } // end anonymous namespace
  464. ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
  465. const InitializedEntity &Entity) {
  466. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  467. true);
  468. MultiExprArg SubInit;
  469. Expr *InitExpr;
  470. InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
  471. // C++ [dcl.init.aggr]p7:
  472. // If there are fewer initializer-clauses in the list than there are
  473. // members in the aggregate, then each member not explicitly initialized
  474. // ...
  475. bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
  476. Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
  477. if (EmptyInitList) {
  478. // C++1y / DR1070:
  479. // shall be initialized [...] from an empty initializer list.
  480. //
  481. // We apply the resolution of this DR to C++11 but not C++98, since C++98
  482. // does not have useful semantics for initialization from an init list.
  483. // We treat this as copy-initialization, because aggregate initialization
  484. // always performs copy-initialization on its elements.
  485. //
  486. // Only do this if we're initializing a class type, to avoid filling in
  487. // the initializer list where possible.
  488. InitExpr = VerifyOnly
  489. ? &DummyInitList
  490. : new (SemaRef.Context)
  491. InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
  492. InitExpr->setType(SemaRef.Context.VoidTy);
  493. SubInit = InitExpr;
  494. Kind = InitializationKind::CreateCopy(Loc, Loc);
  495. } else {
  496. // C++03:
  497. // shall be value-initialized.
  498. }
  499. InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
  500. // libstdc++4.6 marks the vector default constructor as explicit in
  501. // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
  502. // stlport does so too. Look for std::__debug for libstdc++, and for
  503. // std:: for stlport. This is effectively a compiler-side implementation of
  504. // LWG2193.
  505. if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
  506. InitializationSequence::FK_ExplicitConstructor) {
  507. OverloadCandidateSet::iterator Best;
  508. OverloadingResult O =
  509. InitSeq.getFailedCandidateSet()
  510. .BestViableFunction(SemaRef, Kind.getLocation(), Best);
  511. (void)O;
  512. assert(O == OR_Success && "Inconsistent overload resolution");
  513. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  514. CXXRecordDecl *R = CtorDecl->getParent();
  515. if (CtorDecl->getMinRequiredArguments() == 0 &&
  516. CtorDecl->isExplicit() && R->getDeclName() &&
  517. SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
  518. bool IsInStd = false;
  519. for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
  520. ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
  521. if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
  522. IsInStd = true;
  523. }
  524. if (IsInStd && llvm::StringSwitch<bool>(R->getName())
  525. .Cases("basic_string", "deque", "forward_list", true)
  526. .Cases("list", "map", "multimap", "multiset", true)
  527. .Cases("priority_queue", "queue", "set", "stack", true)
  528. .Cases("unordered_map", "unordered_set", "vector", true)
  529. .Default(false)) {
  530. InitSeq.InitializeFrom(
  531. SemaRef, Entity,
  532. InitializationKind::CreateValue(Loc, Loc, Loc, true),
  533. MultiExprArg(), /*TopLevelOfInitList=*/false,
  534. TreatUnavailableAsInvalid);
  535. // Emit a warning for this. System header warnings aren't shown
  536. // by default, but people working on system headers should see it.
  537. if (!VerifyOnly) {
  538. SemaRef.Diag(CtorDecl->getLocation(),
  539. diag::warn_invalid_initializer_from_system_header);
  540. if (Entity.getKind() == InitializedEntity::EK_Member)
  541. SemaRef.Diag(Entity.getDecl()->getLocation(),
  542. diag::note_used_in_initialization_here);
  543. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
  544. SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
  545. }
  546. }
  547. }
  548. }
  549. if (!InitSeq) {
  550. if (!VerifyOnly) {
  551. InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
  552. if (Entity.getKind() == InitializedEntity::EK_Member)
  553. SemaRef.Diag(Entity.getDecl()->getLocation(),
  554. diag::note_in_omitted_aggregate_initializer)
  555. << /*field*/1 << Entity.getDecl();
  556. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
  557. bool IsTrailingArrayNewMember =
  558. Entity.getParent() &&
  559. Entity.getParent()->isVariableLengthArrayNew();
  560. SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
  561. << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
  562. << Entity.getElementIndex();
  563. }
  564. }
  565. hadError = true;
  566. return ExprError();
  567. }
  568. return VerifyOnly ? ExprResult()
  569. : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
  570. }
  571. void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
  572. SourceLocation Loc) {
  573. // If we're building a fully-structured list, we'll check this at the end
  574. // once we know which elements are actually initialized. Otherwise, we know
  575. // that there are no designators so we can just check now.
  576. if (FullyStructuredList)
  577. return;
  578. PerformEmptyInit(Loc, Entity);
  579. }
  580. void InitListChecker::FillInEmptyInitForBase(
  581. unsigned Init, const CXXBaseSpecifier &Base,
  582. const InitializedEntity &ParentEntity, InitListExpr *ILE,
  583. bool &RequiresSecondPass, bool FillWithNoInit) {
  584. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  585. SemaRef.Context, &Base, false, &ParentEntity);
  586. if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
  587. ExprResult BaseInit = FillWithNoInit
  588. ? new (SemaRef.Context) NoInitExpr(Base.getType())
  589. : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
  590. if (BaseInit.isInvalid()) {
  591. hadError = true;
  592. return;
  593. }
  594. if (!VerifyOnly) {
  595. assert(Init < ILE->getNumInits() && "should have been expanded");
  596. ILE->setInit(Init, BaseInit.getAs<Expr>());
  597. }
  598. } else if (InitListExpr *InnerILE =
  599. dyn_cast<InitListExpr>(ILE->getInit(Init))) {
  600. FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
  601. ILE, Init, FillWithNoInit);
  602. } else if (DesignatedInitUpdateExpr *InnerDIUE =
  603. dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
  604. FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
  605. RequiresSecondPass, ILE, Init,
  606. /*FillWithNoInit =*/true);
  607. }
  608. }
  609. void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  610. const InitializedEntity &ParentEntity,
  611. InitListExpr *ILE,
  612. bool &RequiresSecondPass,
  613. bool FillWithNoInit) {
  614. SourceLocation Loc = ILE->getEndLoc();
  615. unsigned NumInits = ILE->getNumInits();
  616. InitializedEntity MemberEntity
  617. = InitializedEntity::InitializeMember(Field, &ParentEntity);
  618. if (Init >= NumInits || !ILE->getInit(Init)) {
  619. if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
  620. if (!RType->getDecl()->isUnion())
  621. assert((Init < NumInits || VerifyOnly) &&
  622. "This ILE should have been expanded");
  623. if (FillWithNoInit) {
  624. assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
  625. Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
  626. if (Init < NumInits)
  627. ILE->setInit(Init, Filler);
  628. else
  629. ILE->updateInit(SemaRef.Context, Init, Filler);
  630. return;
  631. }
  632. // C++1y [dcl.init.aggr]p7:
  633. // If there are fewer initializer-clauses in the list than there are
  634. // members in the aggregate, then each member not explicitly initialized
  635. // shall be initialized from its brace-or-equal-initializer [...]
  636. if (Field->hasInClassInitializer()) {
  637. if (VerifyOnly)
  638. return;
  639. ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
  640. if (DIE.isInvalid()) {
  641. hadError = true;
  642. return;
  643. }
  644. SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
  645. if (Init < NumInits)
  646. ILE->setInit(Init, DIE.get());
  647. else {
  648. ILE->updateInit(SemaRef.Context, Init, DIE.get());
  649. RequiresSecondPass = true;
  650. }
  651. return;
  652. }
  653. if (Field->getType()->isReferenceType()) {
  654. if (!VerifyOnly) {
  655. // C++ [dcl.init.aggr]p9:
  656. // If an incomplete or empty initializer-list leaves a
  657. // member of reference type uninitialized, the program is
  658. // ill-formed.
  659. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
  660. << Field->getType()
  661. << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
  662. ->getSourceRange();
  663. SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
  664. }
  665. hadError = true;
  666. return;
  667. }
  668. ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
  669. if (MemberInit.isInvalid()) {
  670. hadError = true;
  671. return;
  672. }
  673. if (hadError || VerifyOnly) {
  674. // Do nothing
  675. } else if (Init < NumInits) {
  676. ILE->setInit(Init, MemberInit.getAs<Expr>());
  677. } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
  678. // Empty initialization requires a constructor call, so
  679. // extend the initializer list to include the constructor
  680. // call and make a note that we'll need to take another pass
  681. // through the initializer list.
  682. ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
  683. RequiresSecondPass = true;
  684. }
  685. } else if (InitListExpr *InnerILE
  686. = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
  687. FillInEmptyInitializations(MemberEntity, InnerILE,
  688. RequiresSecondPass, ILE, Init, FillWithNoInit);
  689. } else if (DesignatedInitUpdateExpr *InnerDIUE =
  690. dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
  691. FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
  692. RequiresSecondPass, ILE, Init,
  693. /*FillWithNoInit =*/true);
  694. }
  695. }
  696. /// Recursively replaces NULL values within the given initializer list
  697. /// with expressions that perform value-initialization of the
  698. /// appropriate type, and finish off the InitListExpr formation.
  699. void
  700. InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
  701. InitListExpr *ILE,
  702. bool &RequiresSecondPass,
  703. InitListExpr *OuterILE,
  704. unsigned OuterIndex,
  705. bool FillWithNoInit) {
  706. assert((ILE->getType() != SemaRef.Context.VoidTy) &&
  707. "Should not have void type");
  708. // We don't need to do any checks when just filling NoInitExprs; that can't
  709. // fail.
  710. if (FillWithNoInit && VerifyOnly)
  711. return;
  712. // If this is a nested initializer list, we might have changed its contents
  713. // (and therefore some of its properties, such as instantiation-dependence)
  714. // while filling it in. Inform the outer initializer list so that its state
  715. // can be updated to match.
  716. // FIXME: We should fully build the inner initializers before constructing
  717. // the outer InitListExpr instead of mutating AST nodes after they have
  718. // been used as subexpressions of other nodes.
  719. struct UpdateOuterILEWithUpdatedInit {
  720. InitListExpr *Outer;
  721. unsigned OuterIndex;
  722. ~UpdateOuterILEWithUpdatedInit() {
  723. if (Outer)
  724. Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
  725. }
  726. } UpdateOuterRAII = {OuterILE, OuterIndex};
  727. // A transparent ILE is not performing aggregate initialization and should
  728. // not be filled in.
  729. if (ILE->isTransparent())
  730. return;
  731. if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
  732. const RecordDecl *RDecl = RType->getDecl();
  733. if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
  734. FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
  735. Entity, ILE, RequiresSecondPass, FillWithNoInit);
  736. else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
  737. cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
  738. for (auto *Field : RDecl->fields()) {
  739. if (Field->hasInClassInitializer()) {
  740. FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
  741. FillWithNoInit);
  742. break;
  743. }
  744. }
  745. } else {
  746. // The fields beyond ILE->getNumInits() are default initialized, so in
  747. // order to leave them uninitialized, the ILE is expanded and the extra
  748. // fields are then filled with NoInitExpr.
  749. unsigned NumElems = numStructUnionElements(ILE->getType());
  750. if (RDecl->hasFlexibleArrayMember())
  751. ++NumElems;
  752. if (!VerifyOnly && ILE->getNumInits() < NumElems)
  753. ILE->resizeInits(SemaRef.Context, NumElems);
  754. unsigned Init = 0;
  755. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
  756. for (auto &Base : CXXRD->bases()) {
  757. if (hadError)
  758. return;
  759. FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
  760. FillWithNoInit);
  761. ++Init;
  762. }
  763. }
  764. for (auto *Field : RDecl->fields()) {
  765. if (Field->isUnnamedBitfield())
  766. continue;
  767. if (hadError)
  768. return;
  769. FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
  770. FillWithNoInit);
  771. if (hadError)
  772. return;
  773. ++Init;
  774. // Only look at the first initialization of a union.
  775. if (RDecl->isUnion())
  776. break;
  777. }
  778. }
  779. return;
  780. }
  781. QualType ElementType;
  782. InitializedEntity ElementEntity = Entity;
  783. unsigned NumInits = ILE->getNumInits();
  784. unsigned NumElements = NumInits;
  785. if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
  786. ElementType = AType->getElementType();
  787. if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
  788. NumElements = CAType->getSize().getZExtValue();
  789. // For an array new with an unknown bound, ask for one additional element
  790. // in order to populate the array filler.
  791. if (Entity.isVariableLengthArrayNew())
  792. ++NumElements;
  793. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  794. 0, Entity);
  795. } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
  796. ElementType = VType->getElementType();
  797. NumElements = VType->getNumElements();
  798. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  799. 0, Entity);
  800. } else
  801. ElementType = ILE->getType();
  802. bool SkipEmptyInitChecks = false;
  803. for (unsigned Init = 0; Init != NumElements; ++Init) {
  804. if (hadError)
  805. return;
  806. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
  807. ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
  808. ElementEntity.setElementIndex(Init);
  809. if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
  810. return;
  811. Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
  812. if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
  813. ILE->setInit(Init, ILE->getArrayFiller());
  814. else if (!InitExpr && !ILE->hasArrayFiller()) {
  815. // In VerifyOnly mode, there's no point performing empty initialization
  816. // more than once.
  817. if (SkipEmptyInitChecks)
  818. continue;
  819. Expr *Filler = nullptr;
  820. if (FillWithNoInit)
  821. Filler = new (SemaRef.Context) NoInitExpr(ElementType);
  822. else {
  823. ExprResult ElementInit =
  824. PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
  825. if (ElementInit.isInvalid()) {
  826. hadError = true;
  827. return;
  828. }
  829. Filler = ElementInit.getAs<Expr>();
  830. }
  831. if (hadError) {
  832. // Do nothing
  833. } else if (VerifyOnly) {
  834. SkipEmptyInitChecks = true;
  835. } else if (Init < NumInits) {
  836. // For arrays, just set the expression used for value-initialization
  837. // of the "holes" in the array.
  838. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
  839. ILE->setArrayFiller(Filler);
  840. else
  841. ILE->setInit(Init, Filler);
  842. } else {
  843. // For arrays, just set the expression used for value-initialization
  844. // of the rest of elements and exit.
  845. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  846. ILE->setArrayFiller(Filler);
  847. return;
  848. }
  849. if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
  850. // Empty initialization requires a constructor call, so
  851. // extend the initializer list to include the constructor
  852. // call and make a note that we'll need to take another pass
  853. // through the initializer list.
  854. ILE->updateInit(SemaRef.Context, Init, Filler);
  855. RequiresSecondPass = true;
  856. }
  857. }
  858. } else if (InitListExpr *InnerILE
  859. = dyn_cast_or_null<InitListExpr>(InitExpr)) {
  860. FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
  861. ILE, Init, FillWithNoInit);
  862. } else if (DesignatedInitUpdateExpr *InnerDIUE =
  863. dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
  864. FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
  865. RequiresSecondPass, ILE, Init,
  866. /*FillWithNoInit =*/true);
  867. }
  868. }
  869. }
  870. static bool hasAnyDesignatedInits(const InitListExpr *IL) {
  871. for (const Stmt *Init : *IL)
  872. if (Init && isa<DesignatedInitExpr>(Init))
  873. return true;
  874. return false;
  875. }
  876. InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
  877. InitListExpr *IL, QualType &T, bool VerifyOnly,
  878. bool TreatUnavailableAsInvalid,
  879. bool InOverloadResolution)
  880. : SemaRef(S), VerifyOnly(VerifyOnly),
  881. TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
  882. InOverloadResolution(InOverloadResolution) {
  883. if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
  884. FullyStructuredList =
  885. createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
  886. // FIXME: Check that IL isn't already the semantic form of some other
  887. // InitListExpr. If it is, we'd create a broken AST.
  888. if (!VerifyOnly)
  889. FullyStructuredList->setSyntacticForm(IL);
  890. }
  891. CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
  892. /*TopLevelObject=*/true);
  893. if (!hadError && FullyStructuredList) {
  894. bool RequiresSecondPass = false;
  895. FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
  896. /*OuterILE=*/nullptr, /*OuterIndex=*/0);
  897. if (RequiresSecondPass && !hadError)
  898. FillInEmptyInitializations(Entity, FullyStructuredList,
  899. RequiresSecondPass, nullptr, 0);
  900. }
  901. if (hadError && FullyStructuredList)
  902. FullyStructuredList->markError();
  903. }
  904. int InitListChecker::numArrayElements(QualType DeclType) {
  905. // FIXME: use a proper constant
  906. int maxElements = 0x7FFFFFFF;
  907. if (const ConstantArrayType *CAT =
  908. SemaRef.Context.getAsConstantArrayType(DeclType)) {
  909. maxElements = static_cast<int>(CAT->getSize().getZExtValue());
  910. }
  911. return maxElements;
  912. }
  913. int InitListChecker::numStructUnionElements(QualType DeclType) {
  914. RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
  915. int InitializableMembers = 0;
  916. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
  917. InitializableMembers += CXXRD->getNumBases();
  918. for (const auto *Field : structDecl->fields())
  919. if (!Field->isUnnamedBitfield())
  920. ++InitializableMembers;
  921. if (structDecl->isUnion())
  922. return std::min(InitializableMembers, 1);
  923. return InitializableMembers - structDecl->hasFlexibleArrayMember();
  924. }
  925. /// Determine whether Entity is an entity for which it is idiomatic to elide
  926. /// the braces in aggregate initialization.
  927. static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
  928. // Recursive initialization of the one and only field within an aggregate
  929. // class is considered idiomatic. This case arises in particular for
  930. // initialization of std::array, where the C++ standard suggests the idiom of
  931. //
  932. // std::array<T, N> arr = {1, 2, 3};
  933. //
  934. // (where std::array is an aggregate struct containing a single array field.
  935. if (!Entity.getParent())
  936. return false;
  937. // Allows elide brace initialization for aggregates with empty base.
  938. if (Entity.getKind() == InitializedEntity::EK_Base) {
  939. auto *ParentRD =
  940. Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
  941. CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
  942. return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
  943. }
  944. // Allow brace elision if the only subobject is a field.
  945. if (Entity.getKind() == InitializedEntity::EK_Member) {
  946. auto *ParentRD =
  947. Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
  948. if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
  949. if (CXXRD->getNumBases()) {
  950. return false;
  951. }
  952. }
  953. auto FieldIt = ParentRD->field_begin();
  954. assert(FieldIt != ParentRD->field_end() &&
  955. "no fields but have initializer for member?");
  956. return ++FieldIt == ParentRD->field_end();
  957. }
  958. return false;
  959. }
  960. /// Check whether the range of the initializer \p ParentIList from element
  961. /// \p Index onwards can be used to initialize an object of type \p T. Update
  962. /// \p Index to indicate how many elements of the list were consumed.
  963. ///
  964. /// This also fills in \p StructuredList, from element \p StructuredIndex
  965. /// onwards, with the fully-braced, desugared form of the initialization.
  966. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
  967. InitListExpr *ParentIList,
  968. QualType T, unsigned &Index,
  969. InitListExpr *StructuredList,
  970. unsigned &StructuredIndex) {
  971. int maxElements = 0;
  972. if (T->isArrayType())
  973. maxElements = numArrayElements(T);
  974. else if (T->isRecordType())
  975. maxElements = numStructUnionElements(T);
  976. else if (T->isVectorType())
  977. maxElements = T->castAs<VectorType>()->getNumElements();
  978. else
  979. llvm_unreachable("CheckImplicitInitList(): Illegal type");
  980. if (maxElements == 0) {
  981. if (!VerifyOnly)
  982. SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
  983. diag::err_implicit_empty_initializer);
  984. ++Index;
  985. hadError = true;
  986. return;
  987. }
  988. // Build a structured initializer list corresponding to this subobject.
  989. InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
  990. ParentIList, Index, T, StructuredList, StructuredIndex,
  991. SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
  992. ParentIList->getSourceRange().getEnd()));
  993. unsigned StructuredSubobjectInitIndex = 0;
  994. // Check the element types and build the structural subobject.
  995. unsigned StartIndex = Index;
  996. CheckListElementTypes(Entity, ParentIList, T,
  997. /*SubobjectIsDesignatorContext=*/false, Index,
  998. StructuredSubobjectInitList,
  999. StructuredSubobjectInitIndex);
  1000. if (StructuredSubobjectInitList) {
  1001. StructuredSubobjectInitList->setType(T);
  1002. unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
  1003. // Update the structured sub-object initializer so that it's ending
  1004. // range corresponds with the end of the last initializer it used.
  1005. if (EndIndex < ParentIList->getNumInits() &&
  1006. ParentIList->getInit(EndIndex)) {
  1007. SourceLocation EndLoc
  1008. = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
  1009. StructuredSubobjectInitList->setRBraceLoc(EndLoc);
  1010. }
  1011. // Complain about missing braces.
  1012. if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
  1013. !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
  1014. !isIdiomaticBraceElisionEntity(Entity)) {
  1015. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  1016. diag::warn_missing_braces)
  1017. << StructuredSubobjectInitList->getSourceRange()
  1018. << FixItHint::CreateInsertion(
  1019. StructuredSubobjectInitList->getBeginLoc(), "{")
  1020. << FixItHint::CreateInsertion(
  1021. SemaRef.getLocForEndOfToken(
  1022. StructuredSubobjectInitList->getEndLoc()),
  1023. "}");
  1024. }
  1025. // Warn if this type won't be an aggregate in future versions of C++.
  1026. auto *CXXRD = T->getAsCXXRecordDecl();
  1027. if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  1028. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  1029. diag::warn_cxx20_compat_aggregate_init_with_ctors)
  1030. << StructuredSubobjectInitList->getSourceRange() << T;
  1031. }
  1032. }
  1033. }
  1034. /// Warn that \p Entity was of scalar type and was initialized by a
  1035. /// single-element braced initializer list.
  1036. static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
  1037. SourceRange Braces) {
  1038. // Don't warn during template instantiation. If the initialization was
  1039. // non-dependent, we warned during the initial parse; otherwise, the
  1040. // type might not be scalar in some uses of the template.
  1041. if (S.inTemplateInstantiation())
  1042. return;
  1043. unsigned DiagID = 0;
  1044. switch (Entity.getKind()) {
  1045. case InitializedEntity::EK_VectorElement:
  1046. case InitializedEntity::EK_ComplexElement:
  1047. case InitializedEntity::EK_ArrayElement:
  1048. case InitializedEntity::EK_Parameter:
  1049. case InitializedEntity::EK_Parameter_CF_Audited:
  1050. case InitializedEntity::EK_TemplateParameter:
  1051. case InitializedEntity::EK_Result:
  1052. // Extra braces here are suspicious.
  1053. DiagID = diag::warn_braces_around_init;
  1054. break;
  1055. case InitializedEntity::EK_Member:
  1056. // Warn on aggregate initialization but not on ctor init list or
  1057. // default member initializer.
  1058. if (Entity.getParent())
  1059. DiagID = diag::warn_braces_around_init;
  1060. break;
  1061. case InitializedEntity::EK_Variable:
  1062. case InitializedEntity::EK_LambdaCapture:
  1063. // No warning, might be direct-list-initialization.
  1064. // FIXME: Should we warn for copy-list-initialization in these cases?
  1065. break;
  1066. case InitializedEntity::EK_New:
  1067. case InitializedEntity::EK_Temporary:
  1068. case InitializedEntity::EK_CompoundLiteralInit:
  1069. // No warning, braces are part of the syntax of the underlying construct.
  1070. break;
  1071. case InitializedEntity::EK_RelatedResult:
  1072. // No warning, we already warned when initializing the result.
  1073. break;
  1074. case InitializedEntity::EK_Exception:
  1075. case InitializedEntity::EK_Base:
  1076. case InitializedEntity::EK_Delegating:
  1077. case InitializedEntity::EK_BlockElement:
  1078. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  1079. case InitializedEntity::EK_Binding:
  1080. case InitializedEntity::EK_StmtExprResult:
  1081. llvm_unreachable("unexpected braced scalar init");
  1082. }
  1083. if (DiagID) {
  1084. S.Diag(Braces.getBegin(), DiagID)
  1085. << Entity.getType()->isSizelessBuiltinType() << Braces
  1086. << FixItHint::CreateRemoval(Braces.getBegin())
  1087. << FixItHint::CreateRemoval(Braces.getEnd());
  1088. }
  1089. }
  1090. /// Check whether the initializer \p IList (that was written with explicit
  1091. /// braces) can be used to initialize an object of type \p T.
  1092. ///
  1093. /// This also fills in \p StructuredList with the fully-braced, desugared
  1094. /// form of the initialization.
  1095. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
  1096. InitListExpr *IList, QualType &T,
  1097. InitListExpr *StructuredList,
  1098. bool TopLevelObject) {
  1099. unsigned Index = 0, StructuredIndex = 0;
  1100. CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
  1101. Index, StructuredList, StructuredIndex, TopLevelObject);
  1102. if (StructuredList) {
  1103. QualType ExprTy = T;
  1104. if (!ExprTy->isArrayType())
  1105. ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
  1106. if (!VerifyOnly)
  1107. IList->setType(ExprTy);
  1108. StructuredList->setType(ExprTy);
  1109. }
  1110. if (hadError)
  1111. return;
  1112. // Don't complain for incomplete types, since we'll get an error elsewhere.
  1113. if (Index < IList->getNumInits() && !T->isIncompleteType()) {
  1114. // We have leftover initializers
  1115. bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
  1116. (SemaRef.getLangOpts().OpenCL && T->isVectorType());
  1117. hadError = ExtraInitsIsError;
  1118. if (VerifyOnly) {
  1119. return;
  1120. } else if (StructuredIndex == 1 &&
  1121. IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
  1122. SIF_None) {
  1123. unsigned DK =
  1124. ExtraInitsIsError
  1125. ? diag::err_excess_initializers_in_char_array_initializer
  1126. : diag::ext_excess_initializers_in_char_array_initializer;
  1127. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1128. << IList->getInit(Index)->getSourceRange();
  1129. } else if (T->isSizelessBuiltinType()) {
  1130. unsigned DK = ExtraInitsIsError
  1131. ? diag::err_excess_initializers_for_sizeless_type
  1132. : diag::ext_excess_initializers_for_sizeless_type;
  1133. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1134. << T << IList->getInit(Index)->getSourceRange();
  1135. } else {
  1136. int initKind = T->isArrayType() ? 0 :
  1137. T->isVectorType() ? 1 :
  1138. T->isScalarType() ? 2 :
  1139. T->isUnionType() ? 3 :
  1140. 4;
  1141. unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
  1142. : diag::ext_excess_initializers;
  1143. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1144. << initKind << IList->getInit(Index)->getSourceRange();
  1145. }
  1146. }
  1147. if (!VerifyOnly) {
  1148. if (T->isScalarType() && IList->getNumInits() == 1 &&
  1149. !isa<InitListExpr>(IList->getInit(0)))
  1150. warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
  1151. // Warn if this is a class type that won't be an aggregate in future
  1152. // versions of C++.
  1153. auto *CXXRD = T->getAsCXXRecordDecl();
  1154. if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  1155. // Don't warn if there's an equivalent default constructor that would be
  1156. // used instead.
  1157. bool HasEquivCtor = false;
  1158. if (IList->getNumInits() == 0) {
  1159. auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
  1160. HasEquivCtor = CD && !CD->isDeleted();
  1161. }
  1162. if (!HasEquivCtor) {
  1163. SemaRef.Diag(IList->getBeginLoc(),
  1164. diag::warn_cxx20_compat_aggregate_init_with_ctors)
  1165. << IList->getSourceRange() << T;
  1166. }
  1167. }
  1168. }
  1169. }
  1170. void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
  1171. InitListExpr *IList,
  1172. QualType &DeclType,
  1173. bool SubobjectIsDesignatorContext,
  1174. unsigned &Index,
  1175. InitListExpr *StructuredList,
  1176. unsigned &StructuredIndex,
  1177. bool TopLevelObject) {
  1178. if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
  1179. // Explicitly braced initializer for complex type can be real+imaginary
  1180. // parts.
  1181. CheckComplexType(Entity, IList, DeclType, Index,
  1182. StructuredList, StructuredIndex);
  1183. } else if (DeclType->isScalarType()) {
  1184. CheckScalarType(Entity, IList, DeclType, Index,
  1185. StructuredList, StructuredIndex);
  1186. } else if (DeclType->isVectorType()) {
  1187. CheckVectorType(Entity, IList, DeclType, Index,
  1188. StructuredList, StructuredIndex);
  1189. } else if (DeclType->isRecordType()) {
  1190. assert(DeclType->isAggregateType() &&
  1191. "non-aggregate records should be handed in CheckSubElementType");
  1192. RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
  1193. auto Bases =
  1194. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  1195. CXXRecordDecl::base_class_iterator());
  1196. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1197. Bases = CXXRD->bases();
  1198. CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
  1199. SubobjectIsDesignatorContext, Index, StructuredList,
  1200. StructuredIndex, TopLevelObject);
  1201. } else if (DeclType->isArrayType()) {
  1202. llvm::APSInt Zero(
  1203. SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
  1204. false);
  1205. CheckArrayType(Entity, IList, DeclType, Zero,
  1206. SubobjectIsDesignatorContext, Index,
  1207. StructuredList, StructuredIndex);
  1208. } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
  1209. // This type is invalid, issue a diagnostic.
  1210. ++Index;
  1211. if (!VerifyOnly)
  1212. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1213. << DeclType;
  1214. hadError = true;
  1215. } else if (DeclType->isReferenceType()) {
  1216. CheckReferenceType(Entity, IList, DeclType, Index,
  1217. StructuredList, StructuredIndex);
  1218. } else if (DeclType->isObjCObjectType()) {
  1219. if (!VerifyOnly)
  1220. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
  1221. hadError = true;
  1222. } else if (DeclType->isOCLIntelSubgroupAVCType() ||
  1223. DeclType->isSizelessBuiltinType()) {
  1224. // Checks for scalar type are sufficient for these types too.
  1225. CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1226. StructuredIndex);
  1227. } else {
  1228. if (!VerifyOnly)
  1229. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1230. << DeclType;
  1231. hadError = true;
  1232. }
  1233. }
  1234. void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
  1235. InitListExpr *IList,
  1236. QualType ElemType,
  1237. unsigned &Index,
  1238. InitListExpr *StructuredList,
  1239. unsigned &StructuredIndex,
  1240. bool DirectlyDesignated) {
  1241. Expr *expr = IList->getInit(Index);
  1242. if (ElemType->isReferenceType())
  1243. return CheckReferenceType(Entity, IList, ElemType, Index,
  1244. StructuredList, StructuredIndex);
  1245. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
  1246. if (SubInitList->getNumInits() == 1 &&
  1247. IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
  1248. SIF_None) {
  1249. // FIXME: It would be more faithful and no less correct to include an
  1250. // InitListExpr in the semantic form of the initializer list in this case.
  1251. expr = SubInitList->getInit(0);
  1252. }
  1253. // Nested aggregate initialization and C++ initialization are handled later.
  1254. } else if (isa<ImplicitValueInitExpr>(expr)) {
  1255. // This happens during template instantiation when we see an InitListExpr
  1256. // that we've already checked once.
  1257. assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
  1258. "found implicit initialization for the wrong type");
  1259. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1260. ++Index;
  1261. return;
  1262. }
  1263. if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
  1264. // C++ [dcl.init.aggr]p2:
  1265. // Each member is copy-initialized from the corresponding
  1266. // initializer-clause.
  1267. // FIXME: Better EqualLoc?
  1268. InitializationKind Kind =
  1269. InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
  1270. // Vector elements can be initialized from other vectors in which case
  1271. // we need initialization entity with a type of a vector (and not a vector
  1272. // element!) initializing multiple vector elements.
  1273. auto TmpEntity =
  1274. (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
  1275. ? InitializedEntity::InitializeTemporary(ElemType)
  1276. : Entity;
  1277. InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
  1278. /*TopLevelOfInitList*/ true);
  1279. // C++14 [dcl.init.aggr]p13:
  1280. // If the assignment-expression can initialize a member, the member is
  1281. // initialized. Otherwise [...] brace elision is assumed
  1282. //
  1283. // Brace elision is never performed if the element is not an
  1284. // assignment-expression.
  1285. if (Seq || isa<InitListExpr>(expr)) {
  1286. if (!VerifyOnly) {
  1287. ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
  1288. if (Result.isInvalid())
  1289. hadError = true;
  1290. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1291. Result.getAs<Expr>());
  1292. } else if (!Seq) {
  1293. hadError = true;
  1294. } else if (StructuredList) {
  1295. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1296. getDummyInit());
  1297. }
  1298. ++Index;
  1299. return;
  1300. }
  1301. // Fall through for subaggregate initialization
  1302. } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
  1303. // FIXME: Need to handle atomic aggregate types with implicit init lists.
  1304. return CheckScalarType(Entity, IList, ElemType, Index,
  1305. StructuredList, StructuredIndex);
  1306. } else if (const ArrayType *arrayType =
  1307. SemaRef.Context.getAsArrayType(ElemType)) {
  1308. // arrayType can be incomplete if we're initializing a flexible
  1309. // array member. There's nothing we can do with the completed
  1310. // type here, though.
  1311. if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
  1312. // FIXME: Should we do this checking in verify-only mode?
  1313. if (!VerifyOnly)
  1314. CheckStringInit(expr, ElemType, arrayType, SemaRef);
  1315. if (StructuredList)
  1316. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1317. ++Index;
  1318. return;
  1319. }
  1320. // Fall through for subaggregate initialization.
  1321. } else {
  1322. assert((ElemType->isRecordType() || ElemType->isVectorType() ||
  1323. ElemType->isOpenCLSpecificType()) && "Unexpected type");
  1324. // C99 6.7.8p13:
  1325. //
  1326. // The initializer for a structure or union object that has
  1327. // automatic storage duration shall be either an initializer
  1328. // list as described below, or a single expression that has
  1329. // compatible structure or union type. In the latter case, the
  1330. // initial value of the object, including unnamed members, is
  1331. // that of the expression.
  1332. ExprResult ExprRes = expr;
  1333. if (SemaRef.CheckSingleAssignmentConstraints(
  1334. ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
  1335. if (ExprRes.isInvalid())
  1336. hadError = true;
  1337. else {
  1338. ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
  1339. if (ExprRes.isInvalid())
  1340. hadError = true;
  1341. }
  1342. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1343. ExprRes.getAs<Expr>());
  1344. ++Index;
  1345. return;
  1346. }
  1347. ExprRes.get();
  1348. // Fall through for subaggregate initialization
  1349. }
  1350. // C++ [dcl.init.aggr]p12:
  1351. //
  1352. // [...] Otherwise, if the member is itself a non-empty
  1353. // subaggregate, brace elision is assumed and the initializer is
  1354. // considered for the initialization of the first member of
  1355. // the subaggregate.
  1356. // OpenCL vector initializer is handled elsewhere.
  1357. if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
  1358. ElemType->isAggregateType()) {
  1359. CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
  1360. StructuredIndex);
  1361. ++StructuredIndex;
  1362. // In C++20, brace elision is not permitted for a designated initializer.
  1363. if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
  1364. if (InOverloadResolution)
  1365. hadError = true;
  1366. if (!VerifyOnly) {
  1367. SemaRef.Diag(expr->getBeginLoc(),
  1368. diag::ext_designated_init_brace_elision)
  1369. << expr->getSourceRange()
  1370. << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
  1371. << FixItHint::CreateInsertion(
  1372. SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
  1373. }
  1374. }
  1375. } else {
  1376. if (!VerifyOnly) {
  1377. // We cannot initialize this element, so let PerformCopyInitialization
  1378. // produce the appropriate diagnostic. We already checked that this
  1379. // initialization will fail.
  1380. ExprResult Copy =
  1381. SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
  1382. /*TopLevelOfInitList=*/true);
  1383. (void)Copy;
  1384. assert(Copy.isInvalid() &&
  1385. "expected non-aggregate initialization to fail");
  1386. }
  1387. hadError = true;
  1388. ++Index;
  1389. ++StructuredIndex;
  1390. }
  1391. }
  1392. void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
  1393. InitListExpr *IList, QualType DeclType,
  1394. unsigned &Index,
  1395. InitListExpr *StructuredList,
  1396. unsigned &StructuredIndex) {
  1397. assert(Index == 0 && "Index in explicit init list must be zero");
  1398. // As an extension, clang supports complex initializers, which initialize
  1399. // a complex number component-wise. When an explicit initializer list for
  1400. // a complex number contains two initializers, this extension kicks in:
  1401. // it expects the initializer list to contain two elements convertible to
  1402. // the element type of the complex type. The first element initializes
  1403. // the real part, and the second element intitializes the imaginary part.
  1404. if (IList->getNumInits() != 2)
  1405. return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1406. StructuredIndex);
  1407. // This is an extension in C. (The builtin _Complex type does not exist
  1408. // in the C++ standard.)
  1409. if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
  1410. SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
  1411. << IList->getSourceRange();
  1412. // Initialize the complex number.
  1413. QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
  1414. InitializedEntity ElementEntity =
  1415. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1416. for (unsigned i = 0; i < 2; ++i) {
  1417. ElementEntity.setElementIndex(Index);
  1418. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1419. StructuredList, StructuredIndex);
  1420. }
  1421. }
  1422. void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
  1423. InitListExpr *IList, QualType DeclType,
  1424. unsigned &Index,
  1425. InitListExpr *StructuredList,
  1426. unsigned &StructuredIndex) {
  1427. if (Index >= IList->getNumInits()) {
  1428. if (!VerifyOnly) {
  1429. if (DeclType->isSizelessBuiltinType())
  1430. SemaRef.Diag(IList->getBeginLoc(),
  1431. SemaRef.getLangOpts().CPlusPlus11
  1432. ? diag::warn_cxx98_compat_empty_sizeless_initializer
  1433. : diag::err_empty_sizeless_initializer)
  1434. << DeclType << IList->getSourceRange();
  1435. else
  1436. SemaRef.Diag(IList->getBeginLoc(),
  1437. SemaRef.getLangOpts().CPlusPlus11
  1438. ? diag::warn_cxx98_compat_empty_scalar_initializer
  1439. : diag::err_empty_scalar_initializer)
  1440. << IList->getSourceRange();
  1441. }
  1442. hadError = !SemaRef.getLangOpts().CPlusPlus11;
  1443. ++Index;
  1444. ++StructuredIndex;
  1445. return;
  1446. }
  1447. Expr *expr = IList->getInit(Index);
  1448. if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
  1449. // FIXME: This is invalid, and accepting it causes overload resolution
  1450. // to pick the wrong overload in some corner cases.
  1451. if (!VerifyOnly)
  1452. SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
  1453. << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
  1454. CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
  1455. StructuredIndex);
  1456. return;
  1457. } else if (isa<DesignatedInitExpr>(expr)) {
  1458. if (!VerifyOnly)
  1459. SemaRef.Diag(expr->getBeginLoc(),
  1460. diag::err_designator_for_scalar_or_sizeless_init)
  1461. << DeclType->isSizelessBuiltinType() << DeclType
  1462. << expr->getSourceRange();
  1463. hadError = true;
  1464. ++Index;
  1465. ++StructuredIndex;
  1466. return;
  1467. }
  1468. ExprResult Result;
  1469. if (VerifyOnly) {
  1470. if (SemaRef.CanPerformCopyInitialization(Entity, expr))
  1471. Result = getDummyInit();
  1472. else
  1473. Result = ExprError();
  1474. } else {
  1475. Result =
  1476. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1477. /*TopLevelOfInitList=*/true);
  1478. }
  1479. Expr *ResultExpr = nullptr;
  1480. if (Result.isInvalid())
  1481. hadError = true; // types weren't compatible.
  1482. else {
  1483. ResultExpr = Result.getAs<Expr>();
  1484. if (ResultExpr != expr && !VerifyOnly) {
  1485. // The type was promoted, update initializer list.
  1486. // FIXME: Why are we updating the syntactic init list?
  1487. IList->setInit(Index, ResultExpr);
  1488. }
  1489. }
  1490. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  1491. ++Index;
  1492. }
  1493. void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
  1494. InitListExpr *IList, QualType DeclType,
  1495. unsigned &Index,
  1496. InitListExpr *StructuredList,
  1497. unsigned &StructuredIndex) {
  1498. if (Index >= IList->getNumInits()) {
  1499. // FIXME: It would be wonderful if we could point at the actual member. In
  1500. // general, it would be useful to pass location information down the stack,
  1501. // so that we know the location (or decl) of the "current object" being
  1502. // initialized.
  1503. if (!VerifyOnly)
  1504. SemaRef.Diag(IList->getBeginLoc(),
  1505. diag::err_init_reference_member_uninitialized)
  1506. << DeclType << IList->getSourceRange();
  1507. hadError = true;
  1508. ++Index;
  1509. ++StructuredIndex;
  1510. return;
  1511. }
  1512. Expr *expr = IList->getInit(Index);
  1513. if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
  1514. if (!VerifyOnly)
  1515. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
  1516. << DeclType << IList->getSourceRange();
  1517. hadError = true;
  1518. ++Index;
  1519. ++StructuredIndex;
  1520. return;
  1521. }
  1522. ExprResult Result;
  1523. if (VerifyOnly) {
  1524. if (SemaRef.CanPerformCopyInitialization(Entity,expr))
  1525. Result = getDummyInit();
  1526. else
  1527. Result = ExprError();
  1528. } else {
  1529. Result =
  1530. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1531. /*TopLevelOfInitList=*/true);
  1532. }
  1533. if (Result.isInvalid())
  1534. hadError = true;
  1535. expr = Result.getAs<Expr>();
  1536. // FIXME: Why are we updating the syntactic init list?
  1537. if (!VerifyOnly && expr)
  1538. IList->setInit(Index, expr);
  1539. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1540. ++Index;
  1541. }
  1542. void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
  1543. InitListExpr *IList, QualType DeclType,
  1544. unsigned &Index,
  1545. InitListExpr *StructuredList,
  1546. unsigned &StructuredIndex) {
  1547. const VectorType *VT = DeclType->castAs<VectorType>();
  1548. unsigned maxElements = VT->getNumElements();
  1549. unsigned numEltsInit = 0;
  1550. QualType elementType = VT->getElementType();
  1551. if (Index >= IList->getNumInits()) {
  1552. // Make sure the element type can be value-initialized.
  1553. CheckEmptyInitializable(
  1554. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1555. IList->getEndLoc());
  1556. return;
  1557. }
  1558. if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
  1559. // If the initializing element is a vector, try to copy-initialize
  1560. // instead of breaking it apart (which is doomed to failure anyway).
  1561. Expr *Init = IList->getInit(Index);
  1562. if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
  1563. ExprResult Result;
  1564. if (VerifyOnly) {
  1565. if (SemaRef.CanPerformCopyInitialization(Entity, Init))
  1566. Result = getDummyInit();
  1567. else
  1568. Result = ExprError();
  1569. } else {
  1570. Result =
  1571. SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
  1572. /*TopLevelOfInitList=*/true);
  1573. }
  1574. Expr *ResultExpr = nullptr;
  1575. if (Result.isInvalid())
  1576. hadError = true; // types weren't compatible.
  1577. else {
  1578. ResultExpr = Result.getAs<Expr>();
  1579. if (ResultExpr != Init && !VerifyOnly) {
  1580. // The type was promoted, update initializer list.
  1581. // FIXME: Why are we updating the syntactic init list?
  1582. IList->setInit(Index, ResultExpr);
  1583. }
  1584. }
  1585. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  1586. ++Index;
  1587. return;
  1588. }
  1589. InitializedEntity ElementEntity =
  1590. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1591. for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
  1592. // Don't attempt to go past the end of the init list
  1593. if (Index >= IList->getNumInits()) {
  1594. CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
  1595. break;
  1596. }
  1597. ElementEntity.setElementIndex(Index);
  1598. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1599. StructuredList, StructuredIndex);
  1600. }
  1601. if (VerifyOnly)
  1602. return;
  1603. bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
  1604. const VectorType *T = Entity.getType()->castAs<VectorType>();
  1605. if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
  1606. T->getVectorKind() == VectorType::NeonPolyVector)) {
  1607. // The ability to use vector initializer lists is a GNU vector extension
  1608. // and is unrelated to the NEON intrinsics in arm_neon.h. On little
  1609. // endian machines it works fine, however on big endian machines it
  1610. // exhibits surprising behaviour:
  1611. //
  1612. // uint32x2_t x = {42, 64};
  1613. // return vget_lane_u32(x, 0); // Will return 64.
  1614. //
  1615. // Because of this, explicitly call out that it is non-portable.
  1616. //
  1617. SemaRef.Diag(IList->getBeginLoc(),
  1618. diag::warn_neon_vector_initializer_non_portable);
  1619. const char *typeCode;
  1620. unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
  1621. if (elementType->isFloatingType())
  1622. typeCode = "f";
  1623. else if (elementType->isSignedIntegerType())
  1624. typeCode = "s";
  1625. else if (elementType->isUnsignedIntegerType())
  1626. typeCode = "u";
  1627. else
  1628. llvm_unreachable("Invalid element type!");
  1629. SemaRef.Diag(IList->getBeginLoc(),
  1630. SemaRef.Context.getTypeSize(VT) > 64
  1631. ? diag::note_neon_vector_initializer_non_portable_q
  1632. : diag::note_neon_vector_initializer_non_portable)
  1633. << typeCode << typeSize;
  1634. }
  1635. return;
  1636. }
  1637. InitializedEntity ElementEntity =
  1638. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1639. // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
  1640. for (unsigned i = 0; i < maxElements; ++i) {
  1641. // Don't attempt to go past the end of the init list
  1642. if (Index >= IList->getNumInits())
  1643. break;
  1644. ElementEntity.setElementIndex(Index);
  1645. QualType IType = IList->getInit(Index)->getType();
  1646. if (!IType->isVectorType()) {
  1647. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1648. StructuredList, StructuredIndex);
  1649. ++numEltsInit;
  1650. } else {
  1651. QualType VecType;
  1652. const VectorType *IVT = IType->castAs<VectorType>();
  1653. unsigned numIElts = IVT->getNumElements();
  1654. if (IType->isExtVectorType())
  1655. VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
  1656. else
  1657. VecType = SemaRef.Context.getVectorType(elementType, numIElts,
  1658. IVT->getVectorKind());
  1659. CheckSubElementType(ElementEntity, IList, VecType, Index,
  1660. StructuredList, StructuredIndex);
  1661. numEltsInit += numIElts;
  1662. }
  1663. }
  1664. // OpenCL and HLSL require all elements to be initialized.
  1665. if (numEltsInit != maxElements) {
  1666. if (!VerifyOnly)
  1667. SemaRef.Diag(IList->getBeginLoc(),
  1668. diag::err_vector_incorrect_num_initializers)
  1669. << (numEltsInit < maxElements) << maxElements << numEltsInit;
  1670. hadError = true;
  1671. }
  1672. }
  1673. /// Check if the type of a class element has an accessible destructor, and marks
  1674. /// it referenced. Returns true if we shouldn't form a reference to the
  1675. /// destructor.
  1676. ///
  1677. /// Aggregate initialization requires a class element's destructor be
  1678. /// accessible per 11.6.1 [dcl.init.aggr]:
  1679. ///
  1680. /// The destructor for each element of class type is potentially invoked
  1681. /// (15.4 [class.dtor]) from the context where the aggregate initialization
  1682. /// occurs.
  1683. static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
  1684. Sema &SemaRef) {
  1685. auto *CXXRD = ElementType->getAsCXXRecordDecl();
  1686. if (!CXXRD)
  1687. return false;
  1688. CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
  1689. SemaRef.CheckDestructorAccess(Loc, Destructor,
  1690. SemaRef.PDiag(diag::err_access_dtor_temp)
  1691. << ElementType);
  1692. SemaRef.MarkFunctionReferenced(Loc, Destructor);
  1693. return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
  1694. }
  1695. void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
  1696. InitListExpr *IList, QualType &DeclType,
  1697. llvm::APSInt elementIndex,
  1698. bool SubobjectIsDesignatorContext,
  1699. unsigned &Index,
  1700. InitListExpr *StructuredList,
  1701. unsigned &StructuredIndex) {
  1702. const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
  1703. if (!VerifyOnly) {
  1704. if (checkDestructorReference(arrayType->getElementType(),
  1705. IList->getEndLoc(), SemaRef)) {
  1706. hadError = true;
  1707. return;
  1708. }
  1709. }
  1710. // Check for the special-case of initializing an array with a string.
  1711. if (Index < IList->getNumInits()) {
  1712. if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
  1713. SIF_None) {
  1714. // We place the string literal directly into the resulting
  1715. // initializer list. This is the only place where the structure
  1716. // of the structured initializer list doesn't match exactly,
  1717. // because doing so would involve allocating one character
  1718. // constant for each string.
  1719. // FIXME: Should we do these checks in verify-only mode too?
  1720. if (!VerifyOnly)
  1721. CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
  1722. if (StructuredList) {
  1723. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1724. IList->getInit(Index));
  1725. StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
  1726. }
  1727. ++Index;
  1728. return;
  1729. }
  1730. }
  1731. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
  1732. // Check for VLAs; in standard C it would be possible to check this
  1733. // earlier, but I don't know where clang accepts VLAs (gcc accepts
  1734. // them in all sorts of strange places).
  1735. if (!VerifyOnly)
  1736. SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
  1737. diag::err_variable_object_no_init)
  1738. << VAT->getSizeExpr()->getSourceRange();
  1739. hadError = true;
  1740. ++Index;
  1741. ++StructuredIndex;
  1742. return;
  1743. }
  1744. // We might know the maximum number of elements in advance.
  1745. llvm::APSInt maxElements(elementIndex.getBitWidth(),
  1746. elementIndex.isUnsigned());
  1747. bool maxElementsKnown = false;
  1748. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
  1749. maxElements = CAT->getSize();
  1750. elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
  1751. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1752. maxElementsKnown = true;
  1753. }
  1754. QualType elementType = arrayType->getElementType();
  1755. while (Index < IList->getNumInits()) {
  1756. Expr *Init = IList->getInit(Index);
  1757. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1758. // If we're not the subobject that matches up with the '{' for
  1759. // the designator, we shouldn't be handling the
  1760. // designator. Return immediately.
  1761. if (!SubobjectIsDesignatorContext)
  1762. return;
  1763. // Handle this designated initializer. elementIndex will be
  1764. // updated to be the next array element we'll initialize.
  1765. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1766. DeclType, nullptr, &elementIndex, Index,
  1767. StructuredList, StructuredIndex, true,
  1768. false)) {
  1769. hadError = true;
  1770. continue;
  1771. }
  1772. if (elementIndex.getBitWidth() > maxElements.getBitWidth())
  1773. maxElements = maxElements.extend(elementIndex.getBitWidth());
  1774. else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
  1775. elementIndex = elementIndex.extend(maxElements.getBitWidth());
  1776. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1777. // If the array is of incomplete type, keep track of the number of
  1778. // elements in the initializer.
  1779. if (!maxElementsKnown && elementIndex > maxElements)
  1780. maxElements = elementIndex;
  1781. continue;
  1782. }
  1783. // If we know the maximum number of elements, and we've already
  1784. // hit it, stop consuming elements in the initializer list.
  1785. if (maxElementsKnown && elementIndex == maxElements)
  1786. break;
  1787. InitializedEntity ElementEntity =
  1788. InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
  1789. Entity);
  1790. // Check this element.
  1791. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1792. StructuredList, StructuredIndex);
  1793. ++elementIndex;
  1794. // If the array is of incomplete type, keep track of the number of
  1795. // elements in the initializer.
  1796. if (!maxElementsKnown && elementIndex > maxElements)
  1797. maxElements = elementIndex;
  1798. }
  1799. if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
  1800. // If this is an incomplete array type, the actual type needs to
  1801. // be calculated here.
  1802. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
  1803. if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
  1804. // Sizing an array implicitly to zero is not allowed by ISO C,
  1805. // but is supported by GNU.
  1806. SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
  1807. }
  1808. DeclType = SemaRef.Context.getConstantArrayType(
  1809. elementType, maxElements, nullptr, ArrayType::Normal, 0);
  1810. }
  1811. if (!hadError) {
  1812. // If there are any members of the array that get value-initialized, check
  1813. // that is possible. That happens if we know the bound and don't have
  1814. // enough elements, or if we're performing an array new with an unknown
  1815. // bound.
  1816. if ((maxElementsKnown && elementIndex < maxElements) ||
  1817. Entity.isVariableLengthArrayNew())
  1818. CheckEmptyInitializable(
  1819. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1820. IList->getEndLoc());
  1821. }
  1822. }
  1823. bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
  1824. Expr *InitExpr,
  1825. FieldDecl *Field,
  1826. bool TopLevelObject) {
  1827. // Handle GNU flexible array initializers.
  1828. unsigned FlexArrayDiag;
  1829. if (isa<InitListExpr>(InitExpr) &&
  1830. cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
  1831. // Empty flexible array init always allowed as an extension
  1832. FlexArrayDiag = diag::ext_flexible_array_init;
  1833. } else if (!TopLevelObject) {
  1834. // Disallow flexible array init on non-top-level object
  1835. FlexArrayDiag = diag::err_flexible_array_init;
  1836. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  1837. // Disallow flexible array init on anything which is not a variable.
  1838. FlexArrayDiag = diag::err_flexible_array_init;
  1839. } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
  1840. // Disallow flexible array init on local variables.
  1841. FlexArrayDiag = diag::err_flexible_array_init;
  1842. } else {
  1843. // Allow other cases.
  1844. FlexArrayDiag = diag::ext_flexible_array_init;
  1845. }
  1846. if (!VerifyOnly) {
  1847. SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
  1848. << InitExpr->getBeginLoc();
  1849. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1850. << Field;
  1851. }
  1852. return FlexArrayDiag != diag::ext_flexible_array_init;
  1853. }
  1854. void InitListChecker::CheckStructUnionTypes(
  1855. const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
  1856. CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
  1857. bool SubobjectIsDesignatorContext, unsigned &Index,
  1858. InitListExpr *StructuredList, unsigned &StructuredIndex,
  1859. bool TopLevelObject) {
  1860. RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
  1861. // If the record is invalid, some of it's members are invalid. To avoid
  1862. // confusion, we forgo checking the initializer for the entire record.
  1863. if (structDecl->isInvalidDecl()) {
  1864. // Assume it was supposed to consume a single initializer.
  1865. ++Index;
  1866. hadError = true;
  1867. return;
  1868. }
  1869. if (DeclType->isUnionType() && IList->getNumInits() == 0) {
  1870. RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
  1871. if (!VerifyOnly)
  1872. for (FieldDecl *FD : RD->fields()) {
  1873. QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
  1874. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  1875. hadError = true;
  1876. return;
  1877. }
  1878. }
  1879. // If there's a default initializer, use it.
  1880. if (isa<CXXRecordDecl>(RD) &&
  1881. cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
  1882. if (!StructuredList)
  1883. return;
  1884. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1885. Field != FieldEnd; ++Field) {
  1886. if (Field->hasInClassInitializer()) {
  1887. StructuredList->setInitializedFieldInUnion(*Field);
  1888. // FIXME: Actually build a CXXDefaultInitExpr?
  1889. return;
  1890. }
  1891. }
  1892. }
  1893. // Value-initialize the first member of the union that isn't an unnamed
  1894. // bitfield.
  1895. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1896. Field != FieldEnd; ++Field) {
  1897. if (!Field->isUnnamedBitfield()) {
  1898. CheckEmptyInitializable(
  1899. InitializedEntity::InitializeMember(*Field, &Entity),
  1900. IList->getEndLoc());
  1901. if (StructuredList)
  1902. StructuredList->setInitializedFieldInUnion(*Field);
  1903. break;
  1904. }
  1905. }
  1906. return;
  1907. }
  1908. bool InitializedSomething = false;
  1909. // If we have any base classes, they are initialized prior to the fields.
  1910. for (auto &Base : Bases) {
  1911. Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
  1912. // Designated inits always initialize fields, so if we see one, all
  1913. // remaining base classes have no explicit initializer.
  1914. if (Init && isa<DesignatedInitExpr>(Init))
  1915. Init = nullptr;
  1916. SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
  1917. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  1918. SemaRef.Context, &Base, false, &Entity);
  1919. if (Init) {
  1920. CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
  1921. StructuredList, StructuredIndex);
  1922. InitializedSomething = true;
  1923. } else {
  1924. CheckEmptyInitializable(BaseEntity, InitLoc);
  1925. }
  1926. if (!VerifyOnly)
  1927. if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
  1928. hadError = true;
  1929. return;
  1930. }
  1931. }
  1932. // If structDecl is a forward declaration, this loop won't do
  1933. // anything except look at designated initializers; That's okay,
  1934. // because an error should get printed out elsewhere. It might be
  1935. // worthwhile to skip over the rest of the initializer, though.
  1936. RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
  1937. RecordDecl::field_iterator FieldEnd = RD->field_end();
  1938. size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
  1939. return isa<FieldDecl>(D) || isa<RecordDecl>(D);
  1940. });
  1941. bool CheckForMissingFields =
  1942. !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
  1943. bool HasDesignatedInit = false;
  1944. while (Index < IList->getNumInits()) {
  1945. Expr *Init = IList->getInit(Index);
  1946. SourceLocation InitLoc = Init->getBeginLoc();
  1947. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1948. // If we're not the subobject that matches up with the '{' for
  1949. // the designator, we shouldn't be handling the
  1950. // designator. Return immediately.
  1951. if (!SubobjectIsDesignatorContext)
  1952. return;
  1953. HasDesignatedInit = true;
  1954. // Handle this designated initializer. Field will be updated to
  1955. // the next field that we'll be initializing.
  1956. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1957. DeclType, &Field, nullptr, Index,
  1958. StructuredList, StructuredIndex,
  1959. true, TopLevelObject))
  1960. hadError = true;
  1961. else if (!VerifyOnly) {
  1962. // Find the field named by the designated initializer.
  1963. RecordDecl::field_iterator F = RD->field_begin();
  1964. while (std::next(F) != Field)
  1965. ++F;
  1966. QualType ET = SemaRef.Context.getBaseElementType(F->getType());
  1967. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  1968. hadError = true;
  1969. return;
  1970. }
  1971. }
  1972. InitializedSomething = true;
  1973. // Disable check for missing fields when designators are used.
  1974. // This matches gcc behaviour.
  1975. CheckForMissingFields = false;
  1976. continue;
  1977. }
  1978. // Check if this is an initializer of forms:
  1979. //
  1980. // struct foo f = {};
  1981. // struct foo g = {0};
  1982. //
  1983. // These are okay for randomized structures. [C99 6.7.8p19]
  1984. //
  1985. // Also, if there is only one element in the structure, we allow something
  1986. // like this, because it's really not randomized in the tranditional sense.
  1987. //
  1988. // struct foo h = {bar};
  1989. auto IsZeroInitializer = [&](const Expr *I) {
  1990. if (IList->getNumInits() == 1) {
  1991. if (NumRecordDecls == 1)
  1992. return true;
  1993. if (const auto *IL = dyn_cast<IntegerLiteral>(I))
  1994. return IL->getValue().isZero();
  1995. }
  1996. return false;
  1997. };
  1998. // Don't allow non-designated initializers on randomized structures.
  1999. if (RD->isRandomized() && !IsZeroInitializer(Init)) {
  2000. if (!VerifyOnly)
  2001. SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
  2002. hadError = true;
  2003. break;
  2004. }
  2005. if (Field == FieldEnd) {
  2006. // We've run out of fields. We're done.
  2007. break;
  2008. }
  2009. // We've already initialized a member of a union. We're done.
  2010. if (InitializedSomething && DeclType->isUnionType())
  2011. break;
  2012. // If we've hit the flexible array member at the end, we're done.
  2013. if (Field->getType()->isIncompleteArrayType())
  2014. break;
  2015. if (Field->isUnnamedBitfield()) {
  2016. // Don't initialize unnamed bitfields, e.g. "int : 20;"
  2017. ++Field;
  2018. continue;
  2019. }
  2020. // Make sure we can use this declaration.
  2021. bool InvalidUse;
  2022. if (VerifyOnly)
  2023. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  2024. else
  2025. InvalidUse = SemaRef.DiagnoseUseOfDecl(
  2026. *Field, IList->getInit(Index)->getBeginLoc());
  2027. if (InvalidUse) {
  2028. ++Index;
  2029. ++Field;
  2030. hadError = true;
  2031. continue;
  2032. }
  2033. if (!VerifyOnly) {
  2034. QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
  2035. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  2036. hadError = true;
  2037. return;
  2038. }
  2039. }
  2040. InitializedEntity MemberEntity =
  2041. InitializedEntity::InitializeMember(*Field, &Entity);
  2042. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2043. StructuredList, StructuredIndex);
  2044. InitializedSomething = true;
  2045. if (DeclType->isUnionType() && StructuredList) {
  2046. // Initialize the first field within the union.
  2047. StructuredList->setInitializedFieldInUnion(*Field);
  2048. }
  2049. ++Field;
  2050. }
  2051. // Emit warnings for missing struct field initializers.
  2052. if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
  2053. Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
  2054. !DeclType->isUnionType()) {
  2055. // It is possible we have one or more unnamed bitfields remaining.
  2056. // Find first (if any) named field and emit warning.
  2057. for (RecordDecl::field_iterator it = Field, end = RD->field_end();
  2058. it != end; ++it) {
  2059. if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
  2060. SemaRef.Diag(IList->getSourceRange().getEnd(),
  2061. diag::warn_missing_field_initializers) << *it;
  2062. break;
  2063. }
  2064. }
  2065. }
  2066. // Check that any remaining fields can be value-initialized if we're not
  2067. // building a structured list. (If we are, we'll check this later.)
  2068. if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
  2069. !Field->getType()->isIncompleteArrayType()) {
  2070. for (; Field != FieldEnd && !hadError; ++Field) {
  2071. if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
  2072. CheckEmptyInitializable(
  2073. InitializedEntity::InitializeMember(*Field, &Entity),
  2074. IList->getEndLoc());
  2075. }
  2076. }
  2077. // Check that the types of the remaining fields have accessible destructors.
  2078. if (!VerifyOnly) {
  2079. // If the initializer expression has a designated initializer, check the
  2080. // elements for which a designated initializer is not provided too.
  2081. RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
  2082. : Field;
  2083. for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
  2084. QualType ET = SemaRef.Context.getBaseElementType(I->getType());
  2085. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  2086. hadError = true;
  2087. return;
  2088. }
  2089. }
  2090. }
  2091. if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
  2092. Index >= IList->getNumInits())
  2093. return;
  2094. if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
  2095. TopLevelObject)) {
  2096. hadError = true;
  2097. ++Index;
  2098. return;
  2099. }
  2100. InitializedEntity MemberEntity =
  2101. InitializedEntity::InitializeMember(*Field, &Entity);
  2102. if (isa<InitListExpr>(IList->getInit(Index)))
  2103. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2104. StructuredList, StructuredIndex);
  2105. else
  2106. CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
  2107. StructuredList, StructuredIndex);
  2108. }
  2109. /// Expand a field designator that refers to a member of an
  2110. /// anonymous struct or union into a series of field designators that
  2111. /// refers to the field within the appropriate subobject.
  2112. ///
  2113. static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
  2114. DesignatedInitExpr *DIE,
  2115. unsigned DesigIdx,
  2116. IndirectFieldDecl *IndirectField) {
  2117. typedef DesignatedInitExpr::Designator Designator;
  2118. // Build the replacement designators.
  2119. SmallVector<Designator, 4> Replacements;
  2120. for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
  2121. PE = IndirectField->chain_end(); PI != PE; ++PI) {
  2122. if (PI + 1 == PE)
  2123. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  2124. DIE->getDesignator(DesigIdx)->getDotLoc(),
  2125. DIE->getDesignator(DesigIdx)->getFieldLoc()));
  2126. else
  2127. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  2128. SourceLocation(), SourceLocation()));
  2129. assert(isa<FieldDecl>(*PI));
  2130. Replacements.back().setField(cast<FieldDecl>(*PI));
  2131. }
  2132. // Expand the current designator into the set of replacement
  2133. // designators, so we have a full subobject path down to where the
  2134. // member of the anonymous struct/union is actually stored.
  2135. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
  2136. &Replacements[0] + Replacements.size());
  2137. }
  2138. static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
  2139. DesignatedInitExpr *DIE) {
  2140. unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
  2141. SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
  2142. for (unsigned I = 0; I < NumIndexExprs; ++I)
  2143. IndexExprs[I] = DIE->getSubExpr(I + 1);
  2144. return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
  2145. IndexExprs,
  2146. DIE->getEqualOrColonLoc(),
  2147. DIE->usesGNUSyntax(), DIE->getInit());
  2148. }
  2149. namespace {
  2150. // Callback to only accept typo corrections that are for field members of
  2151. // the given struct or union.
  2152. class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
  2153. public:
  2154. explicit FieldInitializerValidatorCCC(RecordDecl *RD)
  2155. : Record(RD) {}
  2156. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2157. FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
  2158. return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
  2159. }
  2160. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2161. return std::make_unique<FieldInitializerValidatorCCC>(*this);
  2162. }
  2163. private:
  2164. RecordDecl *Record;
  2165. };
  2166. } // end anonymous namespace
  2167. /// Check the well-formedness of a C99 designated initializer.
  2168. ///
  2169. /// Determines whether the designated initializer @p DIE, which
  2170. /// resides at the given @p Index within the initializer list @p
  2171. /// IList, is well-formed for a current object of type @p DeclType
  2172. /// (C99 6.7.8). The actual subobject that this designator refers to
  2173. /// within the current subobject is returned in either
  2174. /// @p NextField or @p NextElementIndex (whichever is appropriate).
  2175. ///
  2176. /// @param IList The initializer list in which this designated
  2177. /// initializer occurs.
  2178. ///
  2179. /// @param DIE The designated initializer expression.
  2180. ///
  2181. /// @param DesigIdx The index of the current designator.
  2182. ///
  2183. /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
  2184. /// into which the designation in @p DIE should refer.
  2185. ///
  2186. /// @param NextField If non-NULL and the first designator in @p DIE is
  2187. /// a field, this will be set to the field declaration corresponding
  2188. /// to the field named by the designator. On input, this is expected to be
  2189. /// the next field that would be initialized in the absence of designation,
  2190. /// if the complete object being initialized is a struct.
  2191. ///
  2192. /// @param NextElementIndex If non-NULL and the first designator in @p
  2193. /// DIE is an array designator or GNU array-range designator, this
  2194. /// will be set to the last index initialized by this designator.
  2195. ///
  2196. /// @param Index Index into @p IList where the designated initializer
  2197. /// @p DIE occurs.
  2198. ///
  2199. /// @param StructuredList The initializer list expression that
  2200. /// describes all of the subobject initializers in the order they'll
  2201. /// actually be initialized.
  2202. ///
  2203. /// @returns true if there was an error, false otherwise.
  2204. bool
  2205. InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
  2206. InitListExpr *IList,
  2207. DesignatedInitExpr *DIE,
  2208. unsigned DesigIdx,
  2209. QualType &CurrentObjectType,
  2210. RecordDecl::field_iterator *NextField,
  2211. llvm::APSInt *NextElementIndex,
  2212. unsigned &Index,
  2213. InitListExpr *StructuredList,
  2214. unsigned &StructuredIndex,
  2215. bool FinishSubobjectInit,
  2216. bool TopLevelObject) {
  2217. if (DesigIdx == DIE->size()) {
  2218. // C++20 designated initialization can result in direct-list-initialization
  2219. // of the designated subobject. This is the only way that we can end up
  2220. // performing direct initialization as part of aggregate initialization, so
  2221. // it needs special handling.
  2222. if (DIE->isDirectInit()) {
  2223. Expr *Init = DIE->getInit();
  2224. assert(isa<InitListExpr>(Init) &&
  2225. "designator result in direct non-list initialization?");
  2226. InitializationKind Kind = InitializationKind::CreateDirectList(
  2227. DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
  2228. InitializationSequence Seq(SemaRef, Entity, Kind, Init,
  2229. /*TopLevelOfInitList*/ true);
  2230. if (StructuredList) {
  2231. ExprResult Result = VerifyOnly
  2232. ? getDummyInit()
  2233. : Seq.Perform(SemaRef, Entity, Kind, Init);
  2234. UpdateStructuredListElement(StructuredList, StructuredIndex,
  2235. Result.get());
  2236. }
  2237. ++Index;
  2238. return !Seq;
  2239. }
  2240. // Check the actual initialization for the designated object type.
  2241. bool prevHadError = hadError;
  2242. // Temporarily remove the designator expression from the
  2243. // initializer list that the child calls see, so that we don't try
  2244. // to re-process the designator.
  2245. unsigned OldIndex = Index;
  2246. IList->setInit(OldIndex, DIE->getInit());
  2247. CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
  2248. StructuredIndex, /*DirectlyDesignated=*/true);
  2249. // Restore the designated initializer expression in the syntactic
  2250. // form of the initializer list.
  2251. if (IList->getInit(OldIndex) != DIE->getInit())
  2252. DIE->setInit(IList->getInit(OldIndex));
  2253. IList->setInit(OldIndex, DIE);
  2254. return hadError && !prevHadError;
  2255. }
  2256. DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
  2257. bool IsFirstDesignator = (DesigIdx == 0);
  2258. if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
  2259. // Determine the structural initializer list that corresponds to the
  2260. // current subobject.
  2261. if (IsFirstDesignator)
  2262. StructuredList = FullyStructuredList;
  2263. else {
  2264. Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
  2265. StructuredList->getInit(StructuredIndex) : nullptr;
  2266. if (!ExistingInit && StructuredList->hasArrayFiller())
  2267. ExistingInit = StructuredList->getArrayFiller();
  2268. if (!ExistingInit)
  2269. StructuredList = getStructuredSubobjectInit(
  2270. IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
  2271. SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
  2272. else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
  2273. StructuredList = Result;
  2274. else {
  2275. // We are creating an initializer list that initializes the
  2276. // subobjects of the current object, but there was already an
  2277. // initialization that completely initialized the current
  2278. // subobject, e.g., by a compound literal:
  2279. //
  2280. // struct X { int a, b; };
  2281. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2282. //
  2283. // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
  2284. // designated initializer re-initializes only its current object
  2285. // subobject [0].b.
  2286. diagnoseInitOverride(ExistingInit,
  2287. SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
  2288. /*FullyOverwritten=*/false);
  2289. if (!VerifyOnly) {
  2290. if (DesignatedInitUpdateExpr *E =
  2291. dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
  2292. StructuredList = E->getUpdater();
  2293. else {
  2294. DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
  2295. DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
  2296. ExistingInit, DIE->getEndLoc());
  2297. StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
  2298. StructuredList = DIUE->getUpdater();
  2299. }
  2300. } else {
  2301. // We don't need to track the structured representation of a
  2302. // designated init update of an already-fully-initialized object in
  2303. // verify-only mode. The only reason we would need the structure is
  2304. // to determine where the uninitialized "holes" are, and in this
  2305. // case, we know there aren't any and we can't introduce any.
  2306. StructuredList = nullptr;
  2307. }
  2308. }
  2309. }
  2310. }
  2311. if (D->isFieldDesignator()) {
  2312. // C99 6.7.8p7:
  2313. //
  2314. // If a designator has the form
  2315. //
  2316. // . identifier
  2317. //
  2318. // then the current object (defined below) shall have
  2319. // structure or union type and the identifier shall be the
  2320. // name of a member of that type.
  2321. const RecordType *RT = CurrentObjectType->getAs<RecordType>();
  2322. if (!RT) {
  2323. SourceLocation Loc = D->getDotLoc();
  2324. if (Loc.isInvalid())
  2325. Loc = D->getFieldLoc();
  2326. if (!VerifyOnly)
  2327. SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
  2328. << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
  2329. ++Index;
  2330. return true;
  2331. }
  2332. FieldDecl *KnownField = D->getField();
  2333. if (!KnownField) {
  2334. IdentifierInfo *FieldName = D->getFieldName();
  2335. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
  2336. for (NamedDecl *ND : Lookup) {
  2337. if (auto *FD = dyn_cast<FieldDecl>(ND)) {
  2338. KnownField = FD;
  2339. break;
  2340. }
  2341. if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
  2342. // In verify mode, don't modify the original.
  2343. if (VerifyOnly)
  2344. DIE = CloneDesignatedInitExpr(SemaRef, DIE);
  2345. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
  2346. D = DIE->getDesignator(DesigIdx);
  2347. KnownField = cast<FieldDecl>(*IFD->chain_begin());
  2348. break;
  2349. }
  2350. }
  2351. if (!KnownField) {
  2352. if (VerifyOnly) {
  2353. ++Index;
  2354. return true; // No typo correction when just trying this out.
  2355. }
  2356. // Name lookup found something, but it wasn't a field.
  2357. if (!Lookup.empty()) {
  2358. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
  2359. << FieldName;
  2360. SemaRef.Diag(Lookup.front()->getLocation(),
  2361. diag::note_field_designator_found);
  2362. ++Index;
  2363. return true;
  2364. }
  2365. // Name lookup didn't find anything.
  2366. // Determine whether this was a typo for another field name.
  2367. FieldInitializerValidatorCCC CCC(RT->getDecl());
  2368. if (TypoCorrection Corrected = SemaRef.CorrectTypo(
  2369. DeclarationNameInfo(FieldName, D->getFieldLoc()),
  2370. Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
  2371. Sema::CTK_ErrorRecovery, RT->getDecl())) {
  2372. SemaRef.diagnoseTypo(
  2373. Corrected,
  2374. SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
  2375. << FieldName << CurrentObjectType);
  2376. KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
  2377. hadError = true;
  2378. } else {
  2379. // Typo correction didn't find anything.
  2380. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
  2381. << FieldName << CurrentObjectType;
  2382. ++Index;
  2383. return true;
  2384. }
  2385. }
  2386. }
  2387. unsigned NumBases = 0;
  2388. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2389. NumBases = CXXRD->getNumBases();
  2390. unsigned FieldIndex = NumBases;
  2391. for (auto *FI : RT->getDecl()->fields()) {
  2392. if (FI->isUnnamedBitfield())
  2393. continue;
  2394. if (declaresSameEntity(KnownField, FI)) {
  2395. KnownField = FI;
  2396. break;
  2397. }
  2398. ++FieldIndex;
  2399. }
  2400. RecordDecl::field_iterator Field =
  2401. RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
  2402. // All of the fields of a union are located at the same place in
  2403. // the initializer list.
  2404. if (RT->getDecl()->isUnion()) {
  2405. FieldIndex = 0;
  2406. if (StructuredList) {
  2407. FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
  2408. if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
  2409. assert(StructuredList->getNumInits() == 1
  2410. && "A union should never have more than one initializer!");
  2411. Expr *ExistingInit = StructuredList->getInit(0);
  2412. if (ExistingInit) {
  2413. // We're about to throw away an initializer, emit warning.
  2414. diagnoseInitOverride(
  2415. ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
  2416. }
  2417. // remove existing initializer
  2418. StructuredList->resizeInits(SemaRef.Context, 0);
  2419. StructuredList->setInitializedFieldInUnion(nullptr);
  2420. }
  2421. StructuredList->setInitializedFieldInUnion(*Field);
  2422. }
  2423. }
  2424. // Make sure we can use this declaration.
  2425. bool InvalidUse;
  2426. if (VerifyOnly)
  2427. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  2428. else
  2429. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
  2430. if (InvalidUse) {
  2431. ++Index;
  2432. return true;
  2433. }
  2434. // C++20 [dcl.init.list]p3:
  2435. // The ordered identifiers in the designators of the designated-
  2436. // initializer-list shall form a subsequence of the ordered identifiers
  2437. // in the direct non-static data members of T.
  2438. //
  2439. // Note that this is not a condition on forming the aggregate
  2440. // initialization, only on actually performing initialization,
  2441. // so it is not checked in VerifyOnly mode.
  2442. //
  2443. // FIXME: This is the only reordering diagnostic we produce, and it only
  2444. // catches cases where we have a top-level field designator that jumps
  2445. // backwards. This is the only such case that is reachable in an
  2446. // otherwise-valid C++20 program, so is the only case that's required for
  2447. // conformance, but for consistency, we should diagnose all the other
  2448. // cases where a designator takes us backwards too.
  2449. if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
  2450. NextField &&
  2451. (*NextField == RT->getDecl()->field_end() ||
  2452. (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
  2453. // Find the field that we just initialized.
  2454. FieldDecl *PrevField = nullptr;
  2455. for (auto FI = RT->getDecl()->field_begin();
  2456. FI != RT->getDecl()->field_end(); ++FI) {
  2457. if (FI->isUnnamedBitfield())
  2458. continue;
  2459. if (*NextField != RT->getDecl()->field_end() &&
  2460. declaresSameEntity(*FI, **NextField))
  2461. break;
  2462. PrevField = *FI;
  2463. }
  2464. if (PrevField &&
  2465. PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
  2466. SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
  2467. << KnownField << PrevField << DIE->getSourceRange();
  2468. unsigned OldIndex = NumBases + PrevField->getFieldIndex();
  2469. if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
  2470. if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
  2471. SemaRef.Diag(PrevInit->getBeginLoc(),
  2472. diag::note_previous_field_init)
  2473. << PrevField << PrevInit->getSourceRange();
  2474. }
  2475. }
  2476. }
  2477. }
  2478. // Update the designator with the field declaration.
  2479. if (!VerifyOnly)
  2480. D->setField(*Field);
  2481. // Make sure that our non-designated initializer list has space
  2482. // for a subobject corresponding to this field.
  2483. if (StructuredList && FieldIndex >= StructuredList->getNumInits())
  2484. StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
  2485. // This designator names a flexible array member.
  2486. if (Field->getType()->isIncompleteArrayType()) {
  2487. bool Invalid = false;
  2488. if ((DesigIdx + 1) != DIE->size()) {
  2489. // We can't designate an object within the flexible array
  2490. // member (because GCC doesn't allow it).
  2491. if (!VerifyOnly) {
  2492. DesignatedInitExpr::Designator *NextD
  2493. = DIE->getDesignator(DesigIdx + 1);
  2494. SemaRef.Diag(NextD->getBeginLoc(),
  2495. diag::err_designator_into_flexible_array_member)
  2496. << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
  2497. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2498. << *Field;
  2499. }
  2500. Invalid = true;
  2501. }
  2502. if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
  2503. !isa<StringLiteral>(DIE->getInit())) {
  2504. // The initializer is not an initializer list.
  2505. if (!VerifyOnly) {
  2506. SemaRef.Diag(DIE->getInit()->getBeginLoc(),
  2507. diag::err_flexible_array_init_needs_braces)
  2508. << DIE->getInit()->getSourceRange();
  2509. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2510. << *Field;
  2511. }
  2512. Invalid = true;
  2513. }
  2514. // Check GNU flexible array initializer.
  2515. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
  2516. TopLevelObject))
  2517. Invalid = true;
  2518. if (Invalid) {
  2519. ++Index;
  2520. return true;
  2521. }
  2522. // Initialize the array.
  2523. bool prevHadError = hadError;
  2524. unsigned newStructuredIndex = FieldIndex;
  2525. unsigned OldIndex = Index;
  2526. IList->setInit(Index, DIE->getInit());
  2527. InitializedEntity MemberEntity =
  2528. InitializedEntity::InitializeMember(*Field, &Entity);
  2529. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2530. StructuredList, newStructuredIndex);
  2531. IList->setInit(OldIndex, DIE);
  2532. if (hadError && !prevHadError) {
  2533. ++Field;
  2534. ++FieldIndex;
  2535. if (NextField)
  2536. *NextField = Field;
  2537. StructuredIndex = FieldIndex;
  2538. return true;
  2539. }
  2540. } else {
  2541. // Recurse to check later designated subobjects.
  2542. QualType FieldType = Field->getType();
  2543. unsigned newStructuredIndex = FieldIndex;
  2544. InitializedEntity MemberEntity =
  2545. InitializedEntity::InitializeMember(*Field, &Entity);
  2546. if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
  2547. FieldType, nullptr, nullptr, Index,
  2548. StructuredList, newStructuredIndex,
  2549. FinishSubobjectInit, false))
  2550. return true;
  2551. }
  2552. // Find the position of the next field to be initialized in this
  2553. // subobject.
  2554. ++Field;
  2555. ++FieldIndex;
  2556. // If this the first designator, our caller will continue checking
  2557. // the rest of this struct/class/union subobject.
  2558. if (IsFirstDesignator) {
  2559. if (NextField)
  2560. *NextField = Field;
  2561. StructuredIndex = FieldIndex;
  2562. return false;
  2563. }
  2564. if (!FinishSubobjectInit)
  2565. return false;
  2566. // We've already initialized something in the union; we're done.
  2567. if (RT->getDecl()->isUnion())
  2568. return hadError;
  2569. // Check the remaining fields within this class/struct/union subobject.
  2570. bool prevHadError = hadError;
  2571. auto NoBases =
  2572. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  2573. CXXRecordDecl::base_class_iterator());
  2574. CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
  2575. false, Index, StructuredList, FieldIndex);
  2576. return hadError && !prevHadError;
  2577. }
  2578. // C99 6.7.8p6:
  2579. //
  2580. // If a designator has the form
  2581. //
  2582. // [ constant-expression ]
  2583. //
  2584. // then the current object (defined below) shall have array
  2585. // type and the expression shall be an integer constant
  2586. // expression. If the array is of unknown size, any
  2587. // nonnegative value is valid.
  2588. //
  2589. // Additionally, cope with the GNU extension that permits
  2590. // designators of the form
  2591. //
  2592. // [ constant-expression ... constant-expression ]
  2593. const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
  2594. if (!AT) {
  2595. if (!VerifyOnly)
  2596. SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
  2597. << CurrentObjectType;
  2598. ++Index;
  2599. return true;
  2600. }
  2601. Expr *IndexExpr = nullptr;
  2602. llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
  2603. if (D->isArrayDesignator()) {
  2604. IndexExpr = DIE->getArrayIndex(*D);
  2605. DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
  2606. DesignatedEndIndex = DesignatedStartIndex;
  2607. } else {
  2608. assert(D->isArrayRangeDesignator() && "Need array-range designator");
  2609. DesignatedStartIndex =
  2610. DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2611. DesignatedEndIndex =
  2612. DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2613. IndexExpr = DIE->getArrayRangeEnd(*D);
  2614. // Codegen can't handle evaluating array range designators that have side
  2615. // effects, because we replicate the AST value for each initialized element.
  2616. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
  2617. // elements with something that has a side effect, so codegen can emit an
  2618. // "error unsupported" error instead of miscompiling the app.
  2619. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
  2620. DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
  2621. FullyStructuredList->sawArrayRangeDesignator();
  2622. }
  2623. if (isa<ConstantArrayType>(AT)) {
  2624. llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
  2625. DesignatedStartIndex
  2626. = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
  2627. DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
  2628. DesignatedEndIndex
  2629. = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
  2630. DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
  2631. if (DesignatedEndIndex >= MaxElements) {
  2632. if (!VerifyOnly)
  2633. SemaRef.Diag(IndexExpr->getBeginLoc(),
  2634. diag::err_array_designator_too_large)
  2635. << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
  2636. << IndexExpr->getSourceRange();
  2637. ++Index;
  2638. return true;
  2639. }
  2640. } else {
  2641. unsigned DesignatedIndexBitWidth =
  2642. ConstantArrayType::getMaxSizeBits(SemaRef.Context);
  2643. DesignatedStartIndex =
  2644. DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
  2645. DesignatedEndIndex =
  2646. DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
  2647. DesignatedStartIndex.setIsUnsigned(true);
  2648. DesignatedEndIndex.setIsUnsigned(true);
  2649. }
  2650. bool IsStringLiteralInitUpdate =
  2651. StructuredList && StructuredList->isStringLiteralInit();
  2652. if (IsStringLiteralInitUpdate && VerifyOnly) {
  2653. // We're just verifying an update to a string literal init. We don't need
  2654. // to split the string up into individual characters to do that.
  2655. StructuredList = nullptr;
  2656. } else if (IsStringLiteralInitUpdate) {
  2657. // We're modifying a string literal init; we have to decompose the string
  2658. // so we can modify the individual characters.
  2659. ASTContext &Context = SemaRef.Context;
  2660. Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
  2661. // Compute the character type
  2662. QualType CharTy = AT->getElementType();
  2663. // Compute the type of the integer literals.
  2664. QualType PromotedCharTy = CharTy;
  2665. if (Context.isPromotableIntegerType(CharTy))
  2666. PromotedCharTy = Context.getPromotedIntegerType(CharTy);
  2667. unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
  2668. if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
  2669. // Get the length of the string.
  2670. uint64_t StrLen = SL->getLength();
  2671. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2672. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2673. StructuredList->resizeInits(Context, StrLen);
  2674. // Build a literal for each character in the string, and put them into
  2675. // the init list.
  2676. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2677. llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
  2678. Expr *Init = new (Context) IntegerLiteral(
  2679. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2680. if (CharTy != PromotedCharTy)
  2681. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2682. Init, nullptr, VK_PRValue,
  2683. FPOptionsOverride());
  2684. StructuredList->updateInit(Context, i, Init);
  2685. }
  2686. } else {
  2687. ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
  2688. std::string Str;
  2689. Context.getObjCEncodingForType(E->getEncodedType(), Str);
  2690. // Get the length of the string.
  2691. uint64_t StrLen = Str.size();
  2692. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2693. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2694. StructuredList->resizeInits(Context, StrLen);
  2695. // Build a literal for each character in the string, and put them into
  2696. // the init list.
  2697. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2698. llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
  2699. Expr *Init = new (Context) IntegerLiteral(
  2700. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2701. if (CharTy != PromotedCharTy)
  2702. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2703. Init, nullptr, VK_PRValue,
  2704. FPOptionsOverride());
  2705. StructuredList->updateInit(Context, i, Init);
  2706. }
  2707. }
  2708. }
  2709. // Make sure that our non-designated initializer list has space
  2710. // for a subobject corresponding to this array element.
  2711. if (StructuredList &&
  2712. DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
  2713. StructuredList->resizeInits(SemaRef.Context,
  2714. DesignatedEndIndex.getZExtValue() + 1);
  2715. // Repeatedly perform subobject initializations in the range
  2716. // [DesignatedStartIndex, DesignatedEndIndex].
  2717. // Move to the next designator
  2718. unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
  2719. unsigned OldIndex = Index;
  2720. InitializedEntity ElementEntity =
  2721. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  2722. while (DesignatedStartIndex <= DesignatedEndIndex) {
  2723. // Recurse to check later designated subobjects.
  2724. QualType ElementType = AT->getElementType();
  2725. Index = OldIndex;
  2726. ElementEntity.setElementIndex(ElementIndex);
  2727. if (CheckDesignatedInitializer(
  2728. ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
  2729. nullptr, Index, StructuredList, ElementIndex,
  2730. FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
  2731. false))
  2732. return true;
  2733. // Move to the next index in the array that we'll be initializing.
  2734. ++DesignatedStartIndex;
  2735. ElementIndex = DesignatedStartIndex.getZExtValue();
  2736. }
  2737. // If this the first designator, our caller will continue checking
  2738. // the rest of this array subobject.
  2739. if (IsFirstDesignator) {
  2740. if (NextElementIndex)
  2741. *NextElementIndex = DesignatedStartIndex;
  2742. StructuredIndex = ElementIndex;
  2743. return false;
  2744. }
  2745. if (!FinishSubobjectInit)
  2746. return false;
  2747. // Check the remaining elements within this array subobject.
  2748. bool prevHadError = hadError;
  2749. CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
  2750. /*SubobjectIsDesignatorContext=*/false, Index,
  2751. StructuredList, ElementIndex);
  2752. return hadError && !prevHadError;
  2753. }
  2754. // Get the structured initializer list for a subobject of type
  2755. // @p CurrentObjectType.
  2756. InitListExpr *
  2757. InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  2758. QualType CurrentObjectType,
  2759. InitListExpr *StructuredList,
  2760. unsigned StructuredIndex,
  2761. SourceRange InitRange,
  2762. bool IsFullyOverwritten) {
  2763. if (!StructuredList)
  2764. return nullptr;
  2765. Expr *ExistingInit = nullptr;
  2766. if (StructuredIndex < StructuredList->getNumInits())
  2767. ExistingInit = StructuredList->getInit(StructuredIndex);
  2768. if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
  2769. // There might have already been initializers for subobjects of the current
  2770. // object, but a subsequent initializer list will overwrite the entirety
  2771. // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
  2772. //
  2773. // struct P { char x[6]; };
  2774. // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
  2775. //
  2776. // The first designated initializer is ignored, and l.x is just "f".
  2777. if (!IsFullyOverwritten)
  2778. return Result;
  2779. if (ExistingInit) {
  2780. // We are creating an initializer list that initializes the
  2781. // subobjects of the current object, but there was already an
  2782. // initialization that completely initialized the current
  2783. // subobject:
  2784. //
  2785. // struct X { int a, b; };
  2786. // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
  2787. //
  2788. // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
  2789. // designated initializer overwrites the [0].b initializer
  2790. // from the prior initialization.
  2791. //
  2792. // When the existing initializer is an expression rather than an
  2793. // initializer list, we cannot decompose and update it in this way.
  2794. // For example:
  2795. //
  2796. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2797. //
  2798. // This case is handled by CheckDesignatedInitializer.
  2799. diagnoseInitOverride(ExistingInit, InitRange);
  2800. }
  2801. unsigned ExpectedNumInits = 0;
  2802. if (Index < IList->getNumInits()) {
  2803. if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
  2804. ExpectedNumInits = Init->getNumInits();
  2805. else
  2806. ExpectedNumInits = IList->getNumInits() - Index;
  2807. }
  2808. InitListExpr *Result =
  2809. createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
  2810. // Link this new initializer list into the structured initializer
  2811. // lists.
  2812. StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
  2813. return Result;
  2814. }
  2815. InitListExpr *
  2816. InitListChecker::createInitListExpr(QualType CurrentObjectType,
  2817. SourceRange InitRange,
  2818. unsigned ExpectedNumInits) {
  2819. InitListExpr *Result = new (SemaRef.Context) InitListExpr(
  2820. SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
  2821. QualType ResultType = CurrentObjectType;
  2822. if (!ResultType->isArrayType())
  2823. ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
  2824. Result->setType(ResultType);
  2825. // Pre-allocate storage for the structured initializer list.
  2826. unsigned NumElements = 0;
  2827. if (const ArrayType *AType
  2828. = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
  2829. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
  2830. NumElements = CAType->getSize().getZExtValue();
  2831. // Simple heuristic so that we don't allocate a very large
  2832. // initializer with many empty entries at the end.
  2833. if (NumElements > ExpectedNumInits)
  2834. NumElements = 0;
  2835. }
  2836. } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
  2837. NumElements = VType->getNumElements();
  2838. } else if (CurrentObjectType->isRecordType()) {
  2839. NumElements = numStructUnionElements(CurrentObjectType);
  2840. }
  2841. Result->reserveInits(SemaRef.Context, NumElements);
  2842. return Result;
  2843. }
  2844. /// Update the initializer at index @p StructuredIndex within the
  2845. /// structured initializer list to the value @p expr.
  2846. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
  2847. unsigned &StructuredIndex,
  2848. Expr *expr) {
  2849. // No structured initializer list to update
  2850. if (!StructuredList)
  2851. return;
  2852. if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
  2853. StructuredIndex, expr)) {
  2854. // This initializer overwrites a previous initializer.
  2855. // No need to diagnose when `expr` is nullptr because a more relevant
  2856. // diagnostic has already been issued and this diagnostic is potentially
  2857. // noise.
  2858. if (expr)
  2859. diagnoseInitOverride(PrevInit, expr->getSourceRange());
  2860. }
  2861. ++StructuredIndex;
  2862. }
  2863. /// Determine whether we can perform aggregate initialization for the purposes
  2864. /// of overload resolution.
  2865. bool Sema::CanPerformAggregateInitializationForOverloadResolution(
  2866. const InitializedEntity &Entity, InitListExpr *From) {
  2867. QualType Type = Entity.getType();
  2868. InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
  2869. /*TreatUnavailableAsInvalid=*/false,
  2870. /*InOverloadResolution=*/true);
  2871. return !Check.HadError();
  2872. }
  2873. /// Check that the given Index expression is a valid array designator
  2874. /// value. This is essentially just a wrapper around
  2875. /// VerifyIntegerConstantExpression that also checks for negative values
  2876. /// and produces a reasonable diagnostic if there is a
  2877. /// failure. Returns the index expression, possibly with an implicit cast
  2878. /// added, on success. If everything went okay, Value will receive the
  2879. /// value of the constant expression.
  2880. static ExprResult
  2881. CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
  2882. SourceLocation Loc = Index->getBeginLoc();
  2883. // Make sure this is an integer constant expression.
  2884. ExprResult Result =
  2885. S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
  2886. if (Result.isInvalid())
  2887. return Result;
  2888. if (Value.isSigned() && Value.isNegative())
  2889. return S.Diag(Loc, diag::err_array_designator_negative)
  2890. << toString(Value, 10) << Index->getSourceRange();
  2891. Value.setIsUnsigned(true);
  2892. return Result;
  2893. }
  2894. ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
  2895. SourceLocation EqualOrColonLoc,
  2896. bool GNUSyntax,
  2897. ExprResult Init) {
  2898. typedef DesignatedInitExpr::Designator ASTDesignator;
  2899. bool Invalid = false;
  2900. SmallVector<ASTDesignator, 32> Designators;
  2901. SmallVector<Expr *, 32> InitExpressions;
  2902. // Build designators and check array designator expressions.
  2903. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
  2904. const Designator &D = Desig.getDesignator(Idx);
  2905. switch (D.getKind()) {
  2906. case Designator::FieldDesignator:
  2907. Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
  2908. D.getFieldLoc()));
  2909. break;
  2910. case Designator::ArrayDesignator: {
  2911. Expr *Index = static_cast<Expr *>(D.getArrayIndex());
  2912. llvm::APSInt IndexValue;
  2913. if (!Index->isTypeDependent() && !Index->isValueDependent())
  2914. Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
  2915. if (!Index)
  2916. Invalid = true;
  2917. else {
  2918. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2919. D.getLBracketLoc(),
  2920. D.getRBracketLoc()));
  2921. InitExpressions.push_back(Index);
  2922. }
  2923. break;
  2924. }
  2925. case Designator::ArrayRangeDesignator: {
  2926. Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
  2927. Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
  2928. llvm::APSInt StartValue;
  2929. llvm::APSInt EndValue;
  2930. bool StartDependent = StartIndex->isTypeDependent() ||
  2931. StartIndex->isValueDependent();
  2932. bool EndDependent = EndIndex->isTypeDependent() ||
  2933. EndIndex->isValueDependent();
  2934. if (!StartDependent)
  2935. StartIndex =
  2936. CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
  2937. if (!EndDependent)
  2938. EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
  2939. if (!StartIndex || !EndIndex)
  2940. Invalid = true;
  2941. else {
  2942. // Make sure we're comparing values with the same bit width.
  2943. if (StartDependent || EndDependent) {
  2944. // Nothing to compute.
  2945. } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
  2946. EndValue = EndValue.extend(StartValue.getBitWidth());
  2947. else if (StartValue.getBitWidth() < EndValue.getBitWidth())
  2948. StartValue = StartValue.extend(EndValue.getBitWidth());
  2949. if (!StartDependent && !EndDependent && EndValue < StartValue) {
  2950. Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
  2951. << toString(StartValue, 10) << toString(EndValue, 10)
  2952. << StartIndex->getSourceRange() << EndIndex->getSourceRange();
  2953. Invalid = true;
  2954. } else {
  2955. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2956. D.getLBracketLoc(),
  2957. D.getEllipsisLoc(),
  2958. D.getRBracketLoc()));
  2959. InitExpressions.push_back(StartIndex);
  2960. InitExpressions.push_back(EndIndex);
  2961. }
  2962. }
  2963. break;
  2964. }
  2965. }
  2966. }
  2967. if (Invalid || Init.isInvalid())
  2968. return ExprError();
  2969. // Clear out the expressions within the designation.
  2970. Desig.ClearExprs(*this);
  2971. return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
  2972. EqualOrColonLoc, GNUSyntax,
  2973. Init.getAs<Expr>());
  2974. }
  2975. //===----------------------------------------------------------------------===//
  2976. // Initialization entity
  2977. //===----------------------------------------------------------------------===//
  2978. InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
  2979. const InitializedEntity &Parent)
  2980. : Parent(&Parent), Index(Index)
  2981. {
  2982. if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
  2983. Kind = EK_ArrayElement;
  2984. Type = AT->getElementType();
  2985. } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
  2986. Kind = EK_VectorElement;
  2987. Type = VT->getElementType();
  2988. } else {
  2989. const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
  2990. assert(CT && "Unexpected type");
  2991. Kind = EK_ComplexElement;
  2992. Type = CT->getElementType();
  2993. }
  2994. }
  2995. InitializedEntity
  2996. InitializedEntity::InitializeBase(ASTContext &Context,
  2997. const CXXBaseSpecifier *Base,
  2998. bool IsInheritedVirtualBase,
  2999. const InitializedEntity *Parent) {
  3000. InitializedEntity Result;
  3001. Result.Kind = EK_Base;
  3002. Result.Parent = Parent;
  3003. Result.Base = {Base, IsInheritedVirtualBase};
  3004. Result.Type = Base->getType();
  3005. return Result;
  3006. }
  3007. DeclarationName InitializedEntity::getName() const {
  3008. switch (getKind()) {
  3009. case EK_Parameter:
  3010. case EK_Parameter_CF_Audited: {
  3011. ParmVarDecl *D = Parameter.getPointer();
  3012. return (D ? D->getDeclName() : DeclarationName());
  3013. }
  3014. case EK_Variable:
  3015. case EK_Member:
  3016. case EK_Binding:
  3017. case EK_TemplateParameter:
  3018. return Variable.VariableOrMember->getDeclName();
  3019. case EK_LambdaCapture:
  3020. return DeclarationName(Capture.VarID);
  3021. case EK_Result:
  3022. case EK_StmtExprResult:
  3023. case EK_Exception:
  3024. case EK_New:
  3025. case EK_Temporary:
  3026. case EK_Base:
  3027. case EK_Delegating:
  3028. case EK_ArrayElement:
  3029. case EK_VectorElement:
  3030. case EK_ComplexElement:
  3031. case EK_BlockElement:
  3032. case EK_LambdaToBlockConversionBlockElement:
  3033. case EK_CompoundLiteralInit:
  3034. case EK_RelatedResult:
  3035. return DeclarationName();
  3036. }
  3037. llvm_unreachable("Invalid EntityKind!");
  3038. }
  3039. ValueDecl *InitializedEntity::getDecl() const {
  3040. switch (getKind()) {
  3041. case EK_Variable:
  3042. case EK_Member:
  3043. case EK_Binding:
  3044. case EK_TemplateParameter:
  3045. return Variable.VariableOrMember;
  3046. case EK_Parameter:
  3047. case EK_Parameter_CF_Audited:
  3048. return Parameter.getPointer();
  3049. case EK_Result:
  3050. case EK_StmtExprResult:
  3051. case EK_Exception:
  3052. case EK_New:
  3053. case EK_Temporary:
  3054. case EK_Base:
  3055. case EK_Delegating:
  3056. case EK_ArrayElement:
  3057. case EK_VectorElement:
  3058. case EK_ComplexElement:
  3059. case EK_BlockElement:
  3060. case EK_LambdaToBlockConversionBlockElement:
  3061. case EK_LambdaCapture:
  3062. case EK_CompoundLiteralInit:
  3063. case EK_RelatedResult:
  3064. return nullptr;
  3065. }
  3066. llvm_unreachable("Invalid EntityKind!");
  3067. }
  3068. bool InitializedEntity::allowsNRVO() const {
  3069. switch (getKind()) {
  3070. case EK_Result:
  3071. case EK_Exception:
  3072. return LocAndNRVO.NRVO;
  3073. case EK_StmtExprResult:
  3074. case EK_Variable:
  3075. case EK_Parameter:
  3076. case EK_Parameter_CF_Audited:
  3077. case EK_TemplateParameter:
  3078. case EK_Member:
  3079. case EK_Binding:
  3080. case EK_New:
  3081. case EK_Temporary:
  3082. case EK_CompoundLiteralInit:
  3083. case EK_Base:
  3084. case EK_Delegating:
  3085. case EK_ArrayElement:
  3086. case EK_VectorElement:
  3087. case EK_ComplexElement:
  3088. case EK_BlockElement:
  3089. case EK_LambdaToBlockConversionBlockElement:
  3090. case EK_LambdaCapture:
  3091. case EK_RelatedResult:
  3092. break;
  3093. }
  3094. return false;
  3095. }
  3096. unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
  3097. assert(getParent() != this);
  3098. unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
  3099. for (unsigned I = 0; I != Depth; ++I)
  3100. OS << "`-";
  3101. switch (getKind()) {
  3102. case EK_Variable: OS << "Variable"; break;
  3103. case EK_Parameter: OS << "Parameter"; break;
  3104. case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
  3105. break;
  3106. case EK_TemplateParameter: OS << "TemplateParameter"; break;
  3107. case EK_Result: OS << "Result"; break;
  3108. case EK_StmtExprResult: OS << "StmtExprResult"; break;
  3109. case EK_Exception: OS << "Exception"; break;
  3110. case EK_Member: OS << "Member"; break;
  3111. case EK_Binding: OS << "Binding"; break;
  3112. case EK_New: OS << "New"; break;
  3113. case EK_Temporary: OS << "Temporary"; break;
  3114. case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
  3115. case EK_RelatedResult: OS << "RelatedResult"; break;
  3116. case EK_Base: OS << "Base"; break;
  3117. case EK_Delegating: OS << "Delegating"; break;
  3118. case EK_ArrayElement: OS << "ArrayElement " << Index; break;
  3119. case EK_VectorElement: OS << "VectorElement " << Index; break;
  3120. case EK_ComplexElement: OS << "ComplexElement " << Index; break;
  3121. case EK_BlockElement: OS << "Block"; break;
  3122. case EK_LambdaToBlockConversionBlockElement:
  3123. OS << "Block (lambda)";
  3124. break;
  3125. case EK_LambdaCapture:
  3126. OS << "LambdaCapture ";
  3127. OS << DeclarationName(Capture.VarID);
  3128. break;
  3129. }
  3130. if (auto *D = getDecl()) {
  3131. OS << " ";
  3132. D->printQualifiedName(OS);
  3133. }
  3134. OS << " '" << getType() << "'\n";
  3135. return Depth + 1;
  3136. }
  3137. LLVM_DUMP_METHOD void InitializedEntity::dump() const {
  3138. dumpImpl(llvm::errs());
  3139. }
  3140. //===----------------------------------------------------------------------===//
  3141. // Initialization sequence
  3142. //===----------------------------------------------------------------------===//
  3143. void InitializationSequence::Step::Destroy() {
  3144. switch (Kind) {
  3145. case SK_ResolveAddressOfOverloadedFunction:
  3146. case SK_CastDerivedToBasePRValue:
  3147. case SK_CastDerivedToBaseXValue:
  3148. case SK_CastDerivedToBaseLValue:
  3149. case SK_BindReference:
  3150. case SK_BindReferenceToTemporary:
  3151. case SK_FinalCopy:
  3152. case SK_ExtraneousCopyToTemporary:
  3153. case SK_UserConversion:
  3154. case SK_QualificationConversionPRValue:
  3155. case SK_QualificationConversionXValue:
  3156. case SK_QualificationConversionLValue:
  3157. case SK_FunctionReferenceConversion:
  3158. case SK_AtomicConversion:
  3159. case SK_ListInitialization:
  3160. case SK_UnwrapInitList:
  3161. case SK_RewrapInitList:
  3162. case SK_ConstructorInitialization:
  3163. case SK_ConstructorInitializationFromList:
  3164. case SK_ZeroInitialization:
  3165. case SK_CAssignment:
  3166. case SK_StringInit:
  3167. case SK_ObjCObjectConversion:
  3168. case SK_ArrayLoopIndex:
  3169. case SK_ArrayLoopInit:
  3170. case SK_ArrayInit:
  3171. case SK_GNUArrayInit:
  3172. case SK_ParenthesizedArrayInit:
  3173. case SK_PassByIndirectCopyRestore:
  3174. case SK_PassByIndirectRestore:
  3175. case SK_ProduceObjCObject:
  3176. case SK_StdInitializerList:
  3177. case SK_StdInitializerListConstructorCall:
  3178. case SK_OCLSamplerInit:
  3179. case SK_OCLZeroOpaqueType:
  3180. case SK_ParenthesizedListInit:
  3181. break;
  3182. case SK_ConversionSequence:
  3183. case SK_ConversionSequenceNoNarrowing:
  3184. delete ICS;
  3185. }
  3186. }
  3187. bool InitializationSequence::isDirectReferenceBinding() const {
  3188. // There can be some lvalue adjustments after the SK_BindReference step.
  3189. for (const Step &S : llvm::reverse(Steps)) {
  3190. if (S.Kind == SK_BindReference)
  3191. return true;
  3192. if (S.Kind == SK_BindReferenceToTemporary)
  3193. return false;
  3194. }
  3195. return false;
  3196. }
  3197. bool InitializationSequence::isAmbiguous() const {
  3198. if (!Failed())
  3199. return false;
  3200. switch (getFailureKind()) {
  3201. case FK_TooManyInitsForReference:
  3202. case FK_ParenthesizedListInitForReference:
  3203. case FK_ArrayNeedsInitList:
  3204. case FK_ArrayNeedsInitListOrStringLiteral:
  3205. case FK_ArrayNeedsInitListOrWideStringLiteral:
  3206. case FK_NarrowStringIntoWideCharArray:
  3207. case FK_WideStringIntoCharArray:
  3208. case FK_IncompatWideStringIntoWideChar:
  3209. case FK_PlainStringIntoUTF8Char:
  3210. case FK_UTF8StringIntoPlainChar:
  3211. case FK_AddressOfOverloadFailed: // FIXME: Could do better
  3212. case FK_NonConstLValueReferenceBindingToTemporary:
  3213. case FK_NonConstLValueReferenceBindingToBitfield:
  3214. case FK_NonConstLValueReferenceBindingToVectorElement:
  3215. case FK_NonConstLValueReferenceBindingToMatrixElement:
  3216. case FK_NonConstLValueReferenceBindingToUnrelated:
  3217. case FK_RValueReferenceBindingToLValue:
  3218. case FK_ReferenceAddrspaceMismatchTemporary:
  3219. case FK_ReferenceInitDropsQualifiers:
  3220. case FK_ReferenceInitFailed:
  3221. case FK_ConversionFailed:
  3222. case FK_ConversionFromPropertyFailed:
  3223. case FK_TooManyInitsForScalar:
  3224. case FK_ParenthesizedListInitForScalar:
  3225. case FK_ReferenceBindingToInitList:
  3226. case FK_InitListBadDestinationType:
  3227. case FK_DefaultInitOfConst:
  3228. case FK_Incomplete:
  3229. case FK_ArrayTypeMismatch:
  3230. case FK_NonConstantArrayInit:
  3231. case FK_ListInitializationFailed:
  3232. case FK_VariableLengthArrayHasInitializer:
  3233. case FK_PlaceholderType:
  3234. case FK_ExplicitConstructor:
  3235. case FK_AddressOfUnaddressableFunction:
  3236. case FK_ParenthesizedListInitFailed:
  3237. return false;
  3238. case FK_ReferenceInitOverloadFailed:
  3239. case FK_UserConversionOverloadFailed:
  3240. case FK_ConstructorOverloadFailed:
  3241. case FK_ListConstructorOverloadFailed:
  3242. return FailedOverloadResult == OR_Ambiguous;
  3243. }
  3244. llvm_unreachable("Invalid EntityKind!");
  3245. }
  3246. bool InitializationSequence::isConstructorInitialization() const {
  3247. return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
  3248. }
  3249. void
  3250. InitializationSequence
  3251. ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
  3252. DeclAccessPair Found,
  3253. bool HadMultipleCandidates) {
  3254. Step S;
  3255. S.Kind = SK_ResolveAddressOfOverloadedFunction;
  3256. S.Type = Function->getType();
  3257. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3258. S.Function.Function = Function;
  3259. S.Function.FoundDecl = Found;
  3260. Steps.push_back(S);
  3261. }
  3262. void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
  3263. ExprValueKind VK) {
  3264. Step S;
  3265. switch (VK) {
  3266. case VK_PRValue:
  3267. S.Kind = SK_CastDerivedToBasePRValue;
  3268. break;
  3269. case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
  3270. case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
  3271. }
  3272. S.Type = BaseType;
  3273. Steps.push_back(S);
  3274. }
  3275. void InitializationSequence::AddReferenceBindingStep(QualType T,
  3276. bool BindingTemporary) {
  3277. Step S;
  3278. S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
  3279. S.Type = T;
  3280. Steps.push_back(S);
  3281. }
  3282. void InitializationSequence::AddFinalCopy(QualType T) {
  3283. Step S;
  3284. S.Kind = SK_FinalCopy;
  3285. S.Type = T;
  3286. Steps.push_back(S);
  3287. }
  3288. void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
  3289. Step S;
  3290. S.Kind = SK_ExtraneousCopyToTemporary;
  3291. S.Type = T;
  3292. Steps.push_back(S);
  3293. }
  3294. void
  3295. InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
  3296. DeclAccessPair FoundDecl,
  3297. QualType T,
  3298. bool HadMultipleCandidates) {
  3299. Step S;
  3300. S.Kind = SK_UserConversion;
  3301. S.Type = T;
  3302. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3303. S.Function.Function = Function;
  3304. S.Function.FoundDecl = FoundDecl;
  3305. Steps.push_back(S);
  3306. }
  3307. void InitializationSequence::AddQualificationConversionStep(QualType Ty,
  3308. ExprValueKind VK) {
  3309. Step S;
  3310. S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
  3311. switch (VK) {
  3312. case VK_PRValue:
  3313. S.Kind = SK_QualificationConversionPRValue;
  3314. break;
  3315. case VK_XValue:
  3316. S.Kind = SK_QualificationConversionXValue;
  3317. break;
  3318. case VK_LValue:
  3319. S.Kind = SK_QualificationConversionLValue;
  3320. break;
  3321. }
  3322. S.Type = Ty;
  3323. Steps.push_back(S);
  3324. }
  3325. void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
  3326. Step S;
  3327. S.Kind = SK_FunctionReferenceConversion;
  3328. S.Type = Ty;
  3329. Steps.push_back(S);
  3330. }
  3331. void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
  3332. Step S;
  3333. S.Kind = SK_AtomicConversion;
  3334. S.Type = Ty;
  3335. Steps.push_back(S);
  3336. }
  3337. void InitializationSequence::AddConversionSequenceStep(
  3338. const ImplicitConversionSequence &ICS, QualType T,
  3339. bool TopLevelOfInitList) {
  3340. Step S;
  3341. S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
  3342. : SK_ConversionSequence;
  3343. S.Type = T;
  3344. S.ICS = new ImplicitConversionSequence(ICS);
  3345. Steps.push_back(S);
  3346. }
  3347. void InitializationSequence::AddListInitializationStep(QualType T) {
  3348. Step S;
  3349. S.Kind = SK_ListInitialization;
  3350. S.Type = T;
  3351. Steps.push_back(S);
  3352. }
  3353. void InitializationSequence::AddConstructorInitializationStep(
  3354. DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
  3355. bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
  3356. Step S;
  3357. S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
  3358. : SK_ConstructorInitializationFromList
  3359. : SK_ConstructorInitialization;
  3360. S.Type = T;
  3361. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3362. S.Function.Function = Constructor;
  3363. S.Function.FoundDecl = FoundDecl;
  3364. Steps.push_back(S);
  3365. }
  3366. void InitializationSequence::AddZeroInitializationStep(QualType T) {
  3367. Step S;
  3368. S.Kind = SK_ZeroInitialization;
  3369. S.Type = T;
  3370. Steps.push_back(S);
  3371. }
  3372. void InitializationSequence::AddCAssignmentStep(QualType T) {
  3373. Step S;
  3374. S.Kind = SK_CAssignment;
  3375. S.Type = T;
  3376. Steps.push_back(S);
  3377. }
  3378. void InitializationSequence::AddStringInitStep(QualType T) {
  3379. Step S;
  3380. S.Kind = SK_StringInit;
  3381. S.Type = T;
  3382. Steps.push_back(S);
  3383. }
  3384. void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
  3385. Step S;
  3386. S.Kind = SK_ObjCObjectConversion;
  3387. S.Type = T;
  3388. Steps.push_back(S);
  3389. }
  3390. void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
  3391. Step S;
  3392. S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
  3393. S.Type = T;
  3394. Steps.push_back(S);
  3395. }
  3396. void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
  3397. Step S;
  3398. S.Kind = SK_ArrayLoopIndex;
  3399. S.Type = EltT;
  3400. Steps.insert(Steps.begin(), S);
  3401. S.Kind = SK_ArrayLoopInit;
  3402. S.Type = T;
  3403. Steps.push_back(S);
  3404. }
  3405. void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
  3406. Step S;
  3407. S.Kind = SK_ParenthesizedArrayInit;
  3408. S.Type = T;
  3409. Steps.push_back(S);
  3410. }
  3411. void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
  3412. bool shouldCopy) {
  3413. Step s;
  3414. s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
  3415. : SK_PassByIndirectRestore);
  3416. s.Type = type;
  3417. Steps.push_back(s);
  3418. }
  3419. void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
  3420. Step S;
  3421. S.Kind = SK_ProduceObjCObject;
  3422. S.Type = T;
  3423. Steps.push_back(S);
  3424. }
  3425. void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
  3426. Step S;
  3427. S.Kind = SK_StdInitializerList;
  3428. S.Type = T;
  3429. Steps.push_back(S);
  3430. }
  3431. void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
  3432. Step S;
  3433. S.Kind = SK_OCLSamplerInit;
  3434. S.Type = T;
  3435. Steps.push_back(S);
  3436. }
  3437. void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
  3438. Step S;
  3439. S.Kind = SK_OCLZeroOpaqueType;
  3440. S.Type = T;
  3441. Steps.push_back(S);
  3442. }
  3443. void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
  3444. Step S;
  3445. S.Kind = SK_ParenthesizedListInit;
  3446. S.Type = T;
  3447. Steps.push_back(S);
  3448. }
  3449. void InitializationSequence::RewrapReferenceInitList(QualType T,
  3450. InitListExpr *Syntactic) {
  3451. assert(Syntactic->getNumInits() == 1 &&
  3452. "Can only rewrap trivial init lists.");
  3453. Step S;
  3454. S.Kind = SK_UnwrapInitList;
  3455. S.Type = Syntactic->getInit(0)->getType();
  3456. Steps.insert(Steps.begin(), S);
  3457. S.Kind = SK_RewrapInitList;
  3458. S.Type = T;
  3459. S.WrappingSyntacticList = Syntactic;
  3460. Steps.push_back(S);
  3461. }
  3462. void InitializationSequence::SetOverloadFailure(FailureKind Failure,
  3463. OverloadingResult Result) {
  3464. setSequenceKind(FailedSequence);
  3465. this->Failure = Failure;
  3466. this->FailedOverloadResult = Result;
  3467. }
  3468. //===----------------------------------------------------------------------===//
  3469. // Attempt initialization
  3470. //===----------------------------------------------------------------------===//
  3471. /// Tries to add a zero initializer. Returns true if that worked.
  3472. static bool
  3473. maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
  3474. const InitializedEntity &Entity) {
  3475. if (Entity.getKind() != InitializedEntity::EK_Variable)
  3476. return false;
  3477. VarDecl *VD = cast<VarDecl>(Entity.getDecl());
  3478. if (VD->getInit() || VD->getEndLoc().isMacroID())
  3479. return false;
  3480. QualType VariableTy = VD->getType().getCanonicalType();
  3481. SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
  3482. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  3483. if (!Init.empty()) {
  3484. Sequence.AddZeroInitializationStep(Entity.getType());
  3485. Sequence.SetZeroInitializationFixit(Init, Loc);
  3486. return true;
  3487. }
  3488. return false;
  3489. }
  3490. static void MaybeProduceObjCObject(Sema &S,
  3491. InitializationSequence &Sequence,
  3492. const InitializedEntity &Entity) {
  3493. if (!S.getLangOpts().ObjCAutoRefCount) return;
  3494. /// When initializing a parameter, produce the value if it's marked
  3495. /// __attribute__((ns_consumed)).
  3496. if (Entity.isParameterKind()) {
  3497. if (!Entity.isParameterConsumed())
  3498. return;
  3499. assert(Entity.getType()->isObjCRetainableType() &&
  3500. "consuming an object of unretainable type?");
  3501. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3502. /// When initializing a return value, if the return type is a
  3503. /// retainable type, then returns need to immediately retain the
  3504. /// object. If an autorelease is required, it will be done at the
  3505. /// last instant.
  3506. } else if (Entity.getKind() == InitializedEntity::EK_Result ||
  3507. Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
  3508. if (!Entity.getType()->isObjCRetainableType())
  3509. return;
  3510. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3511. }
  3512. }
  3513. static void TryListInitialization(Sema &S,
  3514. const InitializedEntity &Entity,
  3515. const InitializationKind &Kind,
  3516. InitListExpr *InitList,
  3517. InitializationSequence &Sequence,
  3518. bool TreatUnavailableAsInvalid);
  3519. /// When initializing from init list via constructor, handle
  3520. /// initialization of an object of type std::initializer_list<T>.
  3521. ///
  3522. /// \return true if we have handled initialization of an object of type
  3523. /// std::initializer_list<T>, false otherwise.
  3524. static bool TryInitializerListConstruction(Sema &S,
  3525. InitListExpr *List,
  3526. QualType DestType,
  3527. InitializationSequence &Sequence,
  3528. bool TreatUnavailableAsInvalid) {
  3529. QualType E;
  3530. if (!S.isStdInitializerList(DestType, &E))
  3531. return false;
  3532. if (!S.isCompleteType(List->getExprLoc(), E)) {
  3533. Sequence.setIncompleteTypeFailure(E);
  3534. return true;
  3535. }
  3536. // Try initializing a temporary array from the init list.
  3537. QualType ArrayType = S.Context.getConstantArrayType(
  3538. E.withConst(),
  3539. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  3540. List->getNumInits()),
  3541. nullptr, clang::ArrayType::Normal, 0);
  3542. InitializedEntity HiddenArray =
  3543. InitializedEntity::InitializeTemporary(ArrayType);
  3544. InitializationKind Kind = InitializationKind::CreateDirectList(
  3545. List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
  3546. TryListInitialization(S, HiddenArray, Kind, List, Sequence,
  3547. TreatUnavailableAsInvalid);
  3548. if (Sequence)
  3549. Sequence.AddStdInitializerListConstructionStep(DestType);
  3550. return true;
  3551. }
  3552. /// Determine if the constructor has the signature of a copy or move
  3553. /// constructor for the type T of the class in which it was found. That is,
  3554. /// determine if its first parameter is of type T or reference to (possibly
  3555. /// cv-qualified) T.
  3556. static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
  3557. const ConstructorInfo &Info) {
  3558. if (Info.Constructor->getNumParams() == 0)
  3559. return false;
  3560. QualType ParmT =
  3561. Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
  3562. QualType ClassT =
  3563. Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
  3564. return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
  3565. }
  3566. static OverloadingResult
  3567. ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
  3568. MultiExprArg Args,
  3569. OverloadCandidateSet &CandidateSet,
  3570. QualType DestType,
  3571. DeclContext::lookup_result Ctors,
  3572. OverloadCandidateSet::iterator &Best,
  3573. bool CopyInitializing, bool AllowExplicit,
  3574. bool OnlyListConstructors, bool IsListInit,
  3575. bool SecondStepOfCopyInit = false) {
  3576. CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
  3577. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  3578. for (NamedDecl *D : Ctors) {
  3579. auto Info = getConstructorInfo(D);
  3580. if (!Info.Constructor || Info.Constructor->isInvalidDecl())
  3581. continue;
  3582. if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
  3583. continue;
  3584. // C++11 [over.best.ics]p4:
  3585. // ... and the constructor or user-defined conversion function is a
  3586. // candidate by
  3587. // - 13.3.1.3, when the argument is the temporary in the second step
  3588. // of a class copy-initialization, or
  3589. // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
  3590. // - the second phase of 13.3.1.7 when the initializer list has exactly
  3591. // one element that is itself an initializer list, and the target is
  3592. // the first parameter of a constructor of class X, and the conversion
  3593. // is to X or reference to (possibly cv-qualified X),
  3594. // user-defined conversion sequences are not considered.
  3595. bool SuppressUserConversions =
  3596. SecondStepOfCopyInit ||
  3597. (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  3598. hasCopyOrMoveCtorParam(S.Context, Info));
  3599. if (Info.ConstructorTmpl)
  3600. S.AddTemplateOverloadCandidate(
  3601. Info.ConstructorTmpl, Info.FoundDecl,
  3602. /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
  3603. /*PartialOverloading=*/false, AllowExplicit);
  3604. else {
  3605. // C++ [over.match.copy]p1:
  3606. // - When initializing a temporary to be bound to the first parameter
  3607. // of a constructor [for type T] that takes a reference to possibly
  3608. // cv-qualified T as its first argument, called with a single
  3609. // argument in the context of direct-initialization, explicit
  3610. // conversion functions are also considered.
  3611. // FIXME: What if a constructor template instantiates to such a signature?
  3612. bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
  3613. Args.size() == 1 &&
  3614. hasCopyOrMoveCtorParam(S.Context, Info);
  3615. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
  3616. CandidateSet, SuppressUserConversions,
  3617. /*PartialOverloading=*/false, AllowExplicit,
  3618. AllowExplicitConv);
  3619. }
  3620. }
  3621. // FIXME: Work around a bug in C++17 guaranteed copy elision.
  3622. //
  3623. // When initializing an object of class type T by constructor
  3624. // ([over.match.ctor]) or by list-initialization ([over.match.list])
  3625. // from a single expression of class type U, conversion functions of
  3626. // U that convert to the non-reference type cv T are candidates.
  3627. // Explicit conversion functions are only candidates during
  3628. // direct-initialization.
  3629. //
  3630. // Note: SecondStepOfCopyInit is only ever true in this case when
  3631. // evaluating whether to produce a C++98 compatibility warning.
  3632. if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
  3633. !SecondStepOfCopyInit) {
  3634. Expr *Initializer = Args[0];
  3635. auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
  3636. if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
  3637. const auto &Conversions = SourceRD->getVisibleConversionFunctions();
  3638. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3639. NamedDecl *D = *I;
  3640. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3641. D = D->getUnderlyingDecl();
  3642. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3643. CXXConversionDecl *Conv;
  3644. if (ConvTemplate)
  3645. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3646. else
  3647. Conv = cast<CXXConversionDecl>(D);
  3648. if (ConvTemplate)
  3649. S.AddTemplateConversionCandidate(
  3650. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  3651. CandidateSet, AllowExplicit, AllowExplicit,
  3652. /*AllowResultConversion*/ false);
  3653. else
  3654. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  3655. DestType, CandidateSet, AllowExplicit,
  3656. AllowExplicit,
  3657. /*AllowResultConversion*/ false);
  3658. }
  3659. }
  3660. }
  3661. // Perform overload resolution and return the result.
  3662. return CandidateSet.BestViableFunction(S, DeclLoc, Best);
  3663. }
  3664. /// Attempt initialization by constructor (C++ [dcl.init]), which
  3665. /// enumerates the constructors of the initialized entity and performs overload
  3666. /// resolution to select the best.
  3667. /// \param DestType The destination class type.
  3668. /// \param DestArrayType The destination type, which is either DestType or
  3669. /// a (possibly multidimensional) array of DestType.
  3670. /// \param IsListInit Is this list-initialization?
  3671. /// \param IsInitListCopy Is this non-list-initialization resulting from a
  3672. /// list-initialization from {x} where x is the same
  3673. /// type as the entity?
  3674. static void TryConstructorInitialization(Sema &S,
  3675. const InitializedEntity &Entity,
  3676. const InitializationKind &Kind,
  3677. MultiExprArg Args, QualType DestType,
  3678. QualType DestArrayType,
  3679. InitializationSequence &Sequence,
  3680. bool IsListInit = false,
  3681. bool IsInitListCopy = false) {
  3682. assert(((!IsListInit && !IsInitListCopy) ||
  3683. (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
  3684. "IsListInit/IsInitListCopy must come with a single initializer list "
  3685. "argument.");
  3686. InitListExpr *ILE =
  3687. (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
  3688. MultiExprArg UnwrappedArgs =
  3689. ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
  3690. // The type we're constructing needs to be complete.
  3691. if (!S.isCompleteType(Kind.getLocation(), DestType)) {
  3692. Sequence.setIncompleteTypeFailure(DestType);
  3693. return;
  3694. }
  3695. // C++17 [dcl.init]p17:
  3696. // - If the initializer expression is a prvalue and the cv-unqualified
  3697. // version of the source type is the same class as the class of the
  3698. // destination, the initializer expression is used to initialize the
  3699. // destination object.
  3700. // Per DR (no number yet), this does not apply when initializing a base
  3701. // class or delegating to another constructor from a mem-initializer.
  3702. // ObjC++: Lambda captured by the block in the lambda to block conversion
  3703. // should avoid copy elision.
  3704. if (S.getLangOpts().CPlusPlus17 &&
  3705. Entity.getKind() != InitializedEntity::EK_Base &&
  3706. Entity.getKind() != InitializedEntity::EK_Delegating &&
  3707. Entity.getKind() !=
  3708. InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
  3709. UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
  3710. S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
  3711. // Convert qualifications if necessary.
  3712. Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
  3713. if (ILE)
  3714. Sequence.RewrapReferenceInitList(DestType, ILE);
  3715. return;
  3716. }
  3717. const RecordType *DestRecordType = DestType->getAs<RecordType>();
  3718. assert(DestRecordType && "Constructor initialization requires record type");
  3719. CXXRecordDecl *DestRecordDecl
  3720. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  3721. // Build the candidate set directly in the initialization sequence
  3722. // structure, so that it will persist if we fail.
  3723. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3724. // Determine whether we are allowed to call explicit constructors or
  3725. // explicit conversion operators.
  3726. bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
  3727. bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
  3728. // - Otherwise, if T is a class type, constructors are considered. The
  3729. // applicable constructors are enumerated, and the best one is chosen
  3730. // through overload resolution.
  3731. DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
  3732. OverloadingResult Result = OR_No_Viable_Function;
  3733. OverloadCandidateSet::iterator Best;
  3734. bool AsInitializerList = false;
  3735. // C++11 [over.match.list]p1, per DR1467:
  3736. // When objects of non-aggregate type T are list-initialized, such that
  3737. // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
  3738. // according to the rules in this section, overload resolution selects
  3739. // the constructor in two phases:
  3740. //
  3741. // - Initially, the candidate functions are the initializer-list
  3742. // constructors of the class T and the argument list consists of the
  3743. // initializer list as a single argument.
  3744. if (IsListInit) {
  3745. AsInitializerList = true;
  3746. // If the initializer list has no elements and T has a default constructor,
  3747. // the first phase is omitted.
  3748. if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
  3749. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
  3750. CandidateSet, DestType, Ctors, Best,
  3751. CopyInitialization, AllowExplicit,
  3752. /*OnlyListConstructors=*/true,
  3753. IsListInit);
  3754. }
  3755. // C++11 [over.match.list]p1:
  3756. // - If no viable initializer-list constructor is found, overload resolution
  3757. // is performed again, where the candidate functions are all the
  3758. // constructors of the class T and the argument list consists of the
  3759. // elements of the initializer list.
  3760. if (Result == OR_No_Viable_Function) {
  3761. AsInitializerList = false;
  3762. Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
  3763. CandidateSet, DestType, Ctors, Best,
  3764. CopyInitialization, AllowExplicit,
  3765. /*OnlyListConstructors=*/false,
  3766. IsListInit);
  3767. }
  3768. if (Result) {
  3769. Sequence.SetOverloadFailure(
  3770. IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
  3771. : InitializationSequence::FK_ConstructorOverloadFailed,
  3772. Result);
  3773. if (Result != OR_Deleted)
  3774. return;
  3775. }
  3776. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3777. // In C++17, ResolveConstructorOverload can select a conversion function
  3778. // instead of a constructor.
  3779. if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3780. // Add the user-defined conversion step that calls the conversion function.
  3781. QualType ConvType = CD->getConversionType();
  3782. assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
  3783. "should not have selected this conversion function");
  3784. Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
  3785. HadMultipleCandidates);
  3786. if (!S.Context.hasSameType(ConvType, DestType))
  3787. Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
  3788. if (IsListInit)
  3789. Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
  3790. return;
  3791. }
  3792. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  3793. if (Result != OR_Deleted) {
  3794. // C++11 [dcl.init]p6:
  3795. // If a program calls for the default initialization of an object
  3796. // of a const-qualified type T, T shall be a class type with a
  3797. // user-provided default constructor.
  3798. // C++ core issue 253 proposal:
  3799. // If the implicit default constructor initializes all subobjects, no
  3800. // initializer should be required.
  3801. // The 253 proposal is for example needed to process libstdc++ headers
  3802. // in 5.x.
  3803. if (Kind.getKind() == InitializationKind::IK_Default &&
  3804. Entity.getType().isConstQualified()) {
  3805. if (!CtorDecl->getParent()->allowConstDefaultInit()) {
  3806. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  3807. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3808. return;
  3809. }
  3810. }
  3811. // C++11 [over.match.list]p1:
  3812. // In copy-list-initialization, if an explicit constructor is chosen, the
  3813. // initializer is ill-formed.
  3814. if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
  3815. Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
  3816. return;
  3817. }
  3818. }
  3819. // [class.copy.elision]p3:
  3820. // In some copy-initialization contexts, a two-stage overload resolution
  3821. // is performed.
  3822. // If the first overload resolution selects a deleted function, we also
  3823. // need the initialization sequence to decide whether to perform the second
  3824. // overload resolution.
  3825. // For deleted functions in other contexts, there is no need to get the
  3826. // initialization sequence.
  3827. if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
  3828. return;
  3829. // Add the constructor initialization step. Any cv-qualification conversion is
  3830. // subsumed by the initialization.
  3831. Sequence.AddConstructorInitializationStep(
  3832. Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
  3833. IsListInit | IsInitListCopy, AsInitializerList);
  3834. }
  3835. static bool
  3836. ResolveOverloadedFunctionForReferenceBinding(Sema &S,
  3837. Expr *Initializer,
  3838. QualType &SourceType,
  3839. QualType &UnqualifiedSourceType,
  3840. QualType UnqualifiedTargetType,
  3841. InitializationSequence &Sequence) {
  3842. if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
  3843. S.Context.OverloadTy) {
  3844. DeclAccessPair Found;
  3845. bool HadMultipleCandidates = false;
  3846. if (FunctionDecl *Fn
  3847. = S.ResolveAddressOfOverloadedFunction(Initializer,
  3848. UnqualifiedTargetType,
  3849. false, Found,
  3850. &HadMultipleCandidates)) {
  3851. Sequence.AddAddressOverloadResolutionStep(Fn, Found,
  3852. HadMultipleCandidates);
  3853. SourceType = Fn->getType();
  3854. UnqualifiedSourceType = SourceType.getUnqualifiedType();
  3855. } else if (!UnqualifiedTargetType->isRecordType()) {
  3856. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3857. return true;
  3858. }
  3859. }
  3860. return false;
  3861. }
  3862. static void TryReferenceInitializationCore(Sema &S,
  3863. const InitializedEntity &Entity,
  3864. const InitializationKind &Kind,
  3865. Expr *Initializer,
  3866. QualType cv1T1, QualType T1,
  3867. Qualifiers T1Quals,
  3868. QualType cv2T2, QualType T2,
  3869. Qualifiers T2Quals,
  3870. InitializationSequence &Sequence);
  3871. static void TryValueInitialization(Sema &S,
  3872. const InitializedEntity &Entity,
  3873. const InitializationKind &Kind,
  3874. InitializationSequence &Sequence,
  3875. InitListExpr *InitList = nullptr);
  3876. /// Attempt list initialization of a reference.
  3877. static void TryReferenceListInitialization(Sema &S,
  3878. const InitializedEntity &Entity,
  3879. const InitializationKind &Kind,
  3880. InitListExpr *InitList,
  3881. InitializationSequence &Sequence,
  3882. bool TreatUnavailableAsInvalid) {
  3883. // First, catch C++03 where this isn't possible.
  3884. if (!S.getLangOpts().CPlusPlus11) {
  3885. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3886. return;
  3887. }
  3888. // Can't reference initialize a compound literal.
  3889. if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
  3890. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3891. return;
  3892. }
  3893. QualType DestType = Entity.getType();
  3894. QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
  3895. Qualifiers T1Quals;
  3896. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  3897. // Reference initialization via an initializer list works thus:
  3898. // If the initializer list consists of a single element that is
  3899. // reference-related to the referenced type, bind directly to that element
  3900. // (possibly creating temporaries).
  3901. // Otherwise, initialize a temporary with the initializer list and
  3902. // bind to that.
  3903. if (InitList->getNumInits() == 1) {
  3904. Expr *Initializer = InitList->getInit(0);
  3905. QualType cv2T2 = S.getCompletedType(Initializer);
  3906. Qualifiers T2Quals;
  3907. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  3908. // If this fails, creating a temporary wouldn't work either.
  3909. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  3910. T1, Sequence))
  3911. return;
  3912. SourceLocation DeclLoc = Initializer->getBeginLoc();
  3913. Sema::ReferenceCompareResult RefRelationship
  3914. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
  3915. if (RefRelationship >= Sema::Ref_Related) {
  3916. // Try to bind the reference here.
  3917. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  3918. T1Quals, cv2T2, T2, T2Quals, Sequence);
  3919. if (Sequence)
  3920. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3921. return;
  3922. }
  3923. // Update the initializer if we've resolved an overloaded function.
  3924. if (Sequence.step_begin() != Sequence.step_end())
  3925. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3926. }
  3927. // Perform address space compatibility check.
  3928. QualType cv1T1IgnoreAS = cv1T1;
  3929. if (T1Quals.hasAddressSpace()) {
  3930. Qualifiers T2Quals;
  3931. (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
  3932. if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
  3933. Sequence.SetFailed(
  3934. InitializationSequence::FK_ReferenceInitDropsQualifiers);
  3935. return;
  3936. }
  3937. // Ignore address space of reference type at this point and perform address
  3938. // space conversion after the reference binding step.
  3939. cv1T1IgnoreAS =
  3940. S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
  3941. }
  3942. // Not reference-related. Create a temporary and bind to that.
  3943. InitializedEntity TempEntity =
  3944. InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
  3945. TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
  3946. TreatUnavailableAsInvalid);
  3947. if (Sequence) {
  3948. if (DestType->isRValueReferenceType() ||
  3949. (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
  3950. Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
  3951. /*BindingTemporary=*/true);
  3952. if (T1Quals.hasAddressSpace())
  3953. Sequence.AddQualificationConversionStep(
  3954. cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
  3955. } else
  3956. Sequence.SetFailed(
  3957. InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3958. }
  3959. }
  3960. /// Attempt list initialization (C++0x [dcl.init.list])
  3961. static void TryListInitialization(Sema &S,
  3962. const InitializedEntity &Entity,
  3963. const InitializationKind &Kind,
  3964. InitListExpr *InitList,
  3965. InitializationSequence &Sequence,
  3966. bool TreatUnavailableAsInvalid) {
  3967. QualType DestType = Entity.getType();
  3968. // C++ doesn't allow scalar initialization with more than one argument.
  3969. // But C99 complex numbers are scalars and it makes sense there.
  3970. if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
  3971. !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
  3972. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
  3973. return;
  3974. }
  3975. if (DestType->isReferenceType()) {
  3976. TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
  3977. TreatUnavailableAsInvalid);
  3978. return;
  3979. }
  3980. if (DestType->isRecordType() &&
  3981. !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
  3982. Sequence.setIncompleteTypeFailure(DestType);
  3983. return;
  3984. }
  3985. // C++11 [dcl.init.list]p3, per DR1467:
  3986. // - If T is a class type and the initializer list has a single element of
  3987. // type cv U, where U is T or a class derived from T, the object is
  3988. // initialized from that element (by copy-initialization for
  3989. // copy-list-initialization, or by direct-initialization for
  3990. // direct-list-initialization).
  3991. // - Otherwise, if T is a character array and the initializer list has a
  3992. // single element that is an appropriately-typed string literal
  3993. // (8.5.2 [dcl.init.string]), initialization is performed as described
  3994. // in that section.
  3995. // - Otherwise, if T is an aggregate, [...] (continue below).
  3996. if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
  3997. if (DestType->isRecordType()) {
  3998. QualType InitType = InitList->getInit(0)->getType();
  3999. if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
  4000. S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
  4001. Expr *InitListAsExpr = InitList;
  4002. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  4003. DestType, Sequence,
  4004. /*InitListSyntax*/false,
  4005. /*IsInitListCopy*/true);
  4006. return;
  4007. }
  4008. }
  4009. if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
  4010. Expr *SubInit[1] = {InitList->getInit(0)};
  4011. if (!isa<VariableArrayType>(DestAT) &&
  4012. IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
  4013. InitializationKind SubKind =
  4014. Kind.getKind() == InitializationKind::IK_DirectList
  4015. ? InitializationKind::CreateDirect(Kind.getLocation(),
  4016. InitList->getLBraceLoc(),
  4017. InitList->getRBraceLoc())
  4018. : Kind;
  4019. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  4020. /*TopLevelOfInitList*/ true,
  4021. TreatUnavailableAsInvalid);
  4022. // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
  4023. // the element is not an appropriately-typed string literal, in which
  4024. // case we should proceed as in C++11 (below).
  4025. if (Sequence) {
  4026. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  4027. return;
  4028. }
  4029. }
  4030. }
  4031. }
  4032. // C++11 [dcl.init.list]p3:
  4033. // - If T is an aggregate, aggregate initialization is performed.
  4034. if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
  4035. (S.getLangOpts().CPlusPlus11 &&
  4036. S.isStdInitializerList(DestType, nullptr))) {
  4037. if (S.getLangOpts().CPlusPlus11) {
  4038. // - Otherwise, if the initializer list has no elements and T is a
  4039. // class type with a default constructor, the object is
  4040. // value-initialized.
  4041. if (InitList->getNumInits() == 0) {
  4042. CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
  4043. if (S.LookupDefaultConstructor(RD)) {
  4044. TryValueInitialization(S, Entity, Kind, Sequence, InitList);
  4045. return;
  4046. }
  4047. }
  4048. // - Otherwise, if T is a specialization of std::initializer_list<E>,
  4049. // an initializer_list object constructed [...]
  4050. if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
  4051. TreatUnavailableAsInvalid))
  4052. return;
  4053. // - Otherwise, if T is a class type, constructors are considered.
  4054. Expr *InitListAsExpr = InitList;
  4055. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  4056. DestType, Sequence, /*InitListSyntax*/true);
  4057. } else
  4058. Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
  4059. return;
  4060. }
  4061. if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
  4062. InitList->getNumInits() == 1) {
  4063. Expr *E = InitList->getInit(0);
  4064. // - Otherwise, if T is an enumeration with a fixed underlying type,
  4065. // the initializer-list has a single element v, and the initialization
  4066. // is direct-list-initialization, the object is initialized with the
  4067. // value T(v); if a narrowing conversion is required to convert v to
  4068. // the underlying type of T, the program is ill-formed.
  4069. auto *ET = DestType->getAs<EnumType>();
  4070. if (S.getLangOpts().CPlusPlus17 &&
  4071. Kind.getKind() == InitializationKind::IK_DirectList &&
  4072. ET && ET->getDecl()->isFixed() &&
  4073. !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
  4074. (E->getType()->isIntegralOrUnscopedEnumerationType() ||
  4075. E->getType()->isFloatingType())) {
  4076. // There are two ways that T(v) can work when T is an enumeration type.
  4077. // If there is either an implicit conversion sequence from v to T or
  4078. // a conversion function that can convert from v to T, then we use that.
  4079. // Otherwise, if v is of integral, unscoped enumeration, or floating-point
  4080. // type, it is converted to the enumeration type via its underlying type.
  4081. // There is no overlap possible between these two cases (except when the
  4082. // source value is already of the destination type), and the first
  4083. // case is handled by the general case for single-element lists below.
  4084. ImplicitConversionSequence ICS;
  4085. ICS.setStandard();
  4086. ICS.Standard.setAsIdentityConversion();
  4087. if (!E->isPRValue())
  4088. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  4089. // If E is of a floating-point type, then the conversion is ill-formed
  4090. // due to narrowing, but go through the motions in order to produce the
  4091. // right diagnostic.
  4092. ICS.Standard.Second = E->getType()->isFloatingType()
  4093. ? ICK_Floating_Integral
  4094. : ICK_Integral_Conversion;
  4095. ICS.Standard.setFromType(E->getType());
  4096. ICS.Standard.setToType(0, E->getType());
  4097. ICS.Standard.setToType(1, DestType);
  4098. ICS.Standard.setToType(2, DestType);
  4099. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
  4100. /*TopLevelOfInitList*/true);
  4101. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  4102. return;
  4103. }
  4104. // - Otherwise, if the initializer list has a single element of type E
  4105. // [...references are handled above...], the object or reference is
  4106. // initialized from that element (by copy-initialization for
  4107. // copy-list-initialization, or by direct-initialization for
  4108. // direct-list-initialization); if a narrowing conversion is required
  4109. // to convert the element to T, the program is ill-formed.
  4110. //
  4111. // Per core-24034, this is direct-initialization if we were performing
  4112. // direct-list-initialization and copy-initialization otherwise.
  4113. // We can't use InitListChecker for this, because it always performs
  4114. // copy-initialization. This only matters if we might use an 'explicit'
  4115. // conversion operator, or for the special case conversion of nullptr_t to
  4116. // bool, so we only need to handle those cases.
  4117. //
  4118. // FIXME: Why not do this in all cases?
  4119. Expr *Init = InitList->getInit(0);
  4120. if (Init->getType()->isRecordType() ||
  4121. (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
  4122. InitializationKind SubKind =
  4123. Kind.getKind() == InitializationKind::IK_DirectList
  4124. ? InitializationKind::CreateDirect(Kind.getLocation(),
  4125. InitList->getLBraceLoc(),
  4126. InitList->getRBraceLoc())
  4127. : Kind;
  4128. Expr *SubInit[1] = { Init };
  4129. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  4130. /*TopLevelOfInitList*/true,
  4131. TreatUnavailableAsInvalid);
  4132. if (Sequence)
  4133. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  4134. return;
  4135. }
  4136. }
  4137. InitListChecker CheckInitList(S, Entity, InitList,
  4138. DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
  4139. if (CheckInitList.HadError()) {
  4140. Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
  4141. return;
  4142. }
  4143. // Add the list initialization step with the built init list.
  4144. Sequence.AddListInitializationStep(DestType);
  4145. }
  4146. /// Try a reference initialization that involves calling a conversion
  4147. /// function.
  4148. static OverloadingResult TryRefInitWithConversionFunction(
  4149. Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
  4150. Expr *Initializer, bool AllowRValues, bool IsLValueRef,
  4151. InitializationSequence &Sequence) {
  4152. QualType DestType = Entity.getType();
  4153. QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
  4154. QualType T1 = cv1T1.getUnqualifiedType();
  4155. QualType cv2T2 = Initializer->getType();
  4156. QualType T2 = cv2T2.getUnqualifiedType();
  4157. assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
  4158. "Must have incompatible references when binding via conversion");
  4159. // Build the candidate set directly in the initialization sequence
  4160. // structure, so that it will persist if we fail.
  4161. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  4162. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4163. // Determine whether we are allowed to call explicit conversion operators.
  4164. // Note that none of [over.match.copy], [over.match.conv], nor
  4165. // [over.match.ref] permit an explicit constructor to be chosen when
  4166. // initializing a reference, not even for direct-initialization.
  4167. bool AllowExplicitCtors = false;
  4168. bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
  4169. const RecordType *T1RecordType = nullptr;
  4170. if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
  4171. S.isCompleteType(Kind.getLocation(), T1)) {
  4172. // The type we're converting to is a class type. Enumerate its constructors
  4173. // to see if there is a suitable conversion.
  4174. CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
  4175. for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
  4176. auto Info = getConstructorInfo(D);
  4177. if (!Info.Constructor)
  4178. continue;
  4179. if (!Info.Constructor->isInvalidDecl() &&
  4180. Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
  4181. if (Info.ConstructorTmpl)
  4182. S.AddTemplateOverloadCandidate(
  4183. Info.ConstructorTmpl, Info.FoundDecl,
  4184. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  4185. /*SuppressUserConversions=*/true,
  4186. /*PartialOverloading*/ false, AllowExplicitCtors);
  4187. else
  4188. S.AddOverloadCandidate(
  4189. Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
  4190. /*SuppressUserConversions=*/true,
  4191. /*PartialOverloading*/ false, AllowExplicitCtors);
  4192. }
  4193. }
  4194. }
  4195. if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
  4196. return OR_No_Viable_Function;
  4197. const RecordType *T2RecordType = nullptr;
  4198. if ((T2RecordType = T2->getAs<RecordType>()) &&
  4199. S.isCompleteType(Kind.getLocation(), T2)) {
  4200. // The type we're converting from is a class type, enumerate its conversion
  4201. // functions.
  4202. CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
  4203. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  4204. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4205. NamedDecl *D = *I;
  4206. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4207. if (isa<UsingShadowDecl>(D))
  4208. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4209. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4210. CXXConversionDecl *Conv;
  4211. if (ConvTemplate)
  4212. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4213. else
  4214. Conv = cast<CXXConversionDecl>(D);
  4215. // If the conversion function doesn't return a reference type,
  4216. // it can't be considered for this conversion unless we're allowed to
  4217. // consider rvalues.
  4218. // FIXME: Do we need to make sure that we only consider conversion
  4219. // candidates with reference-compatible results? That might be needed to
  4220. // break recursion.
  4221. if ((AllowRValues ||
  4222. Conv->getConversionType()->isLValueReferenceType())) {
  4223. if (ConvTemplate)
  4224. S.AddTemplateConversionCandidate(
  4225. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  4226. CandidateSet,
  4227. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  4228. else
  4229. S.AddConversionCandidate(
  4230. Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
  4231. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  4232. }
  4233. }
  4234. }
  4235. if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
  4236. return OR_No_Viable_Function;
  4237. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4238. // Perform overload resolution. If it fails, return the failed result.
  4239. OverloadCandidateSet::iterator Best;
  4240. if (OverloadingResult Result
  4241. = CandidateSet.BestViableFunction(S, DeclLoc, Best))
  4242. return Result;
  4243. FunctionDecl *Function = Best->Function;
  4244. // This is the overload that will be used for this initialization step if we
  4245. // use this initialization. Mark it as referenced.
  4246. Function->setReferenced();
  4247. // Compute the returned type and value kind of the conversion.
  4248. QualType cv3T3;
  4249. if (isa<CXXConversionDecl>(Function))
  4250. cv3T3 = Function->getReturnType();
  4251. else
  4252. cv3T3 = T1;
  4253. ExprValueKind VK = VK_PRValue;
  4254. if (cv3T3->isLValueReferenceType())
  4255. VK = VK_LValue;
  4256. else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
  4257. VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
  4258. cv3T3 = cv3T3.getNonLValueExprType(S.Context);
  4259. // Add the user-defined conversion step.
  4260. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4261. Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
  4262. HadMultipleCandidates);
  4263. // Determine whether we'll need to perform derived-to-base adjustments or
  4264. // other conversions.
  4265. Sema::ReferenceConversions RefConv;
  4266. Sema::ReferenceCompareResult NewRefRelationship =
  4267. S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
  4268. // Add the final conversion sequence, if necessary.
  4269. if (NewRefRelationship == Sema::Ref_Incompatible) {
  4270. assert(!isa<CXXConstructorDecl>(Function) &&
  4271. "should not have conversion after constructor");
  4272. ImplicitConversionSequence ICS;
  4273. ICS.setStandard();
  4274. ICS.Standard = Best->FinalConversion;
  4275. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
  4276. // Every implicit conversion results in a prvalue, except for a glvalue
  4277. // derived-to-base conversion, which we handle below.
  4278. cv3T3 = ICS.Standard.getToType(2);
  4279. VK = VK_PRValue;
  4280. }
  4281. // If the converted initializer is a prvalue, its type T4 is adjusted to
  4282. // type "cv1 T4" and the temporary materialization conversion is applied.
  4283. //
  4284. // We adjust the cv-qualifications to match the reference regardless of
  4285. // whether we have a prvalue so that the AST records the change. In this
  4286. // case, T4 is "cv3 T3".
  4287. QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
  4288. if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
  4289. Sequence.AddQualificationConversionStep(cv1T4, VK);
  4290. Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
  4291. VK = IsLValueRef ? VK_LValue : VK_XValue;
  4292. if (RefConv & Sema::ReferenceConversions::DerivedToBase)
  4293. Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
  4294. else if (RefConv & Sema::ReferenceConversions::ObjC)
  4295. Sequence.AddObjCObjectConversionStep(cv1T1);
  4296. else if (RefConv & Sema::ReferenceConversions::Function)
  4297. Sequence.AddFunctionReferenceConversionStep(cv1T1);
  4298. else if (RefConv & Sema::ReferenceConversions::Qualification) {
  4299. if (!S.Context.hasSameType(cv1T4, cv1T1))
  4300. Sequence.AddQualificationConversionStep(cv1T1, VK);
  4301. }
  4302. return OR_Success;
  4303. }
  4304. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  4305. const InitializedEntity &Entity,
  4306. Expr *CurInitExpr);
  4307. /// Attempt reference initialization (C++0x [dcl.init.ref])
  4308. static void TryReferenceInitialization(Sema &S,
  4309. const InitializedEntity &Entity,
  4310. const InitializationKind &Kind,
  4311. Expr *Initializer,
  4312. InitializationSequence &Sequence) {
  4313. QualType DestType = Entity.getType();
  4314. QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
  4315. Qualifiers T1Quals;
  4316. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  4317. QualType cv2T2 = S.getCompletedType(Initializer);
  4318. Qualifiers T2Quals;
  4319. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  4320. // If the initializer is the address of an overloaded function, try
  4321. // to resolve the overloaded function. If all goes well, T2 is the
  4322. // type of the resulting function.
  4323. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  4324. T1, Sequence))
  4325. return;
  4326. // Delegate everything else to a subfunction.
  4327. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  4328. T1Quals, cv2T2, T2, T2Quals, Sequence);
  4329. }
  4330. /// Determine whether an expression is a non-referenceable glvalue (one to
  4331. /// which a reference can never bind). Attempting to bind a reference to
  4332. /// such a glvalue will always create a temporary.
  4333. static bool isNonReferenceableGLValue(Expr *E) {
  4334. return E->refersToBitField() || E->refersToVectorElement() ||
  4335. E->refersToMatrixElement();
  4336. }
  4337. /// Reference initialization without resolving overloaded functions.
  4338. ///
  4339. /// We also can get here in C if we call a builtin which is declared as
  4340. /// a function with a parameter of reference type (such as __builtin_va_end()).
  4341. static void TryReferenceInitializationCore(Sema &S,
  4342. const InitializedEntity &Entity,
  4343. const InitializationKind &Kind,
  4344. Expr *Initializer,
  4345. QualType cv1T1, QualType T1,
  4346. Qualifiers T1Quals,
  4347. QualType cv2T2, QualType T2,
  4348. Qualifiers T2Quals,
  4349. InitializationSequence &Sequence) {
  4350. QualType DestType = Entity.getType();
  4351. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4352. // Compute some basic properties of the types and the initializer.
  4353. bool isLValueRef = DestType->isLValueReferenceType();
  4354. bool isRValueRef = !isLValueRef;
  4355. Expr::Classification InitCategory = Initializer->Classify(S.Context);
  4356. Sema::ReferenceConversions RefConv;
  4357. Sema::ReferenceCompareResult RefRelationship =
  4358. S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
  4359. // C++0x [dcl.init.ref]p5:
  4360. // A reference to type "cv1 T1" is initialized by an expression of type
  4361. // "cv2 T2" as follows:
  4362. //
  4363. // - If the reference is an lvalue reference and the initializer
  4364. // expression
  4365. // Note the analogous bullet points for rvalue refs to functions. Because
  4366. // there are no function rvalues in C++, rvalue refs to functions are treated
  4367. // like lvalue refs.
  4368. OverloadingResult ConvOvlResult = OR_Success;
  4369. bool T1Function = T1->isFunctionType();
  4370. if (isLValueRef || T1Function) {
  4371. if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
  4372. (RefRelationship == Sema::Ref_Compatible ||
  4373. (Kind.isCStyleOrFunctionalCast() &&
  4374. RefRelationship == Sema::Ref_Related))) {
  4375. // - is an lvalue (but is not a bit-field), and "cv1 T1" is
  4376. // reference-compatible with "cv2 T2," or
  4377. if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
  4378. Sema::ReferenceConversions::ObjC)) {
  4379. // If we're converting the pointee, add any qualifiers first;
  4380. // these qualifiers must all be top-level, so just convert to "cv1 T2".
  4381. if (RefConv & (Sema::ReferenceConversions::Qualification))
  4382. Sequence.AddQualificationConversionStep(
  4383. S.Context.getQualifiedType(T2, T1Quals),
  4384. Initializer->getValueKind());
  4385. if (RefConv & Sema::ReferenceConversions::DerivedToBase)
  4386. Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
  4387. else
  4388. Sequence.AddObjCObjectConversionStep(cv1T1);
  4389. } else if (RefConv & Sema::ReferenceConversions::Qualification) {
  4390. // Perform a (possibly multi-level) qualification conversion.
  4391. Sequence.AddQualificationConversionStep(cv1T1,
  4392. Initializer->getValueKind());
  4393. } else if (RefConv & Sema::ReferenceConversions::Function) {
  4394. Sequence.AddFunctionReferenceConversionStep(cv1T1);
  4395. }
  4396. // We only create a temporary here when binding a reference to a
  4397. // bit-field or vector element. Those cases are't supposed to be
  4398. // handled by this bullet, but the outcome is the same either way.
  4399. Sequence.AddReferenceBindingStep(cv1T1, false);
  4400. return;
  4401. }
  4402. // - has a class type (i.e., T2 is a class type), where T1 is not
  4403. // reference-related to T2, and can be implicitly converted to an
  4404. // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
  4405. // with "cv3 T3" (this conversion is selected by enumerating the
  4406. // applicable conversion functions (13.3.1.6) and choosing the best
  4407. // one through overload resolution (13.3)),
  4408. // If we have an rvalue ref to function type here, the rhs must be
  4409. // an rvalue. DR1287 removed the "implicitly" here.
  4410. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
  4411. (isLValueRef || InitCategory.isRValue())) {
  4412. if (S.getLangOpts().CPlusPlus) {
  4413. // Try conversion functions only for C++.
  4414. ConvOvlResult = TryRefInitWithConversionFunction(
  4415. S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
  4416. /*IsLValueRef*/ isLValueRef, Sequence);
  4417. if (ConvOvlResult == OR_Success)
  4418. return;
  4419. if (ConvOvlResult != OR_No_Viable_Function)
  4420. Sequence.SetOverloadFailure(
  4421. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4422. ConvOvlResult);
  4423. } else {
  4424. ConvOvlResult = OR_No_Viable_Function;
  4425. }
  4426. }
  4427. }
  4428. // - Otherwise, the reference shall be an lvalue reference to a
  4429. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4430. // shall be an rvalue reference.
  4431. // For address spaces, we interpret this to mean that an addr space
  4432. // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
  4433. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
  4434. T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
  4435. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4436. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4437. else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4438. Sequence.SetOverloadFailure(
  4439. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4440. ConvOvlResult);
  4441. else if (!InitCategory.isLValue())
  4442. Sequence.SetFailed(
  4443. T1Quals.isAddressSpaceSupersetOf(T2Quals)
  4444. ? InitializationSequence::
  4445. FK_NonConstLValueReferenceBindingToTemporary
  4446. : InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4447. else {
  4448. InitializationSequence::FailureKind FK;
  4449. switch (RefRelationship) {
  4450. case Sema::Ref_Compatible:
  4451. if (Initializer->refersToBitField())
  4452. FK = InitializationSequence::
  4453. FK_NonConstLValueReferenceBindingToBitfield;
  4454. else if (Initializer->refersToVectorElement())
  4455. FK = InitializationSequence::
  4456. FK_NonConstLValueReferenceBindingToVectorElement;
  4457. else if (Initializer->refersToMatrixElement())
  4458. FK = InitializationSequence::
  4459. FK_NonConstLValueReferenceBindingToMatrixElement;
  4460. else
  4461. llvm_unreachable("unexpected kind of compatible initializer");
  4462. break;
  4463. case Sema::Ref_Related:
  4464. FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
  4465. break;
  4466. case Sema::Ref_Incompatible:
  4467. FK = InitializationSequence::
  4468. FK_NonConstLValueReferenceBindingToUnrelated;
  4469. break;
  4470. }
  4471. Sequence.SetFailed(FK);
  4472. }
  4473. return;
  4474. }
  4475. // - If the initializer expression
  4476. // - is an
  4477. // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
  4478. // [1z] rvalue (but not a bit-field) or
  4479. // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
  4480. //
  4481. // Note: functions are handled above and below rather than here...
  4482. if (!T1Function &&
  4483. (RefRelationship == Sema::Ref_Compatible ||
  4484. (Kind.isCStyleOrFunctionalCast() &&
  4485. RefRelationship == Sema::Ref_Related)) &&
  4486. ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
  4487. (InitCategory.isPRValue() &&
  4488. (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
  4489. T2->isArrayType())))) {
  4490. ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
  4491. if (InitCategory.isPRValue() && T2->isRecordType()) {
  4492. // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
  4493. // compiler the freedom to perform a copy here or bind to the
  4494. // object, while C++0x requires that we bind directly to the
  4495. // object. Hence, we always bind to the object without making an
  4496. // extra copy. However, in C++03 requires that we check for the
  4497. // presence of a suitable copy constructor:
  4498. //
  4499. // The constructor that would be used to make the copy shall
  4500. // be callable whether or not the copy is actually done.
  4501. if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
  4502. Sequence.AddExtraneousCopyToTemporary(cv2T2);
  4503. else if (S.getLangOpts().CPlusPlus11)
  4504. CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
  4505. }
  4506. // C++1z [dcl.init.ref]/5.2.1.2:
  4507. // If the converted initializer is a prvalue, its type T4 is adjusted
  4508. // to type "cv1 T4" and the temporary materialization conversion is
  4509. // applied.
  4510. // Postpone address space conversions to after the temporary materialization
  4511. // conversion to allow creating temporaries in the alloca address space.
  4512. auto T1QualsIgnoreAS = T1Quals;
  4513. auto T2QualsIgnoreAS = T2Quals;
  4514. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4515. T1QualsIgnoreAS.removeAddressSpace();
  4516. T2QualsIgnoreAS.removeAddressSpace();
  4517. }
  4518. QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
  4519. if (T1QualsIgnoreAS != T2QualsIgnoreAS)
  4520. Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
  4521. Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
  4522. ValueKind = isLValueRef ? VK_LValue : VK_XValue;
  4523. // Add addr space conversion if required.
  4524. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4525. auto T4Quals = cv1T4.getQualifiers();
  4526. T4Quals.addAddressSpace(T1Quals.getAddressSpace());
  4527. QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
  4528. Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
  4529. cv1T4 = cv1T4WithAS;
  4530. }
  4531. // In any case, the reference is bound to the resulting glvalue (or to
  4532. // an appropriate base class subobject).
  4533. if (RefConv & Sema::ReferenceConversions::DerivedToBase)
  4534. Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
  4535. else if (RefConv & Sema::ReferenceConversions::ObjC)
  4536. Sequence.AddObjCObjectConversionStep(cv1T1);
  4537. else if (RefConv & Sema::ReferenceConversions::Qualification) {
  4538. if (!S.Context.hasSameType(cv1T4, cv1T1))
  4539. Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
  4540. }
  4541. return;
  4542. }
  4543. // - has a class type (i.e., T2 is a class type), where T1 is not
  4544. // reference-related to T2, and can be implicitly converted to an
  4545. // xvalue, class prvalue, or function lvalue of type "cv3 T3",
  4546. // where "cv1 T1" is reference-compatible with "cv3 T3",
  4547. //
  4548. // DR1287 removes the "implicitly" here.
  4549. if (T2->isRecordType()) {
  4550. if (RefRelationship == Sema::Ref_Incompatible) {
  4551. ConvOvlResult = TryRefInitWithConversionFunction(
  4552. S, Entity, Kind, Initializer, /*AllowRValues*/ true,
  4553. /*IsLValueRef*/ isLValueRef, Sequence);
  4554. if (ConvOvlResult)
  4555. Sequence.SetOverloadFailure(
  4556. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4557. ConvOvlResult);
  4558. return;
  4559. }
  4560. if (RefRelationship == Sema::Ref_Compatible &&
  4561. isRValueRef && InitCategory.isLValue()) {
  4562. Sequence.SetFailed(
  4563. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4564. return;
  4565. }
  4566. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4567. return;
  4568. }
  4569. // - Otherwise, a temporary of type "cv1 T1" is created and initialized
  4570. // from the initializer expression using the rules for a non-reference
  4571. // copy-initialization (8.5). The reference is then bound to the
  4572. // temporary. [...]
  4573. // Ignore address space of reference type at this point and perform address
  4574. // space conversion after the reference binding step.
  4575. QualType cv1T1IgnoreAS =
  4576. T1Quals.hasAddressSpace()
  4577. ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
  4578. : cv1T1;
  4579. InitializedEntity TempEntity =
  4580. InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
  4581. // FIXME: Why do we use an implicit conversion here rather than trying
  4582. // copy-initialization?
  4583. ImplicitConversionSequence ICS
  4584. = S.TryImplicitConversion(Initializer, TempEntity.getType(),
  4585. /*SuppressUserConversions=*/false,
  4586. Sema::AllowedExplicit::None,
  4587. /*FIXME:InOverloadResolution=*/false,
  4588. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  4589. /*AllowObjCWritebackConversion=*/false);
  4590. if (ICS.isBad()) {
  4591. // FIXME: Use the conversion function set stored in ICS to turn
  4592. // this into an overloading ambiguity diagnostic. However, we need
  4593. // to keep that set as an OverloadCandidateSet rather than as some
  4594. // other kind of set.
  4595. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4596. Sequence.SetOverloadFailure(
  4597. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4598. ConvOvlResult);
  4599. else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4600. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4601. else
  4602. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
  4603. return;
  4604. } else {
  4605. Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
  4606. }
  4607. // [...] If T1 is reference-related to T2, cv1 must be the
  4608. // same cv-qualification as, or greater cv-qualification
  4609. // than, cv2; otherwise, the program is ill-formed.
  4610. unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
  4611. unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
  4612. if (RefRelationship == Sema::Ref_Related &&
  4613. ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
  4614. !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
  4615. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4616. return;
  4617. }
  4618. // [...] If T1 is reference-related to T2 and the reference is an rvalue
  4619. // reference, the initializer expression shall not be an lvalue.
  4620. if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
  4621. InitCategory.isLValue()) {
  4622. Sequence.SetFailed(
  4623. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4624. return;
  4625. }
  4626. Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
  4627. if (T1Quals.hasAddressSpace()) {
  4628. if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
  4629. LangAS::Default)) {
  4630. Sequence.SetFailed(
  4631. InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
  4632. return;
  4633. }
  4634. Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
  4635. : VK_XValue);
  4636. }
  4637. }
  4638. /// Attempt character array initialization from a string literal
  4639. /// (C++ [dcl.init.string], C99 6.7.8).
  4640. static void TryStringLiteralInitialization(Sema &S,
  4641. const InitializedEntity &Entity,
  4642. const InitializationKind &Kind,
  4643. Expr *Initializer,
  4644. InitializationSequence &Sequence) {
  4645. Sequence.AddStringInitStep(Entity.getType());
  4646. }
  4647. /// Attempt value initialization (C++ [dcl.init]p7).
  4648. static void TryValueInitialization(Sema &S,
  4649. const InitializedEntity &Entity,
  4650. const InitializationKind &Kind,
  4651. InitializationSequence &Sequence,
  4652. InitListExpr *InitList) {
  4653. assert((!InitList || InitList->getNumInits() == 0) &&
  4654. "Shouldn't use value-init for non-empty init lists");
  4655. // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
  4656. //
  4657. // To value-initialize an object of type T means:
  4658. QualType T = Entity.getType();
  4659. // -- if T is an array type, then each element is value-initialized;
  4660. T = S.Context.getBaseElementType(T);
  4661. if (const RecordType *RT = T->getAs<RecordType>()) {
  4662. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  4663. bool NeedZeroInitialization = true;
  4664. // C++98:
  4665. // -- if T is a class type (clause 9) with a user-declared constructor
  4666. // (12.1), then the default constructor for T is called (and the
  4667. // initialization is ill-formed if T has no accessible default
  4668. // constructor);
  4669. // C++11:
  4670. // -- if T is a class type (clause 9) with either no default constructor
  4671. // (12.1 [class.ctor]) or a default constructor that is user-provided
  4672. // or deleted, then the object is default-initialized;
  4673. //
  4674. // Note that the C++11 rule is the same as the C++98 rule if there are no
  4675. // defaulted or deleted constructors, so we just use it unconditionally.
  4676. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
  4677. if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
  4678. NeedZeroInitialization = false;
  4679. // -- if T is a (possibly cv-qualified) non-union class type without a
  4680. // user-provided or deleted default constructor, then the object is
  4681. // zero-initialized and, if T has a non-trivial default constructor,
  4682. // default-initialized;
  4683. // The 'non-union' here was removed by DR1502. The 'non-trivial default
  4684. // constructor' part was removed by DR1507.
  4685. if (NeedZeroInitialization)
  4686. Sequence.AddZeroInitializationStep(Entity.getType());
  4687. // C++03:
  4688. // -- if T is a non-union class type without a user-declared constructor,
  4689. // then every non-static data member and base class component of T is
  4690. // value-initialized;
  4691. // [...] A program that calls for [...] value-initialization of an
  4692. // entity of reference type is ill-formed.
  4693. //
  4694. // C++11 doesn't need this handling, because value-initialization does not
  4695. // occur recursively there, and the implicit default constructor is
  4696. // defined as deleted in the problematic cases.
  4697. if (!S.getLangOpts().CPlusPlus11 &&
  4698. ClassDecl->hasUninitializedReferenceMember()) {
  4699. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
  4700. return;
  4701. }
  4702. // If this is list-value-initialization, pass the empty init list on when
  4703. // building the constructor call. This affects the semantics of a few
  4704. // things (such as whether an explicit default constructor can be called).
  4705. Expr *InitListAsExpr = InitList;
  4706. MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
  4707. bool InitListSyntax = InitList;
  4708. // FIXME: Instead of creating a CXXConstructExpr of array type here,
  4709. // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
  4710. return TryConstructorInitialization(
  4711. S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
  4712. }
  4713. }
  4714. Sequence.AddZeroInitializationStep(Entity.getType());
  4715. }
  4716. /// Attempt default initialization (C++ [dcl.init]p6).
  4717. static void TryDefaultInitialization(Sema &S,
  4718. const InitializedEntity &Entity,
  4719. const InitializationKind &Kind,
  4720. InitializationSequence &Sequence) {
  4721. assert(Kind.getKind() == InitializationKind::IK_Default);
  4722. // C++ [dcl.init]p6:
  4723. // To default-initialize an object of type T means:
  4724. // - if T is an array type, each element is default-initialized;
  4725. QualType DestType = S.Context.getBaseElementType(Entity.getType());
  4726. // - if T is a (possibly cv-qualified) class type (Clause 9), the default
  4727. // constructor for T is called (and the initialization is ill-formed if
  4728. // T has no accessible default constructor);
  4729. if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
  4730. TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
  4731. Entity.getType(), Sequence);
  4732. return;
  4733. }
  4734. // - otherwise, no initialization is performed.
  4735. // If a program calls for the default initialization of an object of
  4736. // a const-qualified type T, T shall be a class type with a user-provided
  4737. // default constructor.
  4738. if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
  4739. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  4740. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  4741. return;
  4742. }
  4743. // If the destination type has a lifetime property, zero-initialize it.
  4744. if (DestType.getQualifiers().hasObjCLifetime()) {
  4745. Sequence.AddZeroInitializationStep(Entity.getType());
  4746. return;
  4747. }
  4748. }
  4749. static void TryOrBuildParenListInitialization(
  4750. Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
  4751. ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
  4752. ExprResult *Result = nullptr) {
  4753. unsigned ArgIndexToProcess = 0;
  4754. SmallVector<Expr *, 4> InitExprs;
  4755. QualType ResultType;
  4756. Expr *ArrayFiller = nullptr;
  4757. FieldDecl *InitializedFieldInUnion = nullptr;
  4758. // Process entities (i.e. array members, base classes, or class fields) by
  4759. // adding an initialization expression to InitExprs for each entity to
  4760. // initialize.
  4761. auto ProcessEntities = [&](auto Range) -> bool {
  4762. bool IsUnionType = Entity.getType()->isUnionType();
  4763. for (InitializedEntity SubEntity : Range) {
  4764. // Unions should only have one initializer expression.
  4765. // If there are more initializers than it will be caught when we check
  4766. // whether Index equals Args.size().
  4767. if (ArgIndexToProcess == 1 && IsUnionType)
  4768. return true;
  4769. bool IsMember = SubEntity.getKind() == InitializedEntity::EK_Member;
  4770. // Unnamed bitfields should not be initialized at all, either with an arg
  4771. // or by default.
  4772. if (IsMember && cast<FieldDecl>(SubEntity.getDecl())->isUnnamedBitfield())
  4773. continue;
  4774. if (ArgIndexToProcess < Args.size()) {
  4775. // There are still expressions in Args that haven't been processed.
  4776. // Let's match them to the current entity to initialize.
  4777. Expr *E = Args[ArgIndexToProcess++];
  4778. // Incomplete array types indicate flexible array members. Do not allow
  4779. // paren list initializations of structs with these members, as GCC
  4780. // doesn't either.
  4781. if (IsMember) {
  4782. auto *FD = cast<FieldDecl>(SubEntity.getDecl());
  4783. if (FD->getType()->isIncompleteArrayType()) {
  4784. if (!VerifyOnly) {
  4785. S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
  4786. << SourceRange(E->getBeginLoc(), E->getEndLoc());
  4787. S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
  4788. }
  4789. Sequence.SetFailed(
  4790. InitializationSequence::FK_ParenthesizedListInitFailed);
  4791. return false;
  4792. }
  4793. }
  4794. InitializationKind SubKind = InitializationKind::CreateForInit(
  4795. E->getExprLoc(), /*isDirectInit=*/false, E);
  4796. InitializationSequence SubSeq(S, SubEntity, SubKind, E);
  4797. if (SubSeq.Failed()) {
  4798. if (!VerifyOnly)
  4799. SubSeq.Diagnose(S, SubEntity, SubKind, E);
  4800. else
  4801. Sequence.SetFailed(
  4802. InitializationSequence::FK_ParenthesizedListInitFailed);
  4803. return false;
  4804. }
  4805. if (!VerifyOnly) {
  4806. ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, E);
  4807. InitExprs.push_back(ER.get());
  4808. if (IsMember && IsUnionType)
  4809. InitializedFieldInUnion = cast<FieldDecl>(SubEntity.getDecl());
  4810. }
  4811. } else {
  4812. // We've processed all of the args, but there are still entities that
  4813. // have to be initialized.
  4814. if (IsMember) {
  4815. // C++ [dcl.init]p17.6.2.2
  4816. // The remaining elements are initialized with their default member
  4817. // initializers, if any
  4818. auto *FD = cast<FieldDecl>(SubEntity.getDecl());
  4819. if (Expr *ICE = FD->getInClassInitializer(); ICE && !VerifyOnly) {
  4820. ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD);
  4821. if (DIE.isInvalid())
  4822. return false;
  4823. S.checkInitializerLifetime(SubEntity, DIE.get());
  4824. InitExprs.push_back(DIE.get());
  4825. continue;
  4826. };
  4827. }
  4828. // Remaining class elements without default member initializers and
  4829. // array elements are value initialized:
  4830. //
  4831. // C++ [dcl.init]p17.6.2.2
  4832. // The remaining elements...otherwise are value initialzed
  4833. //
  4834. // C++ [dcl.init]p17.5
  4835. // if the destination type is an array, the object is initialized as
  4836. // . follows. Let x1, . . . , xk be the elements of the expression-list
  4837. // ...Let n denote the array size...the ith array element is...value-
  4838. // initialized for each k < i <= n.
  4839. InitializationKind SubKind = InitializationKind::CreateValue(
  4840. Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
  4841. InitializationSequence SubSeq(S, SubEntity, SubKind, std::nullopt);
  4842. if (SubSeq.Failed()) {
  4843. if (!VerifyOnly)
  4844. SubSeq.Diagnose(S, SubEntity, SubKind, std::nullopt);
  4845. return false;
  4846. }
  4847. if (!VerifyOnly) {
  4848. ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, std::nullopt);
  4849. if (SubEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  4850. ArrayFiller = ER.get();
  4851. return true;
  4852. }
  4853. InitExprs.push_back(ER.get());
  4854. }
  4855. }
  4856. }
  4857. return true;
  4858. };
  4859. if (const ArrayType *AT =
  4860. S.getASTContext().getAsArrayType(Entity.getType())) {
  4861. SmallVector<InitializedEntity, 4> ElementEntities;
  4862. uint64_t ArrayLength;
  4863. // C++ [dcl.init]p17.5
  4864. // if the destination type is an array, the object is initialized as
  4865. // follows. Let x1, . . . , xk be the elements of the expression-list. If
  4866. // the destination type is an array of unknown bound, it is define as
  4867. // having k elements.
  4868. if (const ConstantArrayType *CAT =
  4869. S.getASTContext().getAsConstantArrayType(Entity.getType()))
  4870. ArrayLength = CAT->getSize().getZExtValue();
  4871. else
  4872. ArrayLength = Args.size();
  4873. if (ArrayLength >= Args.size()) {
  4874. for (uint64_t I = 0; I < ArrayLength; ++I)
  4875. ElementEntities.push_back(
  4876. InitializedEntity::InitializeElement(S.getASTContext(), I, Entity));
  4877. if (!ProcessEntities(ElementEntities))
  4878. return;
  4879. ResultType = S.Context.getConstantArrayType(
  4880. AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
  4881. nullptr, ArrayType::Normal, 0);
  4882. }
  4883. } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
  4884. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  4885. auto BaseRange = map_range(RD->bases(), [&S](auto &base) {
  4886. return InitializedEntity::InitializeBase(S.getASTContext(), &base, false);
  4887. });
  4888. auto FieldRange = map_range(RD->fields(), [](auto *field) {
  4889. return InitializedEntity::InitializeMember(field);
  4890. });
  4891. if (!ProcessEntities(BaseRange))
  4892. return;
  4893. if (!ProcessEntities(FieldRange))
  4894. return;
  4895. ResultType = Entity.getType();
  4896. }
  4897. // Not all of the args have been processed, so there must've been more args
  4898. // then were required to initialize the element.
  4899. if (ArgIndexToProcess < Args.size()) {
  4900. Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
  4901. if (!VerifyOnly) {
  4902. QualType T = Entity.getType();
  4903. int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
  4904. SourceRange ExcessInitSR(Args[ArgIndexToProcess]->getBeginLoc(),
  4905. Args.back()->getEndLoc());
  4906. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  4907. << InitKind << ExcessInitSR;
  4908. }
  4909. return;
  4910. }
  4911. if (VerifyOnly) {
  4912. Sequence.setSequenceKind(InitializationSequence::NormalSequence);
  4913. Sequence.AddParenthesizedListInitStep(Entity.getType());
  4914. } else if (Result) {
  4915. SourceRange SR = Kind.getParenOrBraceRange();
  4916. auto *CPLIE = CXXParenListInitExpr::Create(
  4917. S.getASTContext(), InitExprs, ResultType, Args.size(),
  4918. Kind.getLocation(), SR.getBegin(), SR.getEnd());
  4919. if (ArrayFiller)
  4920. CPLIE->setArrayFiller(ArrayFiller);
  4921. if (InitializedFieldInUnion)
  4922. CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
  4923. *Result = CPLIE;
  4924. S.Diag(Kind.getLocation(),
  4925. diag::warn_cxx17_compat_aggregate_init_paren_list)
  4926. << Kind.getLocation() << SR << ResultType;
  4927. }
  4928. return;
  4929. }
  4930. /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
  4931. /// which enumerates all conversion functions and performs overload resolution
  4932. /// to select the best.
  4933. static void TryUserDefinedConversion(Sema &S,
  4934. QualType DestType,
  4935. const InitializationKind &Kind,
  4936. Expr *Initializer,
  4937. InitializationSequence &Sequence,
  4938. bool TopLevelOfInitList) {
  4939. assert(!DestType->isReferenceType() && "References are handled elsewhere");
  4940. QualType SourceType = Initializer->getType();
  4941. assert((DestType->isRecordType() || SourceType->isRecordType()) &&
  4942. "Must have a class type to perform a user-defined conversion");
  4943. // Build the candidate set directly in the initialization sequence
  4944. // structure, so that it will persist if we fail.
  4945. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  4946. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4947. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  4948. // Determine whether we are allowed to call explicit constructors or
  4949. // explicit conversion operators.
  4950. bool AllowExplicit = Kind.AllowExplicit();
  4951. if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
  4952. // The type we're converting to is a class type. Enumerate its constructors
  4953. // to see if there is a suitable conversion.
  4954. CXXRecordDecl *DestRecordDecl
  4955. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  4956. // Try to complete the type we're converting to.
  4957. if (S.isCompleteType(Kind.getLocation(), DestType)) {
  4958. for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
  4959. auto Info = getConstructorInfo(D);
  4960. if (!Info.Constructor)
  4961. continue;
  4962. if (!Info.Constructor->isInvalidDecl() &&
  4963. Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
  4964. if (Info.ConstructorTmpl)
  4965. S.AddTemplateOverloadCandidate(
  4966. Info.ConstructorTmpl, Info.FoundDecl,
  4967. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  4968. /*SuppressUserConversions=*/true,
  4969. /*PartialOverloading*/ false, AllowExplicit);
  4970. else
  4971. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  4972. Initializer, CandidateSet,
  4973. /*SuppressUserConversions=*/true,
  4974. /*PartialOverloading*/ false, AllowExplicit);
  4975. }
  4976. }
  4977. }
  4978. }
  4979. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4980. if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
  4981. // The type we're converting from is a class type, enumerate its conversion
  4982. // functions.
  4983. // We can only enumerate the conversion functions for a complete type; if
  4984. // the type isn't complete, simply skip this step.
  4985. if (S.isCompleteType(DeclLoc, SourceType)) {
  4986. CXXRecordDecl *SourceRecordDecl
  4987. = cast<CXXRecordDecl>(SourceRecordType->getDecl());
  4988. const auto &Conversions =
  4989. SourceRecordDecl->getVisibleConversionFunctions();
  4990. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4991. NamedDecl *D = *I;
  4992. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4993. if (isa<UsingShadowDecl>(D))
  4994. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4995. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4996. CXXConversionDecl *Conv;
  4997. if (ConvTemplate)
  4998. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4999. else
  5000. Conv = cast<CXXConversionDecl>(D);
  5001. if (ConvTemplate)
  5002. S.AddTemplateConversionCandidate(
  5003. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  5004. CandidateSet, AllowExplicit, AllowExplicit);
  5005. else
  5006. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  5007. DestType, CandidateSet, AllowExplicit,
  5008. AllowExplicit);
  5009. }
  5010. }
  5011. }
  5012. // Perform overload resolution. If it fails, return the failed result.
  5013. OverloadCandidateSet::iterator Best;
  5014. if (OverloadingResult Result
  5015. = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  5016. Sequence.SetOverloadFailure(
  5017. InitializationSequence::FK_UserConversionOverloadFailed, Result);
  5018. // [class.copy.elision]p3:
  5019. // In some copy-initialization contexts, a two-stage overload resolution
  5020. // is performed.
  5021. // If the first overload resolution selects a deleted function, we also
  5022. // need the initialization sequence to decide whether to perform the second
  5023. // overload resolution.
  5024. if (!(Result == OR_Deleted &&
  5025. Kind.getKind() == InitializationKind::IK_Copy))
  5026. return;
  5027. }
  5028. FunctionDecl *Function = Best->Function;
  5029. Function->setReferenced();
  5030. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  5031. if (isa<CXXConstructorDecl>(Function)) {
  5032. // Add the user-defined conversion step. Any cv-qualification conversion is
  5033. // subsumed by the initialization. Per DR5, the created temporary is of the
  5034. // cv-unqualified type of the destination.
  5035. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  5036. DestType.getUnqualifiedType(),
  5037. HadMultipleCandidates);
  5038. // C++14 and before:
  5039. // - if the function is a constructor, the call initializes a temporary
  5040. // of the cv-unqualified version of the destination type. The [...]
  5041. // temporary [...] is then used to direct-initialize, according to the
  5042. // rules above, the object that is the destination of the
  5043. // copy-initialization.
  5044. // Note that this just performs a simple object copy from the temporary.
  5045. //
  5046. // C++17:
  5047. // - if the function is a constructor, the call is a prvalue of the
  5048. // cv-unqualified version of the destination type whose return object
  5049. // is initialized by the constructor. The call is used to
  5050. // direct-initialize, according to the rules above, the object that
  5051. // is the destination of the copy-initialization.
  5052. // Therefore we need to do nothing further.
  5053. //
  5054. // FIXME: Mark this copy as extraneous.
  5055. if (!S.getLangOpts().CPlusPlus17)
  5056. Sequence.AddFinalCopy(DestType);
  5057. else if (DestType.hasQualifiers())
  5058. Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
  5059. return;
  5060. }
  5061. // Add the user-defined conversion step that calls the conversion function.
  5062. QualType ConvType = Function->getCallResultType();
  5063. Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
  5064. HadMultipleCandidates);
  5065. if (ConvType->getAs<RecordType>()) {
  5066. // The call is used to direct-initialize [...] the object that is the
  5067. // destination of the copy-initialization.
  5068. //
  5069. // In C++17, this does not call a constructor if we enter /17.6.1:
  5070. // - If the initializer expression is a prvalue and the cv-unqualified
  5071. // version of the source type is the same as the class of the
  5072. // destination [... do not make an extra copy]
  5073. //
  5074. // FIXME: Mark this copy as extraneous.
  5075. if (!S.getLangOpts().CPlusPlus17 ||
  5076. Function->getReturnType()->isReferenceType() ||
  5077. !S.Context.hasSameUnqualifiedType(ConvType, DestType))
  5078. Sequence.AddFinalCopy(DestType);
  5079. else if (!S.Context.hasSameType(ConvType, DestType))
  5080. Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
  5081. return;
  5082. }
  5083. // If the conversion following the call to the conversion function
  5084. // is interesting, add it as a separate step.
  5085. if (Best->FinalConversion.First || Best->FinalConversion.Second ||
  5086. Best->FinalConversion.Third) {
  5087. ImplicitConversionSequence ICS;
  5088. ICS.setStandard();
  5089. ICS.Standard = Best->FinalConversion;
  5090. Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  5091. }
  5092. }
  5093. /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
  5094. /// a function with a pointer return type contains a 'return false;' statement.
  5095. /// In C++11, 'false' is not a null pointer, so this breaks the build of any
  5096. /// code using that header.
  5097. ///
  5098. /// Work around this by treating 'return false;' as zero-initializing the result
  5099. /// if it's used in a pointer-returning function in a system header.
  5100. static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
  5101. const InitializedEntity &Entity,
  5102. const Expr *Init) {
  5103. return S.getLangOpts().CPlusPlus11 &&
  5104. Entity.getKind() == InitializedEntity::EK_Result &&
  5105. Entity.getType()->isPointerType() &&
  5106. isa<CXXBoolLiteralExpr>(Init) &&
  5107. !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
  5108. S.getSourceManager().isInSystemHeader(Init->getExprLoc());
  5109. }
  5110. /// The non-zero enum values here are indexes into diagnostic alternatives.
  5111. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
  5112. /// Determines whether this expression is an acceptable ICR source.
  5113. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
  5114. bool isAddressOf, bool &isWeakAccess) {
  5115. // Skip parens.
  5116. e = e->IgnoreParens();
  5117. // Skip address-of nodes.
  5118. if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  5119. if (op->getOpcode() == UO_AddrOf)
  5120. return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
  5121. isWeakAccess);
  5122. // Skip certain casts.
  5123. } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
  5124. switch (ce->getCastKind()) {
  5125. case CK_Dependent:
  5126. case CK_BitCast:
  5127. case CK_LValueBitCast:
  5128. case CK_NoOp:
  5129. return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
  5130. case CK_ArrayToPointerDecay:
  5131. return IIK_nonscalar;
  5132. case CK_NullToPointer:
  5133. return IIK_okay;
  5134. default:
  5135. break;
  5136. }
  5137. // If we have a declaration reference, it had better be a local variable.
  5138. } else if (isa<DeclRefExpr>(e)) {
  5139. // set isWeakAccess to true, to mean that there will be an implicit
  5140. // load which requires a cleanup.
  5141. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  5142. isWeakAccess = true;
  5143. if (!isAddressOf) return IIK_nonlocal;
  5144. VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
  5145. if (!var) return IIK_nonlocal;
  5146. return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
  5147. // If we have a conditional operator, check both sides.
  5148. } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
  5149. if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
  5150. isWeakAccess))
  5151. return iik;
  5152. return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
  5153. // These are never scalar.
  5154. } else if (isa<ArraySubscriptExpr>(e)) {
  5155. return IIK_nonscalar;
  5156. // Otherwise, it needs to be a null pointer constant.
  5157. } else {
  5158. return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
  5159. ? IIK_okay : IIK_nonlocal);
  5160. }
  5161. return IIK_nonlocal;
  5162. }
  5163. /// Check whether the given expression is a valid operand for an
  5164. /// indirect copy/restore.
  5165. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
  5166. assert(src->isPRValue());
  5167. bool isWeakAccess = false;
  5168. InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
  5169. // If isWeakAccess to true, there will be an implicit
  5170. // load which requires a cleanup.
  5171. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
  5172. S.Cleanup.setExprNeedsCleanups(true);
  5173. if (iik == IIK_okay) return;
  5174. S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
  5175. << ((unsigned) iik - 1) // shift index into diagnostic explanations
  5176. << src->getSourceRange();
  5177. }
  5178. /// Determine whether we have compatible array types for the
  5179. /// purposes of GNU by-copy array initialization.
  5180. static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
  5181. const ArrayType *Source) {
  5182. // If the source and destination array types are equivalent, we're
  5183. // done.
  5184. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
  5185. return true;
  5186. // Make sure that the element types are the same.
  5187. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
  5188. return false;
  5189. // The only mismatch we allow is when the destination is an
  5190. // incomplete array type and the source is a constant array type.
  5191. return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
  5192. }
  5193. static bool tryObjCWritebackConversion(Sema &S,
  5194. InitializationSequence &Sequence,
  5195. const InitializedEntity &Entity,
  5196. Expr *Initializer) {
  5197. bool ArrayDecay = false;
  5198. QualType ArgType = Initializer->getType();
  5199. QualType ArgPointee;
  5200. if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
  5201. ArrayDecay = true;
  5202. ArgPointee = ArgArrayType->getElementType();
  5203. ArgType = S.Context.getPointerType(ArgPointee);
  5204. }
  5205. // Handle write-back conversion.
  5206. QualType ConvertedArgType;
  5207. if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
  5208. ConvertedArgType))
  5209. return false;
  5210. // We should copy unless we're passing to an argument explicitly
  5211. // marked 'out'.
  5212. bool ShouldCopy = true;
  5213. if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  5214. ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  5215. // Do we need an lvalue conversion?
  5216. if (ArrayDecay || Initializer->isGLValue()) {
  5217. ImplicitConversionSequence ICS;
  5218. ICS.setStandard();
  5219. ICS.Standard.setAsIdentityConversion();
  5220. QualType ResultType;
  5221. if (ArrayDecay) {
  5222. ICS.Standard.First = ICK_Array_To_Pointer;
  5223. ResultType = S.Context.getPointerType(ArgPointee);
  5224. } else {
  5225. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  5226. ResultType = Initializer->getType().getNonLValueExprType(S.Context);
  5227. }
  5228. Sequence.AddConversionSequenceStep(ICS, ResultType);
  5229. }
  5230. Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  5231. return true;
  5232. }
  5233. static bool TryOCLSamplerInitialization(Sema &S,
  5234. InitializationSequence &Sequence,
  5235. QualType DestType,
  5236. Expr *Initializer) {
  5237. if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
  5238. (!Initializer->isIntegerConstantExpr(S.Context) &&
  5239. !Initializer->getType()->isSamplerT()))
  5240. return false;
  5241. Sequence.AddOCLSamplerInitStep(DestType);
  5242. return true;
  5243. }
  5244. static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
  5245. return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
  5246. (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
  5247. }
  5248. static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
  5249. InitializationSequence &Sequence,
  5250. QualType DestType,
  5251. Expr *Initializer) {
  5252. if (!S.getLangOpts().OpenCL)
  5253. return false;
  5254. //
  5255. // OpenCL 1.2 spec, s6.12.10
  5256. //
  5257. // The event argument can also be used to associate the
  5258. // async_work_group_copy with a previous async copy allowing
  5259. // an event to be shared by multiple async copies; otherwise
  5260. // event should be zero.
  5261. //
  5262. if (DestType->isEventT() || DestType->isQueueT()) {
  5263. if (!IsZeroInitializer(Initializer, S))
  5264. return false;
  5265. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  5266. return true;
  5267. }
  5268. // We should allow zero initialization for all types defined in the
  5269. // cl_intel_device_side_avc_motion_estimation extension, except
  5270. // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
  5271. if (S.getOpenCLOptions().isAvailableOption(
  5272. "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
  5273. DestType->isOCLIntelSubgroupAVCType()) {
  5274. if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
  5275. DestType->isOCLIntelSubgroupAVCMceResultType())
  5276. return false;
  5277. if (!IsZeroInitializer(Initializer, S))
  5278. return false;
  5279. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  5280. return true;
  5281. }
  5282. return false;
  5283. }
  5284. InitializationSequence::InitializationSequence(
  5285. Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
  5286. MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
  5287. : FailedOverloadResult(OR_Success),
  5288. FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
  5289. InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
  5290. TreatUnavailableAsInvalid);
  5291. }
  5292. /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
  5293. /// address of that function, this returns true. Otherwise, it returns false.
  5294. static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
  5295. auto *DRE = dyn_cast<DeclRefExpr>(E);
  5296. if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
  5297. return false;
  5298. return !S.checkAddressOfFunctionIsAvailable(
  5299. cast<FunctionDecl>(DRE->getDecl()));
  5300. }
  5301. /// Determine whether we can perform an elementwise array copy for this kind
  5302. /// of entity.
  5303. static bool canPerformArrayCopy(const InitializedEntity &Entity) {
  5304. switch (Entity.getKind()) {
  5305. case InitializedEntity::EK_LambdaCapture:
  5306. // C++ [expr.prim.lambda]p24:
  5307. // For array members, the array elements are direct-initialized in
  5308. // increasing subscript order.
  5309. return true;
  5310. case InitializedEntity::EK_Variable:
  5311. // C++ [dcl.decomp]p1:
  5312. // [...] each element is copy-initialized or direct-initialized from the
  5313. // corresponding element of the assignment-expression [...]
  5314. return isa<DecompositionDecl>(Entity.getDecl());
  5315. case InitializedEntity::EK_Member:
  5316. // C++ [class.copy.ctor]p14:
  5317. // - if the member is an array, each element is direct-initialized with
  5318. // the corresponding subobject of x
  5319. return Entity.isImplicitMemberInitializer();
  5320. case InitializedEntity::EK_ArrayElement:
  5321. // All the above cases are intended to apply recursively, even though none
  5322. // of them actually say that.
  5323. if (auto *E = Entity.getParent())
  5324. return canPerformArrayCopy(*E);
  5325. break;
  5326. default:
  5327. break;
  5328. }
  5329. return false;
  5330. }
  5331. void InitializationSequence::InitializeFrom(Sema &S,
  5332. const InitializedEntity &Entity,
  5333. const InitializationKind &Kind,
  5334. MultiExprArg Args,
  5335. bool TopLevelOfInitList,
  5336. bool TreatUnavailableAsInvalid) {
  5337. ASTContext &Context = S.Context;
  5338. // Eliminate non-overload placeholder types in the arguments. We
  5339. // need to do this before checking whether types are dependent
  5340. // because lowering a pseudo-object expression might well give us
  5341. // something of dependent type.
  5342. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  5343. if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
  5344. // FIXME: should we be doing this here?
  5345. ExprResult result = S.CheckPlaceholderExpr(Args[I]);
  5346. if (result.isInvalid()) {
  5347. SetFailed(FK_PlaceholderType);
  5348. return;
  5349. }
  5350. Args[I] = result.get();
  5351. }
  5352. // C++0x [dcl.init]p16:
  5353. // The semantics of initializers are as follows. The destination type is
  5354. // the type of the object or reference being initialized and the source
  5355. // type is the type of the initializer expression. The source type is not
  5356. // defined when the initializer is a braced-init-list or when it is a
  5357. // parenthesized list of expressions.
  5358. QualType DestType = Entity.getType();
  5359. if (DestType->isDependentType() ||
  5360. Expr::hasAnyTypeDependentArguments(Args)) {
  5361. SequenceKind = DependentSequence;
  5362. return;
  5363. }
  5364. // Almost everything is a normal sequence.
  5365. setSequenceKind(NormalSequence);
  5366. QualType SourceType;
  5367. Expr *Initializer = nullptr;
  5368. if (Args.size() == 1) {
  5369. Initializer = Args[0];
  5370. if (S.getLangOpts().ObjC) {
  5371. if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
  5372. DestType, Initializer->getType(),
  5373. Initializer) ||
  5374. S.CheckConversionToObjCLiteral(DestType, Initializer))
  5375. Args[0] = Initializer;
  5376. }
  5377. if (!isa<InitListExpr>(Initializer))
  5378. SourceType = Initializer->getType();
  5379. }
  5380. // - If the initializer is a (non-parenthesized) braced-init-list, the
  5381. // object is list-initialized (8.5.4).
  5382. if (Kind.getKind() != InitializationKind::IK_Direct) {
  5383. if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
  5384. TryListInitialization(S, Entity, Kind, InitList, *this,
  5385. TreatUnavailableAsInvalid);
  5386. return;
  5387. }
  5388. }
  5389. // - If the destination type is a reference type, see 8.5.3.
  5390. if (DestType->isReferenceType()) {
  5391. // C++0x [dcl.init.ref]p1:
  5392. // A variable declared to be a T& or T&&, that is, "reference to type T"
  5393. // (8.3.2), shall be initialized by an object, or function, of type T or
  5394. // by an object that can be converted into a T.
  5395. // (Therefore, multiple arguments are not permitted.)
  5396. if (Args.size() != 1)
  5397. SetFailed(FK_TooManyInitsForReference);
  5398. // C++17 [dcl.init.ref]p5:
  5399. // A reference [...] is initialized by an expression [...] as follows:
  5400. // If the initializer is not an expression, presumably we should reject,
  5401. // but the standard fails to actually say so.
  5402. else if (isa<InitListExpr>(Args[0]))
  5403. SetFailed(FK_ParenthesizedListInitForReference);
  5404. else
  5405. TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
  5406. return;
  5407. }
  5408. // - If the initializer is (), the object is value-initialized.
  5409. if (Kind.getKind() == InitializationKind::IK_Value ||
  5410. (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
  5411. TryValueInitialization(S, Entity, Kind, *this);
  5412. return;
  5413. }
  5414. // Handle default initialization.
  5415. if (Kind.getKind() == InitializationKind::IK_Default) {
  5416. TryDefaultInitialization(S, Entity, Kind, *this);
  5417. return;
  5418. }
  5419. // - If the destination type is an array of characters, an array of
  5420. // char16_t, an array of char32_t, or an array of wchar_t, and the
  5421. // initializer is a string literal, see 8.5.2.
  5422. // - Otherwise, if the destination type is an array, the program is
  5423. // ill-formed.
  5424. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
  5425. if (Initializer && isa<VariableArrayType>(DestAT)) {
  5426. SetFailed(FK_VariableLengthArrayHasInitializer);
  5427. return;
  5428. }
  5429. if (Initializer) {
  5430. switch (IsStringInit(Initializer, DestAT, Context)) {
  5431. case SIF_None:
  5432. TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
  5433. return;
  5434. case SIF_NarrowStringIntoWideChar:
  5435. SetFailed(FK_NarrowStringIntoWideCharArray);
  5436. return;
  5437. case SIF_WideStringIntoChar:
  5438. SetFailed(FK_WideStringIntoCharArray);
  5439. return;
  5440. case SIF_IncompatWideStringIntoWideChar:
  5441. SetFailed(FK_IncompatWideStringIntoWideChar);
  5442. return;
  5443. case SIF_PlainStringIntoUTF8Char:
  5444. SetFailed(FK_PlainStringIntoUTF8Char);
  5445. return;
  5446. case SIF_UTF8StringIntoPlainChar:
  5447. SetFailed(FK_UTF8StringIntoPlainChar);
  5448. return;
  5449. case SIF_Other:
  5450. break;
  5451. }
  5452. }
  5453. // Some kinds of initialization permit an array to be initialized from
  5454. // another array of the same type, and perform elementwise initialization.
  5455. if (Initializer && isa<ConstantArrayType>(DestAT) &&
  5456. S.Context.hasSameUnqualifiedType(Initializer->getType(),
  5457. Entity.getType()) &&
  5458. canPerformArrayCopy(Entity)) {
  5459. // If source is a prvalue, use it directly.
  5460. if (Initializer->isPRValue()) {
  5461. AddArrayInitStep(DestType, /*IsGNUExtension*/false);
  5462. return;
  5463. }
  5464. // Emit element-at-a-time copy loop.
  5465. InitializedEntity Element =
  5466. InitializedEntity::InitializeElement(S.Context, 0, Entity);
  5467. QualType InitEltT =
  5468. Context.getAsArrayType(Initializer->getType())->getElementType();
  5469. OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
  5470. Initializer->getValueKind(),
  5471. Initializer->getObjectKind());
  5472. Expr *OVEAsExpr = &OVE;
  5473. InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
  5474. TreatUnavailableAsInvalid);
  5475. if (!Failed())
  5476. AddArrayInitLoopStep(Entity.getType(), InitEltT);
  5477. return;
  5478. }
  5479. // Note: as an GNU C extension, we allow initialization of an
  5480. // array from a compound literal that creates an array of the same
  5481. // type, so long as the initializer has no side effects.
  5482. if (!S.getLangOpts().CPlusPlus && Initializer &&
  5483. isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
  5484. Initializer->getType()->isArrayType()) {
  5485. const ArrayType *SourceAT
  5486. = Context.getAsArrayType(Initializer->getType());
  5487. if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
  5488. SetFailed(FK_ArrayTypeMismatch);
  5489. else if (Initializer->HasSideEffects(S.Context))
  5490. SetFailed(FK_NonConstantArrayInit);
  5491. else {
  5492. AddArrayInitStep(DestType, /*IsGNUExtension*/true);
  5493. }
  5494. }
  5495. // Note: as a GNU C++ extension, we allow list-initialization of a
  5496. // class member of array type from a parenthesized initializer list.
  5497. else if (S.getLangOpts().CPlusPlus &&
  5498. Entity.getKind() == InitializedEntity::EK_Member &&
  5499. Initializer && isa<InitListExpr>(Initializer)) {
  5500. TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
  5501. *this, TreatUnavailableAsInvalid);
  5502. AddParenthesizedArrayInitStep(DestType);
  5503. } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
  5504. Kind.getKind() == InitializationKind::IK_Direct)
  5505. TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
  5506. /*VerifyOnly=*/true);
  5507. else if (DestAT->getElementType()->isCharType())
  5508. SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
  5509. else if (IsWideCharCompatible(DestAT->getElementType(), Context))
  5510. SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
  5511. else
  5512. SetFailed(FK_ArrayNeedsInitList);
  5513. return;
  5514. }
  5515. // Determine whether we should consider writeback conversions for
  5516. // Objective-C ARC.
  5517. bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
  5518. Entity.isParameterKind();
  5519. if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
  5520. return;
  5521. // We're at the end of the line for C: it's either a write-back conversion
  5522. // or it's a C assignment. There's no need to check anything else.
  5523. if (!S.getLangOpts().CPlusPlus) {
  5524. // If allowed, check whether this is an Objective-C writeback conversion.
  5525. if (allowObjCWritebackConversion &&
  5526. tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
  5527. return;
  5528. }
  5529. if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
  5530. return;
  5531. // Handle initialization in C
  5532. AddCAssignmentStep(DestType);
  5533. MaybeProduceObjCObject(S, *this, Entity);
  5534. return;
  5535. }
  5536. assert(S.getLangOpts().CPlusPlus);
  5537. // - If the destination type is a (possibly cv-qualified) class type:
  5538. if (DestType->isRecordType()) {
  5539. // - If the initialization is direct-initialization, or if it is
  5540. // copy-initialization where the cv-unqualified version of the
  5541. // source type is the same class as, or a derived class of, the
  5542. // class of the destination, constructors are considered. [...]
  5543. if (Kind.getKind() == InitializationKind::IK_Direct ||
  5544. (Kind.getKind() == InitializationKind::IK_Copy &&
  5545. (Context.hasSameUnqualifiedType(SourceType, DestType) ||
  5546. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) {
  5547. TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
  5548. *this);
  5549. // We fall back to the "no matching constructor" path if the
  5550. // failed candidate set has functions other than the three default
  5551. // constructors. For example, conversion function.
  5552. if (const auto *RD =
  5553. dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
  5554. // In general, we should call isCompleteType for RD to check its
  5555. // completeness, we don't call it here as it was already called in the
  5556. // above TryConstructorInitialization.
  5557. S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
  5558. RD->isAggregate() && Failed() &&
  5559. getFailureKind() == FK_ConstructorOverloadFailed) {
  5560. // Do not attempt paren list initialization if overload resolution
  5561. // resolves to a deleted function .
  5562. //
  5563. // We may reach this condition if we have a union wrapping a class with
  5564. // a non-trivial copy or move constructor and we call one of those two
  5565. // constructors. The union is an aggregate, but the matched constructor
  5566. // is implicitly deleted, so we need to prevent aggregate initialization
  5567. // (otherwise, it'll attempt aggregate initialization by initializing
  5568. // the first element with a reference to the union).
  5569. OverloadCandidateSet::iterator Best;
  5570. OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
  5571. S, Kind.getLocation(), Best);
  5572. if (OR != OverloadingResult::OR_Deleted) {
  5573. // C++20 [dcl.init] 17.6.2.2:
  5574. // - Otherwise, if no constructor is viable, the destination type is
  5575. // an
  5576. // aggregate class, and the initializer is a parenthesized
  5577. // expression-list.
  5578. TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
  5579. /*VerifyOnly=*/true);
  5580. }
  5581. }
  5582. } else {
  5583. // - Otherwise (i.e., for the remaining copy-initialization cases),
  5584. // user-defined conversion sequences that can convert from the
  5585. // source type to the destination type or (when a conversion
  5586. // function is used) to a derived class thereof are enumerated as
  5587. // described in 13.3.1.4, and the best one is chosen through
  5588. // overload resolution (13.3).
  5589. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5590. TopLevelOfInitList);
  5591. }
  5592. return;
  5593. }
  5594. assert(Args.size() >= 1 && "Zero-argument case handled above");
  5595. // For HLSL ext vector types we allow list initialization behavior for C++
  5596. // constructor syntax. This is accomplished by converting initialization
  5597. // arguments an InitListExpr late.
  5598. if (S.getLangOpts().HLSL && DestType->isExtVectorType() &&
  5599. (SourceType.isNull() ||
  5600. !Context.hasSameUnqualifiedType(SourceType, DestType))) {
  5601. llvm::SmallVector<Expr *> InitArgs;
  5602. for (auto *Arg : Args) {
  5603. if (Arg->getType()->isExtVectorType()) {
  5604. const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
  5605. unsigned Elm = VTy->getNumElements();
  5606. for (unsigned Idx = 0; Idx < Elm; ++Idx) {
  5607. InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
  5608. Arg,
  5609. IntegerLiteral::Create(
  5610. Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
  5611. Context.IntTy, SourceLocation()),
  5612. VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
  5613. SourceLocation()));
  5614. }
  5615. } else
  5616. InitArgs.emplace_back(Arg);
  5617. }
  5618. InitListExpr *ILE = new (Context) InitListExpr(
  5619. S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
  5620. Args[0] = ILE;
  5621. AddListInitializationStep(DestType);
  5622. return;
  5623. }
  5624. // The remaining cases all need a source type.
  5625. if (Args.size() > 1) {
  5626. SetFailed(FK_TooManyInitsForScalar);
  5627. return;
  5628. } else if (isa<InitListExpr>(Args[0])) {
  5629. SetFailed(FK_ParenthesizedListInitForScalar);
  5630. return;
  5631. }
  5632. // - Otherwise, if the source type is a (possibly cv-qualified) class
  5633. // type, conversion functions are considered.
  5634. if (!SourceType.isNull() && SourceType->isRecordType()) {
  5635. // For a conversion to _Atomic(T) from either T or a class type derived
  5636. // from T, initialize the T object then convert to _Atomic type.
  5637. bool NeedAtomicConversion = false;
  5638. if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
  5639. if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
  5640. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
  5641. Atomic->getValueType())) {
  5642. DestType = Atomic->getValueType();
  5643. NeedAtomicConversion = true;
  5644. }
  5645. }
  5646. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5647. TopLevelOfInitList);
  5648. MaybeProduceObjCObject(S, *this, Entity);
  5649. if (!Failed() && NeedAtomicConversion)
  5650. AddAtomicConversionStep(Entity.getType());
  5651. return;
  5652. }
  5653. // - Otherwise, if the initialization is direct-initialization, the source
  5654. // type is std::nullptr_t, and the destination type is bool, the initial
  5655. // value of the object being initialized is false.
  5656. if (!SourceType.isNull() && SourceType->isNullPtrType() &&
  5657. DestType->isBooleanType() &&
  5658. Kind.getKind() == InitializationKind::IK_Direct) {
  5659. AddConversionSequenceStep(
  5660. ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
  5661. Initializer->isGLValue()),
  5662. DestType);
  5663. return;
  5664. }
  5665. // - Otherwise, the initial value of the object being initialized is the
  5666. // (possibly converted) value of the initializer expression. Standard
  5667. // conversions (Clause 4) will be used, if necessary, to convert the
  5668. // initializer expression to the cv-unqualified version of the
  5669. // destination type; no user-defined conversions are considered.
  5670. ImplicitConversionSequence ICS
  5671. = S.TryImplicitConversion(Initializer, DestType,
  5672. /*SuppressUserConversions*/true,
  5673. Sema::AllowedExplicit::None,
  5674. /*InOverloadResolution*/ false,
  5675. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  5676. allowObjCWritebackConversion);
  5677. if (ICS.isStandard() &&
  5678. ICS.Standard.Second == ICK_Writeback_Conversion) {
  5679. // Objective-C ARC writeback conversion.
  5680. // We should copy unless we're passing to an argument explicitly
  5681. // marked 'out'.
  5682. bool ShouldCopy = true;
  5683. if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  5684. ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  5685. // If there was an lvalue adjustment, add it as a separate conversion.
  5686. if (ICS.Standard.First == ICK_Array_To_Pointer ||
  5687. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5688. ImplicitConversionSequence LvalueICS;
  5689. LvalueICS.setStandard();
  5690. LvalueICS.Standard.setAsIdentityConversion();
  5691. LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
  5692. LvalueICS.Standard.First = ICS.Standard.First;
  5693. AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
  5694. }
  5695. AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
  5696. } else if (ICS.isBad()) {
  5697. DeclAccessPair dap;
  5698. if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
  5699. AddZeroInitializationStep(Entity.getType());
  5700. } else if (Initializer->getType() == Context.OverloadTy &&
  5701. !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
  5702. false, dap))
  5703. SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  5704. else if (Initializer->getType()->isFunctionType() &&
  5705. isExprAnUnaddressableFunction(S, Initializer))
  5706. SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
  5707. else
  5708. SetFailed(InitializationSequence::FK_ConversionFailed);
  5709. } else {
  5710. AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  5711. MaybeProduceObjCObject(S, *this, Entity);
  5712. }
  5713. }
  5714. InitializationSequence::~InitializationSequence() {
  5715. for (auto &S : Steps)
  5716. S.Destroy();
  5717. }
  5718. //===----------------------------------------------------------------------===//
  5719. // Perform initialization
  5720. //===----------------------------------------------------------------------===//
  5721. static Sema::AssignmentAction
  5722. getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
  5723. switch(Entity.getKind()) {
  5724. case InitializedEntity::EK_Variable:
  5725. case InitializedEntity::EK_New:
  5726. case InitializedEntity::EK_Exception:
  5727. case InitializedEntity::EK_Base:
  5728. case InitializedEntity::EK_Delegating:
  5729. return Sema::AA_Initializing;
  5730. case InitializedEntity::EK_Parameter:
  5731. if (Entity.getDecl() &&
  5732. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5733. return Sema::AA_Sending;
  5734. return Sema::AA_Passing;
  5735. case InitializedEntity::EK_Parameter_CF_Audited:
  5736. if (Entity.getDecl() &&
  5737. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5738. return Sema::AA_Sending;
  5739. return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
  5740. case InitializedEntity::EK_Result:
  5741. case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
  5742. return Sema::AA_Returning;
  5743. case InitializedEntity::EK_Temporary:
  5744. case InitializedEntity::EK_RelatedResult:
  5745. // FIXME: Can we tell apart casting vs. converting?
  5746. return Sema::AA_Casting;
  5747. case InitializedEntity::EK_TemplateParameter:
  5748. // This is really initialization, but refer to it as conversion for
  5749. // consistency with CheckConvertedConstantExpression.
  5750. return Sema::AA_Converting;
  5751. case InitializedEntity::EK_Member:
  5752. case InitializedEntity::EK_Binding:
  5753. case InitializedEntity::EK_ArrayElement:
  5754. case InitializedEntity::EK_VectorElement:
  5755. case InitializedEntity::EK_ComplexElement:
  5756. case InitializedEntity::EK_BlockElement:
  5757. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5758. case InitializedEntity::EK_LambdaCapture:
  5759. case InitializedEntity::EK_CompoundLiteralInit:
  5760. return Sema::AA_Initializing;
  5761. }
  5762. llvm_unreachable("Invalid EntityKind!");
  5763. }
  5764. /// Whether we should bind a created object as a temporary when
  5765. /// initializing the given entity.
  5766. static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
  5767. switch (Entity.getKind()) {
  5768. case InitializedEntity::EK_ArrayElement:
  5769. case InitializedEntity::EK_Member:
  5770. case InitializedEntity::EK_Result:
  5771. case InitializedEntity::EK_StmtExprResult:
  5772. case InitializedEntity::EK_New:
  5773. case InitializedEntity::EK_Variable:
  5774. case InitializedEntity::EK_Base:
  5775. case InitializedEntity::EK_Delegating:
  5776. case InitializedEntity::EK_VectorElement:
  5777. case InitializedEntity::EK_ComplexElement:
  5778. case InitializedEntity::EK_Exception:
  5779. case InitializedEntity::EK_BlockElement:
  5780. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5781. case InitializedEntity::EK_LambdaCapture:
  5782. case InitializedEntity::EK_CompoundLiteralInit:
  5783. case InitializedEntity::EK_TemplateParameter:
  5784. return false;
  5785. case InitializedEntity::EK_Parameter:
  5786. case InitializedEntity::EK_Parameter_CF_Audited:
  5787. case InitializedEntity::EK_Temporary:
  5788. case InitializedEntity::EK_RelatedResult:
  5789. case InitializedEntity::EK_Binding:
  5790. return true;
  5791. }
  5792. llvm_unreachable("missed an InitializedEntity kind?");
  5793. }
  5794. /// Whether the given entity, when initialized with an object
  5795. /// created for that initialization, requires destruction.
  5796. static bool shouldDestroyEntity(const InitializedEntity &Entity) {
  5797. switch (Entity.getKind()) {
  5798. case InitializedEntity::EK_Result:
  5799. case InitializedEntity::EK_StmtExprResult:
  5800. case InitializedEntity::EK_New:
  5801. case InitializedEntity::EK_Base:
  5802. case InitializedEntity::EK_Delegating:
  5803. case InitializedEntity::EK_VectorElement:
  5804. case InitializedEntity::EK_ComplexElement:
  5805. case InitializedEntity::EK_BlockElement:
  5806. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5807. case InitializedEntity::EK_LambdaCapture:
  5808. return false;
  5809. case InitializedEntity::EK_Member:
  5810. case InitializedEntity::EK_Binding:
  5811. case InitializedEntity::EK_Variable:
  5812. case InitializedEntity::EK_Parameter:
  5813. case InitializedEntity::EK_Parameter_CF_Audited:
  5814. case InitializedEntity::EK_TemplateParameter:
  5815. case InitializedEntity::EK_Temporary:
  5816. case InitializedEntity::EK_ArrayElement:
  5817. case InitializedEntity::EK_Exception:
  5818. case InitializedEntity::EK_CompoundLiteralInit:
  5819. case InitializedEntity::EK_RelatedResult:
  5820. return true;
  5821. }
  5822. llvm_unreachable("missed an InitializedEntity kind?");
  5823. }
  5824. /// Get the location at which initialization diagnostics should appear.
  5825. static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
  5826. Expr *Initializer) {
  5827. switch (Entity.getKind()) {
  5828. case InitializedEntity::EK_Result:
  5829. case InitializedEntity::EK_StmtExprResult:
  5830. return Entity.getReturnLoc();
  5831. case InitializedEntity::EK_Exception:
  5832. return Entity.getThrowLoc();
  5833. case InitializedEntity::EK_Variable:
  5834. case InitializedEntity::EK_Binding:
  5835. return Entity.getDecl()->getLocation();
  5836. case InitializedEntity::EK_LambdaCapture:
  5837. return Entity.getCaptureLoc();
  5838. case InitializedEntity::EK_ArrayElement:
  5839. case InitializedEntity::EK_Member:
  5840. case InitializedEntity::EK_Parameter:
  5841. case InitializedEntity::EK_Parameter_CF_Audited:
  5842. case InitializedEntity::EK_TemplateParameter:
  5843. case InitializedEntity::EK_Temporary:
  5844. case InitializedEntity::EK_New:
  5845. case InitializedEntity::EK_Base:
  5846. case InitializedEntity::EK_Delegating:
  5847. case InitializedEntity::EK_VectorElement:
  5848. case InitializedEntity::EK_ComplexElement:
  5849. case InitializedEntity::EK_BlockElement:
  5850. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5851. case InitializedEntity::EK_CompoundLiteralInit:
  5852. case InitializedEntity::EK_RelatedResult:
  5853. return Initializer->getBeginLoc();
  5854. }
  5855. llvm_unreachable("missed an InitializedEntity kind?");
  5856. }
  5857. /// Make a (potentially elidable) temporary copy of the object
  5858. /// provided by the given initializer by calling the appropriate copy
  5859. /// constructor.
  5860. ///
  5861. /// \param S The Sema object used for type-checking.
  5862. ///
  5863. /// \param T The type of the temporary object, which must either be
  5864. /// the type of the initializer expression or a superclass thereof.
  5865. ///
  5866. /// \param Entity The entity being initialized.
  5867. ///
  5868. /// \param CurInit The initializer expression.
  5869. ///
  5870. /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
  5871. /// is permitted in C++03 (but not C++0x) when binding a reference to
  5872. /// an rvalue.
  5873. ///
  5874. /// \returns An expression that copies the initializer expression into
  5875. /// a temporary object, or an error expression if a copy could not be
  5876. /// created.
  5877. static ExprResult CopyObject(Sema &S,
  5878. QualType T,
  5879. const InitializedEntity &Entity,
  5880. ExprResult CurInit,
  5881. bool IsExtraneousCopy) {
  5882. if (CurInit.isInvalid())
  5883. return CurInit;
  5884. // Determine which class type we're copying to.
  5885. Expr *CurInitExpr = (Expr *)CurInit.get();
  5886. CXXRecordDecl *Class = nullptr;
  5887. if (const RecordType *Record = T->getAs<RecordType>())
  5888. Class = cast<CXXRecordDecl>(Record->getDecl());
  5889. if (!Class)
  5890. return CurInit;
  5891. SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
  5892. // Make sure that the type we are copying is complete.
  5893. if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
  5894. return CurInit;
  5895. // Perform overload resolution using the class's constructors. Per
  5896. // C++11 [dcl.init]p16, second bullet for class types, this initialization
  5897. // is direct-initialization.
  5898. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5899. DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
  5900. OverloadCandidateSet::iterator Best;
  5901. switch (ResolveConstructorOverload(
  5902. S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
  5903. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  5904. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  5905. /*SecondStepOfCopyInit=*/true)) {
  5906. case OR_Success:
  5907. break;
  5908. case OR_No_Viable_Function:
  5909. CandidateSet.NoteCandidates(
  5910. PartialDiagnosticAt(
  5911. Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
  5912. ? diag::ext_rvalue_to_reference_temp_copy_no_viable
  5913. : diag::err_temp_copy_no_viable)
  5914. << (int)Entity.getKind() << CurInitExpr->getType()
  5915. << CurInitExpr->getSourceRange()),
  5916. S, OCD_AllCandidates, CurInitExpr);
  5917. if (!IsExtraneousCopy || S.isSFINAEContext())
  5918. return ExprError();
  5919. return CurInit;
  5920. case OR_Ambiguous:
  5921. CandidateSet.NoteCandidates(
  5922. PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
  5923. << (int)Entity.getKind()
  5924. << CurInitExpr->getType()
  5925. << CurInitExpr->getSourceRange()),
  5926. S, OCD_AmbiguousCandidates, CurInitExpr);
  5927. return ExprError();
  5928. case OR_Deleted:
  5929. S.Diag(Loc, diag::err_temp_copy_deleted)
  5930. << (int)Entity.getKind() << CurInitExpr->getType()
  5931. << CurInitExpr->getSourceRange();
  5932. S.NoteDeletedFunction(Best->Function);
  5933. return ExprError();
  5934. }
  5935. bool HadMultipleCandidates = CandidateSet.size() > 1;
  5936. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  5937. SmallVector<Expr*, 8> ConstructorArgs;
  5938. CurInit.get(); // Ownership transferred into MultiExprArg, below.
  5939. S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
  5940. IsExtraneousCopy);
  5941. if (IsExtraneousCopy) {
  5942. // If this is a totally extraneous copy for C++03 reference
  5943. // binding purposes, just return the original initialization
  5944. // expression. We don't generate an (elided) copy operation here
  5945. // because doing so would require us to pass down a flag to avoid
  5946. // infinite recursion, where each step adds another extraneous,
  5947. // elidable copy.
  5948. // Instantiate the default arguments of any extra parameters in
  5949. // the selected copy constructor, as if we were going to create a
  5950. // proper call to the copy constructor.
  5951. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
  5952. ParmVarDecl *Parm = Constructor->getParamDecl(I);
  5953. if (S.RequireCompleteType(Loc, Parm->getType(),
  5954. diag::err_call_incomplete_argument))
  5955. break;
  5956. // Build the default argument expression; we don't actually care
  5957. // if this succeeds or not, because this routine will complain
  5958. // if there was a problem.
  5959. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
  5960. }
  5961. return CurInitExpr;
  5962. }
  5963. // Determine the arguments required to actually perform the
  5964. // constructor call (we might have derived-to-base conversions, or
  5965. // the copy constructor may have default arguments).
  5966. if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
  5967. ConstructorArgs))
  5968. return ExprError();
  5969. // C++0x [class.copy]p32:
  5970. // When certain criteria are met, an implementation is allowed to
  5971. // omit the copy/move construction of a class object, even if the
  5972. // copy/move constructor and/or destructor for the object have
  5973. // side effects. [...]
  5974. // - when a temporary class object that has not been bound to a
  5975. // reference (12.2) would be copied/moved to a class object
  5976. // with the same cv-unqualified type, the copy/move operation
  5977. // can be omitted by constructing the temporary object
  5978. // directly into the target of the omitted copy/move
  5979. //
  5980. // Note that the other three bullets are handled elsewhere. Copy
  5981. // elision for return statements and throw expressions are handled as part
  5982. // of constructor initialization, while copy elision for exception handlers
  5983. // is handled by the run-time.
  5984. //
  5985. // FIXME: If the function parameter is not the same type as the temporary, we
  5986. // should still be able to elide the copy, but we don't have a way to
  5987. // represent in the AST how much should be elided in this case.
  5988. bool Elidable =
  5989. CurInitExpr->isTemporaryObject(S.Context, Class) &&
  5990. S.Context.hasSameUnqualifiedType(
  5991. Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
  5992. CurInitExpr->getType());
  5993. // Actually perform the constructor call.
  5994. CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
  5995. Elidable,
  5996. ConstructorArgs,
  5997. HadMultipleCandidates,
  5998. /*ListInit*/ false,
  5999. /*StdInitListInit*/ false,
  6000. /*ZeroInit*/ false,
  6001. CXXConstructExpr::CK_Complete,
  6002. SourceRange());
  6003. // If we're supposed to bind temporaries, do so.
  6004. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
  6005. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  6006. return CurInit;
  6007. }
  6008. /// Check whether elidable copy construction for binding a reference to
  6009. /// a temporary would have succeeded if we were building in C++98 mode, for
  6010. /// -Wc++98-compat.
  6011. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  6012. const InitializedEntity &Entity,
  6013. Expr *CurInitExpr) {
  6014. assert(S.getLangOpts().CPlusPlus11);
  6015. const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
  6016. if (!Record)
  6017. return;
  6018. SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
  6019. if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
  6020. return;
  6021. // Find constructors which would have been considered.
  6022. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  6023. DeclContext::lookup_result Ctors =
  6024. S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
  6025. // Perform overload resolution.
  6026. OverloadCandidateSet::iterator Best;
  6027. OverloadingResult OR = ResolveConstructorOverload(
  6028. S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
  6029. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  6030. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  6031. /*SecondStepOfCopyInit=*/true);
  6032. PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
  6033. << OR << (int)Entity.getKind() << CurInitExpr->getType()
  6034. << CurInitExpr->getSourceRange();
  6035. switch (OR) {
  6036. case OR_Success:
  6037. S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
  6038. Best->FoundDecl, Entity, Diag);
  6039. // FIXME: Check default arguments as far as that's possible.
  6040. break;
  6041. case OR_No_Viable_Function:
  6042. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  6043. OCD_AllCandidates, CurInitExpr);
  6044. break;
  6045. case OR_Ambiguous:
  6046. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  6047. OCD_AmbiguousCandidates, CurInitExpr);
  6048. break;
  6049. case OR_Deleted:
  6050. S.Diag(Loc, Diag);
  6051. S.NoteDeletedFunction(Best->Function);
  6052. break;
  6053. }
  6054. }
  6055. void InitializationSequence::PrintInitLocationNote(Sema &S,
  6056. const InitializedEntity &Entity) {
  6057. if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
  6058. if (Entity.getDecl()->getLocation().isInvalid())
  6059. return;
  6060. if (Entity.getDecl()->getDeclName())
  6061. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
  6062. << Entity.getDecl()->getDeclName();
  6063. else
  6064. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
  6065. }
  6066. else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
  6067. Entity.getMethodDecl())
  6068. S.Diag(Entity.getMethodDecl()->getLocation(),
  6069. diag::note_method_return_type_change)
  6070. << Entity.getMethodDecl()->getDeclName();
  6071. }
  6072. /// Returns true if the parameters describe a constructor initialization of
  6073. /// an explicit temporary object, e.g. "Point(x, y)".
  6074. static bool isExplicitTemporary(const InitializedEntity &Entity,
  6075. const InitializationKind &Kind,
  6076. unsigned NumArgs) {
  6077. switch (Entity.getKind()) {
  6078. case InitializedEntity::EK_Temporary:
  6079. case InitializedEntity::EK_CompoundLiteralInit:
  6080. case InitializedEntity::EK_RelatedResult:
  6081. break;
  6082. default:
  6083. return false;
  6084. }
  6085. switch (Kind.getKind()) {
  6086. case InitializationKind::IK_DirectList:
  6087. return true;
  6088. // FIXME: Hack to work around cast weirdness.
  6089. case InitializationKind::IK_Direct:
  6090. case InitializationKind::IK_Value:
  6091. return NumArgs != 1;
  6092. default:
  6093. return false;
  6094. }
  6095. }
  6096. static ExprResult
  6097. PerformConstructorInitialization(Sema &S,
  6098. const InitializedEntity &Entity,
  6099. const InitializationKind &Kind,
  6100. MultiExprArg Args,
  6101. const InitializationSequence::Step& Step,
  6102. bool &ConstructorInitRequiresZeroInit,
  6103. bool IsListInitialization,
  6104. bool IsStdInitListInitialization,
  6105. SourceLocation LBraceLoc,
  6106. SourceLocation RBraceLoc) {
  6107. unsigned NumArgs = Args.size();
  6108. CXXConstructorDecl *Constructor
  6109. = cast<CXXConstructorDecl>(Step.Function.Function);
  6110. bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
  6111. // Build a call to the selected constructor.
  6112. SmallVector<Expr*, 8> ConstructorArgs;
  6113. SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
  6114. ? Kind.getEqualLoc()
  6115. : Kind.getLocation();
  6116. if (Kind.getKind() == InitializationKind::IK_Default) {
  6117. // Force even a trivial, implicit default constructor to be
  6118. // semantically checked. We do this explicitly because we don't build
  6119. // the definition for completely trivial constructors.
  6120. assert(Constructor->getParent() && "No parent class for constructor.");
  6121. if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  6122. Constructor->isTrivial() && !Constructor->isUsed(false)) {
  6123. S.runWithSufficientStackSpace(Loc, [&] {
  6124. S.DefineImplicitDefaultConstructor(Loc, Constructor);
  6125. });
  6126. }
  6127. }
  6128. ExprResult CurInit((Expr *)nullptr);
  6129. // C++ [over.match.copy]p1:
  6130. // - When initializing a temporary to be bound to the first parameter
  6131. // of a constructor that takes a reference to possibly cv-qualified
  6132. // T as its first argument, called with a single argument in the
  6133. // context of direct-initialization, explicit conversion functions
  6134. // are also considered.
  6135. bool AllowExplicitConv =
  6136. Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
  6137. hasCopyOrMoveCtorParam(S.Context,
  6138. getConstructorInfo(Step.Function.FoundDecl));
  6139. // Determine the arguments required to actually perform the constructor
  6140. // call.
  6141. if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
  6142. ConstructorArgs, AllowExplicitConv,
  6143. IsListInitialization))
  6144. return ExprError();
  6145. if (isExplicitTemporary(Entity, Kind, NumArgs)) {
  6146. // An explicitly-constructed temporary, e.g., X(1, 2).
  6147. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  6148. return ExprError();
  6149. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  6150. if (!TSInfo)
  6151. TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
  6152. SourceRange ParenOrBraceRange =
  6153. (Kind.getKind() == InitializationKind::IK_DirectList)
  6154. ? SourceRange(LBraceLoc, RBraceLoc)
  6155. : Kind.getParenOrBraceRange();
  6156. CXXConstructorDecl *CalleeDecl = Constructor;
  6157. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
  6158. Step.Function.FoundDecl.getDecl())) {
  6159. CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
  6160. if (S.DiagnoseUseOfDecl(CalleeDecl, Loc))
  6161. return ExprError();
  6162. }
  6163. S.MarkFunctionReferenced(Loc, CalleeDecl);
  6164. CurInit = S.CheckForImmediateInvocation(
  6165. CXXTemporaryObjectExpr::Create(
  6166. S.Context, CalleeDecl,
  6167. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  6168. ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
  6169. IsListInitialization, IsStdInitListInitialization,
  6170. ConstructorInitRequiresZeroInit),
  6171. CalleeDecl);
  6172. } else {
  6173. CXXConstructExpr::ConstructionKind ConstructKind =
  6174. CXXConstructExpr::CK_Complete;
  6175. if (Entity.getKind() == InitializedEntity::EK_Base) {
  6176. ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
  6177. CXXConstructExpr::CK_VirtualBase :
  6178. CXXConstructExpr::CK_NonVirtualBase;
  6179. } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
  6180. ConstructKind = CXXConstructExpr::CK_Delegating;
  6181. }
  6182. // Only get the parenthesis or brace range if it is a list initialization or
  6183. // direct construction.
  6184. SourceRange ParenOrBraceRange;
  6185. if (IsListInitialization)
  6186. ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
  6187. else if (Kind.getKind() == InitializationKind::IK_Direct)
  6188. ParenOrBraceRange = Kind.getParenOrBraceRange();
  6189. // If the entity allows NRVO, mark the construction as elidable
  6190. // unconditionally.
  6191. if (Entity.allowsNRVO())
  6192. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  6193. Step.Function.FoundDecl,
  6194. Constructor, /*Elidable=*/true,
  6195. ConstructorArgs,
  6196. HadMultipleCandidates,
  6197. IsListInitialization,
  6198. IsStdInitListInitialization,
  6199. ConstructorInitRequiresZeroInit,
  6200. ConstructKind,
  6201. ParenOrBraceRange);
  6202. else
  6203. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  6204. Step.Function.FoundDecl,
  6205. Constructor,
  6206. ConstructorArgs,
  6207. HadMultipleCandidates,
  6208. IsListInitialization,
  6209. IsStdInitListInitialization,
  6210. ConstructorInitRequiresZeroInit,
  6211. ConstructKind,
  6212. ParenOrBraceRange);
  6213. }
  6214. if (CurInit.isInvalid())
  6215. return ExprError();
  6216. // Only check access if all of that succeeded.
  6217. S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
  6218. if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
  6219. return ExprError();
  6220. if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
  6221. if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
  6222. return ExprError();
  6223. if (shouldBindAsTemporary(Entity))
  6224. CurInit = S.MaybeBindToTemporary(CurInit.get());
  6225. return CurInit;
  6226. }
  6227. namespace {
  6228. enum LifetimeKind {
  6229. /// The lifetime of a temporary bound to this entity ends at the end of the
  6230. /// full-expression, and that's (probably) fine.
  6231. LK_FullExpression,
  6232. /// The lifetime of a temporary bound to this entity is extended to the
  6233. /// lifeitme of the entity itself.
  6234. LK_Extended,
  6235. /// The lifetime of a temporary bound to this entity probably ends too soon,
  6236. /// because the entity is allocated in a new-expression.
  6237. LK_New,
  6238. /// The lifetime of a temporary bound to this entity ends too soon, because
  6239. /// the entity is a return object.
  6240. LK_Return,
  6241. /// The lifetime of a temporary bound to this entity ends too soon, because
  6242. /// the entity is the result of a statement expression.
  6243. LK_StmtExprResult,
  6244. /// This is a mem-initializer: if it would extend a temporary (other than via
  6245. /// a default member initializer), the program is ill-formed.
  6246. LK_MemInitializer,
  6247. };
  6248. using LifetimeResult =
  6249. llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
  6250. }
  6251. /// Determine the declaration which an initialized entity ultimately refers to,
  6252. /// for the purpose of lifetime-extending a temporary bound to a reference in
  6253. /// the initialization of \p Entity.
  6254. static LifetimeResult getEntityLifetime(
  6255. const InitializedEntity *Entity,
  6256. const InitializedEntity *InitField = nullptr) {
  6257. // C++11 [class.temporary]p5:
  6258. switch (Entity->getKind()) {
  6259. case InitializedEntity::EK_Variable:
  6260. // The temporary [...] persists for the lifetime of the reference
  6261. return {Entity, LK_Extended};
  6262. case InitializedEntity::EK_Member:
  6263. // For subobjects, we look at the complete object.
  6264. if (Entity->getParent())
  6265. return getEntityLifetime(Entity->getParent(), Entity);
  6266. // except:
  6267. // C++17 [class.base.init]p8:
  6268. // A temporary expression bound to a reference member in a
  6269. // mem-initializer is ill-formed.
  6270. // C++17 [class.base.init]p11:
  6271. // A temporary expression bound to a reference member from a
  6272. // default member initializer is ill-formed.
  6273. //
  6274. // The context of p11 and its example suggest that it's only the use of a
  6275. // default member initializer from a constructor that makes the program
  6276. // ill-formed, not its mere existence, and that it can even be used by
  6277. // aggregate initialization.
  6278. return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
  6279. : LK_MemInitializer};
  6280. case InitializedEntity::EK_Binding:
  6281. // Per [dcl.decomp]p3, the binding is treated as a variable of reference
  6282. // type.
  6283. return {Entity, LK_Extended};
  6284. case InitializedEntity::EK_Parameter:
  6285. case InitializedEntity::EK_Parameter_CF_Audited:
  6286. // -- A temporary bound to a reference parameter in a function call
  6287. // persists until the completion of the full-expression containing
  6288. // the call.
  6289. return {nullptr, LK_FullExpression};
  6290. case InitializedEntity::EK_TemplateParameter:
  6291. // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
  6292. return {nullptr, LK_FullExpression};
  6293. case InitializedEntity::EK_Result:
  6294. // -- The lifetime of a temporary bound to the returned value in a
  6295. // function return statement is not extended; the temporary is
  6296. // destroyed at the end of the full-expression in the return statement.
  6297. return {nullptr, LK_Return};
  6298. case InitializedEntity::EK_StmtExprResult:
  6299. // FIXME: Should we lifetime-extend through the result of a statement
  6300. // expression?
  6301. return {nullptr, LK_StmtExprResult};
  6302. case InitializedEntity::EK_New:
  6303. // -- A temporary bound to a reference in a new-initializer persists
  6304. // until the completion of the full-expression containing the
  6305. // new-initializer.
  6306. return {nullptr, LK_New};
  6307. case InitializedEntity::EK_Temporary:
  6308. case InitializedEntity::EK_CompoundLiteralInit:
  6309. case InitializedEntity::EK_RelatedResult:
  6310. // We don't yet know the storage duration of the surrounding temporary.
  6311. // Assume it's got full-expression duration for now, it will patch up our
  6312. // storage duration if that's not correct.
  6313. return {nullptr, LK_FullExpression};
  6314. case InitializedEntity::EK_ArrayElement:
  6315. // For subobjects, we look at the complete object.
  6316. return getEntityLifetime(Entity->getParent(), InitField);
  6317. case InitializedEntity::EK_Base:
  6318. // For subobjects, we look at the complete object.
  6319. if (Entity->getParent())
  6320. return getEntityLifetime(Entity->getParent(), InitField);
  6321. return {InitField, LK_MemInitializer};
  6322. case InitializedEntity::EK_Delegating:
  6323. // We can reach this case for aggregate initialization in a constructor:
  6324. // struct A { int &&r; };
  6325. // struct B : A { B() : A{0} {} };
  6326. // In this case, use the outermost field decl as the context.
  6327. return {InitField, LK_MemInitializer};
  6328. case InitializedEntity::EK_BlockElement:
  6329. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  6330. case InitializedEntity::EK_LambdaCapture:
  6331. case InitializedEntity::EK_VectorElement:
  6332. case InitializedEntity::EK_ComplexElement:
  6333. return {nullptr, LK_FullExpression};
  6334. case InitializedEntity::EK_Exception:
  6335. // FIXME: Can we diagnose lifetime problems with exceptions?
  6336. return {nullptr, LK_FullExpression};
  6337. }
  6338. llvm_unreachable("unknown entity kind");
  6339. }
  6340. namespace {
  6341. enum ReferenceKind {
  6342. /// Lifetime would be extended by a reference binding to a temporary.
  6343. RK_ReferenceBinding,
  6344. /// Lifetime would be extended by a std::initializer_list object binding to
  6345. /// its backing array.
  6346. RK_StdInitializerList,
  6347. };
  6348. /// A temporary or local variable. This will be one of:
  6349. /// * A MaterializeTemporaryExpr.
  6350. /// * A DeclRefExpr whose declaration is a local.
  6351. /// * An AddrLabelExpr.
  6352. /// * A BlockExpr for a block with captures.
  6353. using Local = Expr*;
  6354. /// Expressions we stepped over when looking for the local state. Any steps
  6355. /// that would inhibit lifetime extension or take us out of subexpressions of
  6356. /// the initializer are included.
  6357. struct IndirectLocalPathEntry {
  6358. enum EntryKind {
  6359. DefaultInit,
  6360. AddressOf,
  6361. VarInit,
  6362. LValToRVal,
  6363. LifetimeBoundCall,
  6364. TemporaryCopy,
  6365. LambdaCaptureInit,
  6366. GslReferenceInit,
  6367. GslPointerInit
  6368. } Kind;
  6369. Expr *E;
  6370. union {
  6371. const Decl *D = nullptr;
  6372. const LambdaCapture *Capture;
  6373. };
  6374. IndirectLocalPathEntry() {}
  6375. IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
  6376. IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
  6377. : Kind(K), E(E), D(D) {}
  6378. IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
  6379. : Kind(K), E(E), Capture(Capture) {}
  6380. };
  6381. using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
  6382. struct RevertToOldSizeRAII {
  6383. IndirectLocalPath &Path;
  6384. unsigned OldSize = Path.size();
  6385. RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
  6386. ~RevertToOldSizeRAII() { Path.resize(OldSize); }
  6387. };
  6388. using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
  6389. ReferenceKind RK)>;
  6390. }
  6391. static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
  6392. for (auto E : Path)
  6393. if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
  6394. return true;
  6395. return false;
  6396. }
  6397. static bool pathContainsInit(IndirectLocalPath &Path) {
  6398. return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
  6399. return E.Kind == IndirectLocalPathEntry::DefaultInit ||
  6400. E.Kind == IndirectLocalPathEntry::VarInit;
  6401. });
  6402. }
  6403. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  6404. Expr *Init, LocalVisitor Visit,
  6405. bool RevisitSubinits,
  6406. bool EnableLifetimeWarnings);
  6407. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  6408. Expr *Init, ReferenceKind RK,
  6409. LocalVisitor Visit,
  6410. bool EnableLifetimeWarnings);
  6411. template <typename T> static bool isRecordWithAttr(QualType Type) {
  6412. if (auto *RD = Type->getAsCXXRecordDecl())
  6413. return RD->hasAttr<T>();
  6414. return false;
  6415. }
  6416. // Decl::isInStdNamespace will return false for iterators in some STL
  6417. // implementations due to them being defined in a namespace outside of the std
  6418. // namespace.
  6419. static bool isInStlNamespace(const Decl *D) {
  6420. const DeclContext *DC = D->getDeclContext();
  6421. if (!DC)
  6422. return false;
  6423. if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
  6424. if (const IdentifierInfo *II = ND->getIdentifier()) {
  6425. StringRef Name = II->getName();
  6426. if (Name.size() >= 2 && Name.front() == '_' &&
  6427. (Name[1] == '_' || isUppercase(Name[1])))
  6428. return true;
  6429. }
  6430. return DC->isStdNamespace();
  6431. }
  6432. static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
  6433. if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
  6434. if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
  6435. return true;
  6436. if (!isInStlNamespace(Callee->getParent()))
  6437. return false;
  6438. if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
  6439. !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
  6440. return false;
  6441. if (Callee->getReturnType()->isPointerType() ||
  6442. isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
  6443. if (!Callee->getIdentifier())
  6444. return false;
  6445. return llvm::StringSwitch<bool>(Callee->getName())
  6446. .Cases("begin", "rbegin", "cbegin", "crbegin", true)
  6447. .Cases("end", "rend", "cend", "crend", true)
  6448. .Cases("c_str", "data", "get", true)
  6449. // Map and set types.
  6450. .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
  6451. .Default(false);
  6452. } else if (Callee->getReturnType()->isReferenceType()) {
  6453. if (!Callee->getIdentifier()) {
  6454. auto OO = Callee->getOverloadedOperator();
  6455. return OO == OverloadedOperatorKind::OO_Subscript ||
  6456. OO == OverloadedOperatorKind::OO_Star;
  6457. }
  6458. return llvm::StringSwitch<bool>(Callee->getName())
  6459. .Cases("front", "back", "at", "top", "value", true)
  6460. .Default(false);
  6461. }
  6462. return false;
  6463. }
  6464. static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
  6465. if (!FD->getIdentifier() || FD->getNumParams() != 1)
  6466. return false;
  6467. const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
  6468. if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
  6469. return false;
  6470. if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
  6471. !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
  6472. return false;
  6473. if (FD->getReturnType()->isPointerType() ||
  6474. isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
  6475. return llvm::StringSwitch<bool>(FD->getName())
  6476. .Cases("begin", "rbegin", "cbegin", "crbegin", true)
  6477. .Cases("end", "rend", "cend", "crend", true)
  6478. .Case("data", true)
  6479. .Default(false);
  6480. } else if (FD->getReturnType()->isReferenceType()) {
  6481. return llvm::StringSwitch<bool>(FD->getName())
  6482. .Cases("get", "any_cast", true)
  6483. .Default(false);
  6484. }
  6485. return false;
  6486. }
  6487. static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
  6488. LocalVisitor Visit) {
  6489. auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
  6490. // We are not interested in the temporary base objects of gsl Pointers:
  6491. // Temp().ptr; // Here ptr might not dangle.
  6492. if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
  6493. return;
  6494. // Once we initialized a value with a reference, it can no longer dangle.
  6495. if (!Value) {
  6496. for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
  6497. if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
  6498. continue;
  6499. if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
  6500. return;
  6501. break;
  6502. }
  6503. }
  6504. Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
  6505. : IndirectLocalPathEntry::GslReferenceInit,
  6506. Arg, D});
  6507. if (Arg->isGLValue())
  6508. visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
  6509. Visit,
  6510. /*EnableLifetimeWarnings=*/true);
  6511. else
  6512. visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
  6513. /*EnableLifetimeWarnings=*/true);
  6514. Path.pop_back();
  6515. };
  6516. if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
  6517. const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
  6518. if (MD && shouldTrackImplicitObjectArg(MD))
  6519. VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
  6520. !MD->getReturnType()->isReferenceType());
  6521. return;
  6522. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
  6523. FunctionDecl *Callee = OCE->getDirectCallee();
  6524. if (Callee && Callee->isCXXInstanceMember() &&
  6525. shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
  6526. VisitPointerArg(Callee, OCE->getArg(0),
  6527. !Callee->getReturnType()->isReferenceType());
  6528. return;
  6529. } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
  6530. FunctionDecl *Callee = CE->getDirectCallee();
  6531. if (Callee && shouldTrackFirstArgument(Callee))
  6532. VisitPointerArg(Callee, CE->getArg(0),
  6533. !Callee->getReturnType()->isReferenceType());
  6534. return;
  6535. }
  6536. if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
  6537. const auto *Ctor = CCE->getConstructor();
  6538. const CXXRecordDecl *RD = Ctor->getParent();
  6539. if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
  6540. VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
  6541. }
  6542. }
  6543. static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
  6544. const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
  6545. if (!TSI)
  6546. return false;
  6547. // Don't declare this variable in the second operand of the for-statement;
  6548. // GCC miscompiles that by ending its lifetime before evaluating the
  6549. // third operand. See gcc.gnu.org/PR86769.
  6550. AttributedTypeLoc ATL;
  6551. for (TypeLoc TL = TSI->getTypeLoc();
  6552. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  6553. TL = ATL.getModifiedLoc()) {
  6554. if (ATL.getAttrAs<LifetimeBoundAttr>())
  6555. return true;
  6556. }
  6557. // Assume that all assignment operators with a "normal" return type return
  6558. // *this, that is, an lvalue reference that is the same type as the implicit
  6559. // object parameter (or the LHS for a non-member operator$=).
  6560. OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
  6561. if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
  6562. QualType RetT = FD->getReturnType();
  6563. if (RetT->isLValueReferenceType()) {
  6564. ASTContext &Ctx = FD->getASTContext();
  6565. QualType LHST;
  6566. auto *MD = dyn_cast<CXXMethodDecl>(FD);
  6567. if (MD && MD->isCXXInstanceMember())
  6568. LHST = Ctx.getLValueReferenceType(MD->getThisObjectType());
  6569. else
  6570. LHST = MD->getParamDecl(0)->getType();
  6571. if (Ctx.hasSameType(RetT, LHST))
  6572. return true;
  6573. }
  6574. }
  6575. return false;
  6576. }
  6577. static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
  6578. LocalVisitor Visit) {
  6579. const FunctionDecl *Callee;
  6580. ArrayRef<Expr*> Args;
  6581. if (auto *CE = dyn_cast<CallExpr>(Call)) {
  6582. Callee = CE->getDirectCallee();
  6583. Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
  6584. } else {
  6585. auto *CCE = cast<CXXConstructExpr>(Call);
  6586. Callee = CCE->getConstructor();
  6587. Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
  6588. }
  6589. if (!Callee)
  6590. return;
  6591. Expr *ObjectArg = nullptr;
  6592. if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
  6593. ObjectArg = Args[0];
  6594. Args = Args.slice(1);
  6595. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
  6596. ObjectArg = MCE->getImplicitObjectArgument();
  6597. }
  6598. auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
  6599. Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
  6600. if (Arg->isGLValue())
  6601. visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
  6602. Visit,
  6603. /*EnableLifetimeWarnings=*/false);
  6604. else
  6605. visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
  6606. /*EnableLifetimeWarnings=*/false);
  6607. Path.pop_back();
  6608. };
  6609. if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
  6610. VisitLifetimeBoundArg(Callee, ObjectArg);
  6611. for (unsigned I = 0,
  6612. N = std::min<unsigned>(Callee->getNumParams(), Args.size());
  6613. I != N; ++I) {
  6614. if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
  6615. VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
  6616. }
  6617. }
  6618. /// Visit the locals that would be reachable through a reference bound to the
  6619. /// glvalue expression \c Init.
  6620. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  6621. Expr *Init, ReferenceKind RK,
  6622. LocalVisitor Visit,
  6623. bool EnableLifetimeWarnings) {
  6624. RevertToOldSizeRAII RAII(Path);
  6625. // Walk past any constructs which we can lifetime-extend across.
  6626. Expr *Old;
  6627. do {
  6628. Old = Init;
  6629. if (auto *FE = dyn_cast<FullExpr>(Init))
  6630. Init = FE->getSubExpr();
  6631. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  6632. // If this is just redundant braces around an initializer, step over it.
  6633. if (ILE->isTransparent())
  6634. Init = ILE->getInit(0);
  6635. }
  6636. // Step over any subobject adjustments; we may have a materialized
  6637. // temporary inside them.
  6638. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  6639. // Per current approach for DR1376, look through casts to reference type
  6640. // when performing lifetime extension.
  6641. if (CastExpr *CE = dyn_cast<CastExpr>(Init))
  6642. if (CE->getSubExpr()->isGLValue())
  6643. Init = CE->getSubExpr();
  6644. // Per the current approach for DR1299, look through array element access
  6645. // on array glvalues when performing lifetime extension.
  6646. if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
  6647. Init = ASE->getBase();
  6648. auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
  6649. if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
  6650. Init = ICE->getSubExpr();
  6651. else
  6652. // We can't lifetime extend through this but we might still find some
  6653. // retained temporaries.
  6654. return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
  6655. EnableLifetimeWarnings);
  6656. }
  6657. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  6658. // constructor inherits one as an implicit mem-initializer.
  6659. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  6660. Path.push_back(
  6661. {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  6662. Init = DIE->getExpr();
  6663. }
  6664. } while (Init != Old);
  6665. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  6666. if (Visit(Path, Local(MTE), RK))
  6667. visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
  6668. EnableLifetimeWarnings);
  6669. }
  6670. if (isa<CallExpr>(Init)) {
  6671. if (EnableLifetimeWarnings)
  6672. handleGslAnnotatedTypes(Path, Init, Visit);
  6673. return visitLifetimeBoundArguments(Path, Init, Visit);
  6674. }
  6675. switch (Init->getStmtClass()) {
  6676. case Stmt::DeclRefExprClass: {
  6677. // If we find the name of a local non-reference parameter, we could have a
  6678. // lifetime problem.
  6679. auto *DRE = cast<DeclRefExpr>(Init);
  6680. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6681. if (VD && VD->hasLocalStorage() &&
  6682. !DRE->refersToEnclosingVariableOrCapture()) {
  6683. if (!VD->getType()->isReferenceType()) {
  6684. Visit(Path, Local(DRE), RK);
  6685. } else if (isa<ParmVarDecl>(DRE->getDecl())) {
  6686. // The lifetime of a reference parameter is unknown; assume it's OK
  6687. // for now.
  6688. break;
  6689. } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
  6690. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  6691. visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
  6692. RK_ReferenceBinding, Visit,
  6693. EnableLifetimeWarnings);
  6694. }
  6695. }
  6696. break;
  6697. }
  6698. case Stmt::UnaryOperatorClass: {
  6699. // The only unary operator that make sense to handle here
  6700. // is Deref. All others don't resolve to a "name." This includes
  6701. // handling all sorts of rvalues passed to a unary operator.
  6702. const UnaryOperator *U = cast<UnaryOperator>(Init);
  6703. if (U->getOpcode() == UO_Deref)
  6704. visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
  6705. EnableLifetimeWarnings);
  6706. break;
  6707. }
  6708. case Stmt::OMPArraySectionExprClass: {
  6709. visitLocalsRetainedByInitializer(Path,
  6710. cast<OMPArraySectionExpr>(Init)->getBase(),
  6711. Visit, true, EnableLifetimeWarnings);
  6712. break;
  6713. }
  6714. case Stmt::ConditionalOperatorClass:
  6715. case Stmt::BinaryConditionalOperatorClass: {
  6716. auto *C = cast<AbstractConditionalOperator>(Init);
  6717. if (!C->getTrueExpr()->getType()->isVoidType())
  6718. visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
  6719. EnableLifetimeWarnings);
  6720. if (!C->getFalseExpr()->getType()->isVoidType())
  6721. visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
  6722. EnableLifetimeWarnings);
  6723. break;
  6724. }
  6725. // FIXME: Visit the left-hand side of an -> or ->*.
  6726. default:
  6727. break;
  6728. }
  6729. }
  6730. /// Visit the locals that would be reachable through an object initialized by
  6731. /// the prvalue expression \c Init.
  6732. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  6733. Expr *Init, LocalVisitor Visit,
  6734. bool RevisitSubinits,
  6735. bool EnableLifetimeWarnings) {
  6736. RevertToOldSizeRAII RAII(Path);
  6737. Expr *Old;
  6738. do {
  6739. Old = Init;
  6740. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  6741. // constructor inherits one as an implicit mem-initializer.
  6742. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  6743. Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  6744. Init = DIE->getExpr();
  6745. }
  6746. if (auto *FE = dyn_cast<FullExpr>(Init))
  6747. Init = FE->getSubExpr();
  6748. // Dig out the expression which constructs the extended temporary.
  6749. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  6750. if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
  6751. Init = BTE->getSubExpr();
  6752. Init = Init->IgnoreParens();
  6753. // Step over value-preserving rvalue casts.
  6754. if (auto *CE = dyn_cast<CastExpr>(Init)) {
  6755. switch (CE->getCastKind()) {
  6756. case CK_LValueToRValue:
  6757. // If we can match the lvalue to a const object, we can look at its
  6758. // initializer.
  6759. Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
  6760. return visitLocalsRetainedByReferenceBinding(
  6761. Path, Init, RK_ReferenceBinding,
  6762. [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
  6763. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  6764. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6765. if (VD && VD->getType().isConstQualified() && VD->getInit() &&
  6766. !isVarOnPath(Path, VD)) {
  6767. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  6768. visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
  6769. EnableLifetimeWarnings);
  6770. }
  6771. } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
  6772. if (MTE->getType().isConstQualified())
  6773. visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
  6774. true, EnableLifetimeWarnings);
  6775. }
  6776. return false;
  6777. }, EnableLifetimeWarnings);
  6778. // We assume that objects can be retained by pointers cast to integers,
  6779. // but not if the integer is cast to floating-point type or to _Complex.
  6780. // We assume that casts to 'bool' do not preserve enough information to
  6781. // retain a local object.
  6782. case CK_NoOp:
  6783. case CK_BitCast:
  6784. case CK_BaseToDerived:
  6785. case CK_DerivedToBase:
  6786. case CK_UncheckedDerivedToBase:
  6787. case CK_Dynamic:
  6788. case CK_ToUnion:
  6789. case CK_UserDefinedConversion:
  6790. case CK_ConstructorConversion:
  6791. case CK_IntegralToPointer:
  6792. case CK_PointerToIntegral:
  6793. case CK_VectorSplat:
  6794. case CK_IntegralCast:
  6795. case CK_CPointerToObjCPointerCast:
  6796. case CK_BlockPointerToObjCPointerCast:
  6797. case CK_AnyPointerToBlockPointerCast:
  6798. case CK_AddressSpaceConversion:
  6799. break;
  6800. case CK_ArrayToPointerDecay:
  6801. // Model array-to-pointer decay as taking the address of the array
  6802. // lvalue.
  6803. Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
  6804. return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
  6805. RK_ReferenceBinding, Visit,
  6806. EnableLifetimeWarnings);
  6807. default:
  6808. return;
  6809. }
  6810. Init = CE->getSubExpr();
  6811. }
  6812. } while (Old != Init);
  6813. // C++17 [dcl.init.list]p6:
  6814. // initializing an initializer_list object from the array extends the
  6815. // lifetime of the array exactly like binding a reference to a temporary.
  6816. if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
  6817. return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
  6818. RK_StdInitializerList, Visit,
  6819. EnableLifetimeWarnings);
  6820. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  6821. // We already visited the elements of this initializer list while
  6822. // performing the initialization. Don't visit them again unless we've
  6823. // changed the lifetime of the initialized entity.
  6824. if (!RevisitSubinits)
  6825. return;
  6826. if (ILE->isTransparent())
  6827. return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
  6828. RevisitSubinits,
  6829. EnableLifetimeWarnings);
  6830. if (ILE->getType()->isArrayType()) {
  6831. for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
  6832. visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
  6833. RevisitSubinits,
  6834. EnableLifetimeWarnings);
  6835. return;
  6836. }
  6837. if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
  6838. assert(RD->isAggregate() && "aggregate init on non-aggregate");
  6839. // If we lifetime-extend a braced initializer which is initializing an
  6840. // aggregate, and that aggregate contains reference members which are
  6841. // bound to temporaries, those temporaries are also lifetime-extended.
  6842. if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
  6843. ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
  6844. visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
  6845. RK_ReferenceBinding, Visit,
  6846. EnableLifetimeWarnings);
  6847. else {
  6848. unsigned Index = 0;
  6849. for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
  6850. visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
  6851. RevisitSubinits,
  6852. EnableLifetimeWarnings);
  6853. for (const auto *I : RD->fields()) {
  6854. if (Index >= ILE->getNumInits())
  6855. break;
  6856. if (I->isUnnamedBitfield())
  6857. continue;
  6858. Expr *SubInit = ILE->getInit(Index);
  6859. if (I->getType()->isReferenceType())
  6860. visitLocalsRetainedByReferenceBinding(Path, SubInit,
  6861. RK_ReferenceBinding, Visit,
  6862. EnableLifetimeWarnings);
  6863. else
  6864. // This might be either aggregate-initialization of a member or
  6865. // initialization of a std::initializer_list object. Regardless,
  6866. // we should recursively lifetime-extend that initializer.
  6867. visitLocalsRetainedByInitializer(Path, SubInit, Visit,
  6868. RevisitSubinits,
  6869. EnableLifetimeWarnings);
  6870. ++Index;
  6871. }
  6872. }
  6873. }
  6874. return;
  6875. }
  6876. // The lifetime of an init-capture is that of the closure object constructed
  6877. // by a lambda-expression.
  6878. if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
  6879. LambdaExpr::capture_iterator CapI = LE->capture_begin();
  6880. for (Expr *E : LE->capture_inits()) {
  6881. assert(CapI != LE->capture_end());
  6882. const LambdaCapture &Cap = *CapI++;
  6883. if (!E)
  6884. continue;
  6885. if (Cap.capturesVariable())
  6886. Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
  6887. if (E->isGLValue())
  6888. visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
  6889. Visit, EnableLifetimeWarnings);
  6890. else
  6891. visitLocalsRetainedByInitializer(Path, E, Visit, true,
  6892. EnableLifetimeWarnings);
  6893. if (Cap.capturesVariable())
  6894. Path.pop_back();
  6895. }
  6896. }
  6897. // Assume that a copy or move from a temporary references the same objects
  6898. // that the temporary does.
  6899. if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  6900. if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
  6901. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
  6902. Expr *Arg = MTE->getSubExpr();
  6903. Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
  6904. CCE->getConstructor()});
  6905. visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
  6906. /*EnableLifetimeWarnings*/false);
  6907. Path.pop_back();
  6908. }
  6909. }
  6910. }
  6911. if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
  6912. if (EnableLifetimeWarnings)
  6913. handleGslAnnotatedTypes(Path, Init, Visit);
  6914. return visitLifetimeBoundArguments(Path, Init, Visit);
  6915. }
  6916. switch (Init->getStmtClass()) {
  6917. case Stmt::UnaryOperatorClass: {
  6918. auto *UO = cast<UnaryOperator>(Init);
  6919. // If the initializer is the address of a local, we could have a lifetime
  6920. // problem.
  6921. if (UO->getOpcode() == UO_AddrOf) {
  6922. // If this is &rvalue, then it's ill-formed and we have already diagnosed
  6923. // it. Don't produce a redundant warning about the lifetime of the
  6924. // temporary.
  6925. if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
  6926. return;
  6927. Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
  6928. visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
  6929. RK_ReferenceBinding, Visit,
  6930. EnableLifetimeWarnings);
  6931. }
  6932. break;
  6933. }
  6934. case Stmt::BinaryOperatorClass: {
  6935. // Handle pointer arithmetic.
  6936. auto *BO = cast<BinaryOperator>(Init);
  6937. BinaryOperatorKind BOK = BO->getOpcode();
  6938. if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
  6939. break;
  6940. if (BO->getLHS()->getType()->isPointerType())
  6941. visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
  6942. EnableLifetimeWarnings);
  6943. else if (BO->getRHS()->getType()->isPointerType())
  6944. visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
  6945. EnableLifetimeWarnings);
  6946. break;
  6947. }
  6948. case Stmt::ConditionalOperatorClass:
  6949. case Stmt::BinaryConditionalOperatorClass: {
  6950. auto *C = cast<AbstractConditionalOperator>(Init);
  6951. // In C++, we can have a throw-expression operand, which has 'void' type
  6952. // and isn't interesting from a lifetime perspective.
  6953. if (!C->getTrueExpr()->getType()->isVoidType())
  6954. visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
  6955. EnableLifetimeWarnings);
  6956. if (!C->getFalseExpr()->getType()->isVoidType())
  6957. visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
  6958. EnableLifetimeWarnings);
  6959. break;
  6960. }
  6961. case Stmt::BlockExprClass:
  6962. if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
  6963. // This is a local block, whose lifetime is that of the function.
  6964. Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
  6965. }
  6966. break;
  6967. case Stmt::AddrLabelExprClass:
  6968. // We want to warn if the address of a label would escape the function.
  6969. Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
  6970. break;
  6971. default:
  6972. break;
  6973. }
  6974. }
  6975. /// Whether a path to an object supports lifetime extension.
  6976. enum PathLifetimeKind {
  6977. /// Lifetime-extend along this path.
  6978. Extend,
  6979. /// We should lifetime-extend, but we don't because (due to technical
  6980. /// limitations) we can't. This happens for default member initializers,
  6981. /// which we don't clone for every use, so we don't have a unique
  6982. /// MaterializeTemporaryExpr to update.
  6983. ShouldExtend,
  6984. /// Do not lifetime extend along this path.
  6985. NoExtend
  6986. };
  6987. /// Determine whether this is an indirect path to a temporary that we are
  6988. /// supposed to lifetime-extend along.
  6989. static PathLifetimeKind
  6990. shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
  6991. PathLifetimeKind Kind = PathLifetimeKind::Extend;
  6992. for (auto Elem : Path) {
  6993. if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
  6994. Kind = PathLifetimeKind::ShouldExtend;
  6995. else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
  6996. return PathLifetimeKind::NoExtend;
  6997. }
  6998. return Kind;
  6999. }
  7000. /// Find the range for the first interesting entry in the path at or after I.
  7001. static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
  7002. Expr *E) {
  7003. for (unsigned N = Path.size(); I != N; ++I) {
  7004. switch (Path[I].Kind) {
  7005. case IndirectLocalPathEntry::AddressOf:
  7006. case IndirectLocalPathEntry::LValToRVal:
  7007. case IndirectLocalPathEntry::LifetimeBoundCall:
  7008. case IndirectLocalPathEntry::TemporaryCopy:
  7009. case IndirectLocalPathEntry::GslReferenceInit:
  7010. case IndirectLocalPathEntry::GslPointerInit:
  7011. // These exist primarily to mark the path as not permitting or
  7012. // supporting lifetime extension.
  7013. break;
  7014. case IndirectLocalPathEntry::VarInit:
  7015. if (cast<VarDecl>(Path[I].D)->isImplicit())
  7016. return SourceRange();
  7017. [[fallthrough]];
  7018. case IndirectLocalPathEntry::DefaultInit:
  7019. return Path[I].E->getSourceRange();
  7020. case IndirectLocalPathEntry::LambdaCaptureInit:
  7021. if (!Path[I].Capture->capturesVariable())
  7022. continue;
  7023. return Path[I].E->getSourceRange();
  7024. }
  7025. }
  7026. return E->getSourceRange();
  7027. }
  7028. static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
  7029. for (const auto &It : llvm::reverse(Path)) {
  7030. if (It.Kind == IndirectLocalPathEntry::VarInit)
  7031. continue;
  7032. if (It.Kind == IndirectLocalPathEntry::AddressOf)
  7033. continue;
  7034. if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
  7035. continue;
  7036. return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
  7037. It.Kind == IndirectLocalPathEntry::GslReferenceInit;
  7038. }
  7039. return false;
  7040. }
  7041. void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
  7042. Expr *Init) {
  7043. LifetimeResult LR = getEntityLifetime(&Entity);
  7044. LifetimeKind LK = LR.getInt();
  7045. const InitializedEntity *ExtendingEntity = LR.getPointer();
  7046. // If this entity doesn't have an interesting lifetime, don't bother looking
  7047. // for temporaries within its initializer.
  7048. if (LK == LK_FullExpression)
  7049. return;
  7050. auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
  7051. ReferenceKind RK) -> bool {
  7052. SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
  7053. SourceLocation DiagLoc = DiagRange.getBegin();
  7054. auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
  7055. bool IsGslPtrInitWithGslTempOwner = false;
  7056. bool IsLocalGslOwner = false;
  7057. if (pathOnlyInitializesGslPointer(Path)) {
  7058. if (isa<DeclRefExpr>(L)) {
  7059. // We do not want to follow the references when returning a pointer originating
  7060. // from a local owner to avoid the following false positive:
  7061. // int &p = *localUniquePtr;
  7062. // someContainer.add(std::move(localUniquePtr));
  7063. // return p;
  7064. IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
  7065. if (pathContainsInit(Path) || !IsLocalGslOwner)
  7066. return false;
  7067. } else {
  7068. IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
  7069. isRecordWithAttr<OwnerAttr>(MTE->getType());
  7070. // Skipping a chain of initializing gsl::Pointer annotated objects.
  7071. // We are looking only for the final source to find out if it was
  7072. // a local or temporary owner or the address of a local variable/param.
  7073. if (!IsGslPtrInitWithGslTempOwner)
  7074. return true;
  7075. }
  7076. }
  7077. switch (LK) {
  7078. case LK_FullExpression:
  7079. llvm_unreachable("already handled this");
  7080. case LK_Extended: {
  7081. if (!MTE) {
  7082. // The initialized entity has lifetime beyond the full-expression,
  7083. // and the local entity does too, so don't warn.
  7084. //
  7085. // FIXME: We should consider warning if a static / thread storage
  7086. // duration variable retains an automatic storage duration local.
  7087. return false;
  7088. }
  7089. if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
  7090. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
  7091. return false;
  7092. }
  7093. switch (shouldLifetimeExtendThroughPath(Path)) {
  7094. case PathLifetimeKind::Extend:
  7095. // Update the storage duration of the materialized temporary.
  7096. // FIXME: Rebuild the expression instead of mutating it.
  7097. MTE->setExtendingDecl(ExtendingEntity->getDecl(),
  7098. ExtendingEntity->allocateManglingNumber());
  7099. // Also visit the temporaries lifetime-extended by this initializer.
  7100. return true;
  7101. case PathLifetimeKind::ShouldExtend:
  7102. // We're supposed to lifetime-extend the temporary along this path (per
  7103. // the resolution of DR1815), but we don't support that yet.
  7104. //
  7105. // FIXME: Properly handle this situation. Perhaps the easiest approach
  7106. // would be to clone the initializer expression on each use that would
  7107. // lifetime extend its temporaries.
  7108. Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
  7109. << RK << DiagRange;
  7110. break;
  7111. case PathLifetimeKind::NoExtend:
  7112. // If the path goes through the initialization of a variable or field,
  7113. // it can't possibly reach a temporary created in this full-expression.
  7114. // We will have already diagnosed any problems with the initializer.
  7115. if (pathContainsInit(Path))
  7116. return false;
  7117. Diag(DiagLoc, diag::warn_dangling_variable)
  7118. << RK << !Entity.getParent()
  7119. << ExtendingEntity->getDecl()->isImplicit()
  7120. << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
  7121. break;
  7122. }
  7123. break;
  7124. }
  7125. case LK_MemInitializer: {
  7126. if (isa<MaterializeTemporaryExpr>(L)) {
  7127. // Under C++ DR1696, if a mem-initializer (or a default member
  7128. // initializer used by the absence of one) would lifetime-extend a
  7129. // temporary, the program is ill-formed.
  7130. if (auto *ExtendingDecl =
  7131. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  7132. if (IsGslPtrInitWithGslTempOwner) {
  7133. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
  7134. << ExtendingDecl << DiagRange;
  7135. Diag(ExtendingDecl->getLocation(),
  7136. diag::note_ref_or_ptr_member_declared_here)
  7137. << true;
  7138. return false;
  7139. }
  7140. bool IsSubobjectMember = ExtendingEntity != &Entity;
  7141. Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
  7142. PathLifetimeKind::NoExtend
  7143. ? diag::err_dangling_member
  7144. : diag::warn_dangling_member)
  7145. << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
  7146. // Don't bother adding a note pointing to the field if we're inside
  7147. // its default member initializer; our primary diagnostic points to
  7148. // the same place in that case.
  7149. if (Path.empty() ||
  7150. Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
  7151. Diag(ExtendingDecl->getLocation(),
  7152. diag::note_lifetime_extending_member_declared_here)
  7153. << RK << IsSubobjectMember;
  7154. }
  7155. } else {
  7156. // We have a mem-initializer but no particular field within it; this
  7157. // is either a base class or a delegating initializer directly
  7158. // initializing the base-class from something that doesn't live long
  7159. // enough.
  7160. //
  7161. // FIXME: Warn on this.
  7162. return false;
  7163. }
  7164. } else {
  7165. // Paths via a default initializer can only occur during error recovery
  7166. // (there's no other way that a default initializer can refer to a
  7167. // local). Don't produce a bogus warning on those cases.
  7168. if (pathContainsInit(Path))
  7169. return false;
  7170. // Suppress false positives for code like the one below:
  7171. // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
  7172. if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
  7173. return false;
  7174. auto *DRE = dyn_cast<DeclRefExpr>(L);
  7175. auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
  7176. if (!VD) {
  7177. // A member was initialized to a local block.
  7178. // FIXME: Warn on this.
  7179. return false;
  7180. }
  7181. if (auto *Member =
  7182. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  7183. bool IsPointer = !Member->getType()->isReferenceType();
  7184. Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  7185. : diag::warn_bind_ref_member_to_parameter)
  7186. << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
  7187. Diag(Member->getLocation(),
  7188. diag::note_ref_or_ptr_member_declared_here)
  7189. << (unsigned)IsPointer;
  7190. }
  7191. }
  7192. break;
  7193. }
  7194. case LK_New:
  7195. if (isa<MaterializeTemporaryExpr>(L)) {
  7196. if (IsGslPtrInitWithGslTempOwner)
  7197. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
  7198. else
  7199. Diag(DiagLoc, RK == RK_ReferenceBinding
  7200. ? diag::warn_new_dangling_reference
  7201. : diag::warn_new_dangling_initializer_list)
  7202. << !Entity.getParent() << DiagRange;
  7203. } else {
  7204. // We can't determine if the allocation outlives the local declaration.
  7205. return false;
  7206. }
  7207. break;
  7208. case LK_Return:
  7209. case LK_StmtExprResult:
  7210. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  7211. // We can't determine if the local variable outlives the statement
  7212. // expression.
  7213. if (LK == LK_StmtExprResult)
  7214. return false;
  7215. Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
  7216. << Entity.getType()->isReferenceType() << DRE->getDecl()
  7217. << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
  7218. } else if (isa<BlockExpr>(L)) {
  7219. Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
  7220. } else if (isa<AddrLabelExpr>(L)) {
  7221. // Don't warn when returning a label from a statement expression.
  7222. // Leaving the scope doesn't end its lifetime.
  7223. if (LK == LK_StmtExprResult)
  7224. return false;
  7225. Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
  7226. } else {
  7227. Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
  7228. << Entity.getType()->isReferenceType() << DiagRange;
  7229. }
  7230. break;
  7231. }
  7232. for (unsigned I = 0; I != Path.size(); ++I) {
  7233. auto Elem = Path[I];
  7234. switch (Elem.Kind) {
  7235. case IndirectLocalPathEntry::AddressOf:
  7236. case IndirectLocalPathEntry::LValToRVal:
  7237. // These exist primarily to mark the path as not permitting or
  7238. // supporting lifetime extension.
  7239. break;
  7240. case IndirectLocalPathEntry::LifetimeBoundCall:
  7241. case IndirectLocalPathEntry::TemporaryCopy:
  7242. case IndirectLocalPathEntry::GslPointerInit:
  7243. case IndirectLocalPathEntry::GslReferenceInit:
  7244. // FIXME: Consider adding a note for these.
  7245. break;
  7246. case IndirectLocalPathEntry::DefaultInit: {
  7247. auto *FD = cast<FieldDecl>(Elem.D);
  7248. Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
  7249. << FD << nextPathEntryRange(Path, I + 1, L);
  7250. break;
  7251. }
  7252. case IndirectLocalPathEntry::VarInit: {
  7253. const VarDecl *VD = cast<VarDecl>(Elem.D);
  7254. Diag(VD->getLocation(), diag::note_local_var_initializer)
  7255. << VD->getType()->isReferenceType()
  7256. << VD->isImplicit() << VD->getDeclName()
  7257. << nextPathEntryRange(Path, I + 1, L);
  7258. break;
  7259. }
  7260. case IndirectLocalPathEntry::LambdaCaptureInit:
  7261. if (!Elem.Capture->capturesVariable())
  7262. break;
  7263. // FIXME: We can't easily tell apart an init-capture from a nested
  7264. // capture of an init-capture.
  7265. const ValueDecl *VD = Elem.Capture->getCapturedVar();
  7266. Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
  7267. << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
  7268. << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
  7269. << nextPathEntryRange(Path, I + 1, L);
  7270. break;
  7271. }
  7272. }
  7273. // We didn't lifetime-extend, so don't go any further; we don't need more
  7274. // warnings or errors on inner temporaries within this one's initializer.
  7275. return false;
  7276. };
  7277. bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
  7278. diag::warn_dangling_lifetime_pointer, SourceLocation());
  7279. llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
  7280. if (Init->isGLValue())
  7281. visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
  7282. TemporaryVisitor,
  7283. EnableLifetimeWarnings);
  7284. else
  7285. visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
  7286. EnableLifetimeWarnings);
  7287. }
  7288. static void DiagnoseNarrowingInInitList(Sema &S,
  7289. const ImplicitConversionSequence &ICS,
  7290. QualType PreNarrowingType,
  7291. QualType EntityType,
  7292. const Expr *PostInit);
  7293. /// Provide warnings when std::move is used on construction.
  7294. static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
  7295. bool IsReturnStmt) {
  7296. if (!InitExpr)
  7297. return;
  7298. if (S.inTemplateInstantiation())
  7299. return;
  7300. QualType DestType = InitExpr->getType();
  7301. if (!DestType->isRecordType())
  7302. return;
  7303. unsigned DiagID = 0;
  7304. if (IsReturnStmt) {
  7305. const CXXConstructExpr *CCE =
  7306. dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
  7307. if (!CCE || CCE->getNumArgs() != 1)
  7308. return;
  7309. if (!CCE->getConstructor()->isCopyOrMoveConstructor())
  7310. return;
  7311. InitExpr = CCE->getArg(0)->IgnoreImpCasts();
  7312. }
  7313. // Find the std::move call and get the argument.
  7314. const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
  7315. if (!CE || !CE->isCallToStdMove())
  7316. return;
  7317. const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
  7318. if (IsReturnStmt) {
  7319. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
  7320. if (!DRE || DRE->refersToEnclosingVariableOrCapture())
  7321. return;
  7322. const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
  7323. if (!VD || !VD->hasLocalStorage())
  7324. return;
  7325. // __block variables are not moved implicitly.
  7326. if (VD->hasAttr<BlocksAttr>())
  7327. return;
  7328. QualType SourceType = VD->getType();
  7329. if (!SourceType->isRecordType())
  7330. return;
  7331. if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
  7332. return;
  7333. }
  7334. // If we're returning a function parameter, copy elision
  7335. // is not possible.
  7336. if (isa<ParmVarDecl>(VD))
  7337. DiagID = diag::warn_redundant_move_on_return;
  7338. else
  7339. DiagID = diag::warn_pessimizing_move_on_return;
  7340. } else {
  7341. DiagID = diag::warn_pessimizing_move_on_initialization;
  7342. const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
  7343. if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
  7344. return;
  7345. }
  7346. S.Diag(CE->getBeginLoc(), DiagID);
  7347. // Get all the locations for a fix-it. Don't emit the fix-it if any location
  7348. // is within a macro.
  7349. SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
  7350. if (CallBegin.isMacroID())
  7351. return;
  7352. SourceLocation RParen = CE->getRParenLoc();
  7353. if (RParen.isMacroID())
  7354. return;
  7355. SourceLocation LParen;
  7356. SourceLocation ArgLoc = Arg->getBeginLoc();
  7357. // Special testing for the argument location. Since the fix-it needs the
  7358. // location right before the argument, the argument location can be in a
  7359. // macro only if it is at the beginning of the macro.
  7360. while (ArgLoc.isMacroID() &&
  7361. S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
  7362. ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
  7363. }
  7364. if (LParen.isMacroID())
  7365. return;
  7366. LParen = ArgLoc.getLocWithOffset(-1);
  7367. S.Diag(CE->getBeginLoc(), diag::note_remove_move)
  7368. << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
  7369. << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
  7370. }
  7371. static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
  7372. // Check to see if we are dereferencing a null pointer. If so, this is
  7373. // undefined behavior, so warn about it. This only handles the pattern
  7374. // "*null", which is a very syntactic check.
  7375. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  7376. if (UO->getOpcode() == UO_Deref &&
  7377. UO->getSubExpr()->IgnoreParenCasts()->
  7378. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
  7379. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  7380. S.PDiag(diag::warn_binding_null_to_reference)
  7381. << UO->getSubExpr()->getSourceRange());
  7382. }
  7383. }
  7384. MaterializeTemporaryExpr *
  7385. Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
  7386. bool BoundToLvalueReference) {
  7387. auto MTE = new (Context)
  7388. MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
  7389. // Order an ExprWithCleanups for lifetime marks.
  7390. //
  7391. // TODO: It'll be good to have a single place to check the access of the
  7392. // destructor and generate ExprWithCleanups for various uses. Currently these
  7393. // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
  7394. // but there may be a chance to merge them.
  7395. Cleanup.setExprNeedsCleanups(false);
  7396. return MTE;
  7397. }
  7398. ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
  7399. // In C++98, we don't want to implicitly create an xvalue.
  7400. // FIXME: This means that AST consumers need to deal with "prvalues" that
  7401. // denote materialized temporaries. Maybe we should add another ValueKind
  7402. // for "xvalue pretending to be a prvalue" for C++98 support.
  7403. if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
  7404. return E;
  7405. // C++1z [conv.rval]/1: T shall be a complete type.
  7406. // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
  7407. // If so, we should check for a non-abstract class type here too.
  7408. QualType T = E->getType();
  7409. if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
  7410. return ExprError();
  7411. return CreateMaterializeTemporaryExpr(E->getType(), E, false);
  7412. }
  7413. ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
  7414. ExprValueKind VK,
  7415. CheckedConversionKind CCK) {
  7416. CastKind CK = CK_NoOp;
  7417. if (VK == VK_PRValue) {
  7418. auto PointeeTy = Ty->getPointeeType();
  7419. auto ExprPointeeTy = E->getType()->getPointeeType();
  7420. if (!PointeeTy.isNull() &&
  7421. PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
  7422. CK = CK_AddressSpaceConversion;
  7423. } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
  7424. CK = CK_AddressSpaceConversion;
  7425. }
  7426. return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
  7427. }
  7428. ExprResult InitializationSequence::Perform(Sema &S,
  7429. const InitializedEntity &Entity,
  7430. const InitializationKind &Kind,
  7431. MultiExprArg Args,
  7432. QualType *ResultType) {
  7433. if (Failed()) {
  7434. Diagnose(S, Entity, Kind, Args);
  7435. return ExprError();
  7436. }
  7437. if (!ZeroInitializationFixit.empty()) {
  7438. const Decl *D = Entity.getDecl();
  7439. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  7440. QualType DestType = Entity.getType();
  7441. // The initialization would have succeeded with this fixit. Since the fixit
  7442. // is on the error, we need to build a valid AST in this case, so this isn't
  7443. // handled in the Failed() branch above.
  7444. if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
  7445. // Use a more useful diagnostic for constexpr variables.
  7446. S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
  7447. << VD
  7448. << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
  7449. ZeroInitializationFixit);
  7450. } else {
  7451. unsigned DiagID = diag::err_default_init_const;
  7452. if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
  7453. DiagID = diag::ext_default_init_const;
  7454. S.Diag(Kind.getLocation(), DiagID)
  7455. << DestType << (bool)DestType->getAs<RecordType>()
  7456. << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
  7457. ZeroInitializationFixit);
  7458. }
  7459. }
  7460. if (getKind() == DependentSequence) {
  7461. // If the declaration is a non-dependent, incomplete array type
  7462. // that has an initializer, then its type will be completed once
  7463. // the initializer is instantiated.
  7464. if (ResultType && !Entity.getType()->isDependentType() &&
  7465. Args.size() == 1) {
  7466. QualType DeclType = Entity.getType();
  7467. if (const IncompleteArrayType *ArrayT
  7468. = S.Context.getAsIncompleteArrayType(DeclType)) {
  7469. // FIXME: We don't currently have the ability to accurately
  7470. // compute the length of an initializer list without
  7471. // performing full type-checking of the initializer list
  7472. // (since we have to determine where braces are implicitly
  7473. // introduced and such). So, we fall back to making the array
  7474. // type a dependently-sized array type with no specified
  7475. // bound.
  7476. if (isa<InitListExpr>((Expr *)Args[0])) {
  7477. SourceRange Brackets;
  7478. // Scavange the location of the brackets from the entity, if we can.
  7479. if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
  7480. if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
  7481. TypeLoc TL = TInfo->getTypeLoc();
  7482. if (IncompleteArrayTypeLoc ArrayLoc =
  7483. TL.getAs<IncompleteArrayTypeLoc>())
  7484. Brackets = ArrayLoc.getBracketsRange();
  7485. }
  7486. }
  7487. *ResultType
  7488. = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
  7489. /*NumElts=*/nullptr,
  7490. ArrayT->getSizeModifier(),
  7491. ArrayT->getIndexTypeCVRQualifiers(),
  7492. Brackets);
  7493. }
  7494. }
  7495. }
  7496. if (Kind.getKind() == InitializationKind::IK_Direct &&
  7497. !Kind.isExplicitCast()) {
  7498. // Rebuild the ParenListExpr.
  7499. SourceRange ParenRange = Kind.getParenOrBraceRange();
  7500. return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
  7501. Args);
  7502. }
  7503. assert(Kind.getKind() == InitializationKind::IK_Copy ||
  7504. Kind.isExplicitCast() ||
  7505. Kind.getKind() == InitializationKind::IK_DirectList);
  7506. return ExprResult(Args[0]);
  7507. }
  7508. // No steps means no initialization.
  7509. if (Steps.empty())
  7510. return ExprResult((Expr *)nullptr);
  7511. if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
  7512. Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  7513. !Entity.isParamOrTemplateParamKind()) {
  7514. // Produce a C++98 compatibility warning if we are initializing a reference
  7515. // from an initializer list. For parameters, we produce a better warning
  7516. // elsewhere.
  7517. Expr *Init = Args[0];
  7518. S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
  7519. << Init->getSourceRange();
  7520. }
  7521. // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
  7522. QualType ETy = Entity.getType();
  7523. bool HasGlobalAS = ETy.hasAddressSpace() &&
  7524. ETy.getAddressSpace() == LangAS::opencl_global;
  7525. if (S.getLangOpts().OpenCLVersion >= 200 &&
  7526. ETy->isAtomicType() && !HasGlobalAS &&
  7527. Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
  7528. S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
  7529. << 1
  7530. << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
  7531. return ExprError();
  7532. }
  7533. QualType DestType = Entity.getType().getNonReferenceType();
  7534. // FIXME: Ugly hack around the fact that Entity.getType() is not
  7535. // the same as Entity.getDecl()->getType() in cases involving type merging,
  7536. // and we want latter when it makes sense.
  7537. if (ResultType)
  7538. *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
  7539. Entity.getType();
  7540. ExprResult CurInit((Expr *)nullptr);
  7541. SmallVector<Expr*, 4> ArrayLoopCommonExprs;
  7542. // HLSL allows vector initialization to function like list initialization, but
  7543. // use the syntax of a C++-like constructor.
  7544. bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
  7545. isa<InitListExpr>(Args[0]);
  7546. (void)IsHLSLVectorInit;
  7547. // For initialization steps that start with a single initializer,
  7548. // grab the only argument out the Args and place it into the "current"
  7549. // initializer.
  7550. switch (Steps.front().Kind) {
  7551. case SK_ResolveAddressOfOverloadedFunction:
  7552. case SK_CastDerivedToBasePRValue:
  7553. case SK_CastDerivedToBaseXValue:
  7554. case SK_CastDerivedToBaseLValue:
  7555. case SK_BindReference:
  7556. case SK_BindReferenceToTemporary:
  7557. case SK_FinalCopy:
  7558. case SK_ExtraneousCopyToTemporary:
  7559. case SK_UserConversion:
  7560. case SK_QualificationConversionLValue:
  7561. case SK_QualificationConversionXValue:
  7562. case SK_QualificationConversionPRValue:
  7563. case SK_FunctionReferenceConversion:
  7564. case SK_AtomicConversion:
  7565. case SK_ConversionSequence:
  7566. case SK_ConversionSequenceNoNarrowing:
  7567. case SK_ListInitialization:
  7568. case SK_UnwrapInitList:
  7569. case SK_RewrapInitList:
  7570. case SK_CAssignment:
  7571. case SK_StringInit:
  7572. case SK_ObjCObjectConversion:
  7573. case SK_ArrayLoopIndex:
  7574. case SK_ArrayLoopInit:
  7575. case SK_ArrayInit:
  7576. case SK_GNUArrayInit:
  7577. case SK_ParenthesizedArrayInit:
  7578. case SK_PassByIndirectCopyRestore:
  7579. case SK_PassByIndirectRestore:
  7580. case SK_ProduceObjCObject:
  7581. case SK_StdInitializerList:
  7582. case SK_OCLSamplerInit:
  7583. case SK_OCLZeroOpaqueType: {
  7584. assert(Args.size() == 1 || IsHLSLVectorInit);
  7585. CurInit = Args[0];
  7586. if (!CurInit.get()) return ExprError();
  7587. break;
  7588. }
  7589. case SK_ConstructorInitialization:
  7590. case SK_ConstructorInitializationFromList:
  7591. case SK_StdInitializerListConstructorCall:
  7592. case SK_ZeroInitialization:
  7593. case SK_ParenthesizedListInit:
  7594. break;
  7595. }
  7596. // Promote from an unevaluated context to an unevaluated list context in
  7597. // C++11 list-initialization; we need to instantiate entities usable in
  7598. // constant expressions here in order to perform narrowing checks =(
  7599. EnterExpressionEvaluationContext Evaluated(
  7600. S, EnterExpressionEvaluationContext::InitList,
  7601. CurInit.get() && isa<InitListExpr>(CurInit.get()));
  7602. // C++ [class.abstract]p2:
  7603. // no objects of an abstract class can be created except as subobjects
  7604. // of a class derived from it
  7605. auto checkAbstractType = [&](QualType T) -> bool {
  7606. if (Entity.getKind() == InitializedEntity::EK_Base ||
  7607. Entity.getKind() == InitializedEntity::EK_Delegating)
  7608. return false;
  7609. return S.RequireNonAbstractType(Kind.getLocation(), T,
  7610. diag::err_allocation_of_abstract_type);
  7611. };
  7612. // Walk through the computed steps for the initialization sequence,
  7613. // performing the specified conversions along the way.
  7614. bool ConstructorInitRequiresZeroInit = false;
  7615. for (step_iterator Step = step_begin(), StepEnd = step_end();
  7616. Step != StepEnd; ++Step) {
  7617. if (CurInit.isInvalid())
  7618. return ExprError();
  7619. QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
  7620. switch (Step->Kind) {
  7621. case SK_ResolveAddressOfOverloadedFunction:
  7622. // Overload resolution determined which function invoke; update the
  7623. // initializer to reflect that choice.
  7624. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
  7625. if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
  7626. return ExprError();
  7627. CurInit = S.FixOverloadedFunctionReference(CurInit,
  7628. Step->Function.FoundDecl,
  7629. Step->Function.Function);
  7630. // We might get back another placeholder expression if we resolved to a
  7631. // builtin.
  7632. if (!CurInit.isInvalid())
  7633. CurInit = S.CheckPlaceholderExpr(CurInit.get());
  7634. break;
  7635. case SK_CastDerivedToBasePRValue:
  7636. case SK_CastDerivedToBaseXValue:
  7637. case SK_CastDerivedToBaseLValue: {
  7638. // We have a derived-to-base cast that produces either an rvalue or an
  7639. // lvalue. Perform that cast.
  7640. CXXCastPath BasePath;
  7641. // Casts to inaccessible base classes are allowed with C-style casts.
  7642. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
  7643. if (S.CheckDerivedToBaseConversion(
  7644. SourceType, Step->Type, CurInit.get()->getBeginLoc(),
  7645. CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
  7646. return ExprError();
  7647. ExprValueKind VK =
  7648. Step->Kind == SK_CastDerivedToBaseLValue
  7649. ? VK_LValue
  7650. : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
  7651. : VK_PRValue);
  7652. CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
  7653. CK_DerivedToBase, CurInit.get(),
  7654. &BasePath, VK, FPOptionsOverride());
  7655. break;
  7656. }
  7657. case SK_BindReference:
  7658. // Reference binding does not have any corresponding ASTs.
  7659. // Check exception specifications
  7660. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  7661. return ExprError();
  7662. // We don't check for e.g. function pointers here, since address
  7663. // availability checks should only occur when the function first decays
  7664. // into a pointer or reference.
  7665. if (CurInit.get()->getType()->isFunctionProtoType()) {
  7666. if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
  7667. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  7668. if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  7669. DRE->getBeginLoc()))
  7670. return ExprError();
  7671. }
  7672. }
  7673. }
  7674. CheckForNullPointerDereference(S, CurInit.get());
  7675. break;
  7676. case SK_BindReferenceToTemporary: {
  7677. // Make sure the "temporary" is actually an rvalue.
  7678. assert(CurInit.get()->isPRValue() && "not a temporary");
  7679. // Check exception specifications
  7680. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  7681. return ExprError();
  7682. QualType MTETy = Step->Type;
  7683. // When this is an incomplete array type (such as when this is
  7684. // initializing an array of unknown bounds from an init list), use THAT
  7685. // type instead so that we propagate the array bounds.
  7686. if (MTETy->isIncompleteArrayType() &&
  7687. !CurInit.get()->getType()->isIncompleteArrayType() &&
  7688. S.Context.hasSameType(
  7689. MTETy->getPointeeOrArrayElementType(),
  7690. CurInit.get()->getType()->getPointeeOrArrayElementType()))
  7691. MTETy = CurInit.get()->getType();
  7692. // Materialize the temporary into memory.
  7693. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  7694. MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
  7695. CurInit = MTE;
  7696. // If we're extending this temporary to automatic storage duration -- we
  7697. // need to register its cleanup during the full-expression's cleanups.
  7698. if (MTE->getStorageDuration() == SD_Automatic &&
  7699. MTE->getType().isDestructedType())
  7700. S.Cleanup.setExprNeedsCleanups(true);
  7701. break;
  7702. }
  7703. case SK_FinalCopy:
  7704. if (checkAbstractType(Step->Type))
  7705. return ExprError();
  7706. // If the overall initialization is initializing a temporary, we already
  7707. // bound our argument if it was necessary to do so. If not (if we're
  7708. // ultimately initializing a non-temporary), our argument needs to be
  7709. // bound since it's initializing a function parameter.
  7710. // FIXME: This is a mess. Rationalize temporary destruction.
  7711. if (!shouldBindAsTemporary(Entity))
  7712. CurInit = S.MaybeBindToTemporary(CurInit.get());
  7713. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  7714. /*IsExtraneousCopy=*/false);
  7715. break;
  7716. case SK_ExtraneousCopyToTemporary:
  7717. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  7718. /*IsExtraneousCopy=*/true);
  7719. break;
  7720. case SK_UserConversion: {
  7721. // We have a user-defined conversion that invokes either a constructor
  7722. // or a conversion function.
  7723. CastKind CastKind;
  7724. FunctionDecl *Fn = Step->Function.Function;
  7725. DeclAccessPair FoundFn = Step->Function.FoundDecl;
  7726. bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
  7727. bool CreatedObject = false;
  7728. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7729. // Build a call to the selected constructor.
  7730. SmallVector<Expr*, 8> ConstructorArgs;
  7731. SourceLocation Loc = CurInit.get()->getBeginLoc();
  7732. // Determine the arguments required to actually perform the constructor
  7733. // call.
  7734. Expr *Arg = CurInit.get();
  7735. if (S.CompleteConstructorCall(Constructor, Step->Type,
  7736. MultiExprArg(&Arg, 1), Loc,
  7737. ConstructorArgs))
  7738. return ExprError();
  7739. // Build an expression that constructs a temporary.
  7740. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
  7741. FoundFn, Constructor,
  7742. ConstructorArgs,
  7743. HadMultipleCandidates,
  7744. /*ListInit*/ false,
  7745. /*StdInitListInit*/ false,
  7746. /*ZeroInit*/ false,
  7747. CXXConstructExpr::CK_Complete,
  7748. SourceRange());
  7749. if (CurInit.isInvalid())
  7750. return ExprError();
  7751. S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
  7752. Entity);
  7753. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  7754. return ExprError();
  7755. CastKind = CK_ConstructorConversion;
  7756. CreatedObject = true;
  7757. } else {
  7758. // Build a call to the conversion function.
  7759. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
  7760. S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
  7761. FoundFn);
  7762. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  7763. return ExprError();
  7764. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
  7765. HadMultipleCandidates);
  7766. if (CurInit.isInvalid())
  7767. return ExprError();
  7768. CastKind = CK_UserDefinedConversion;
  7769. CreatedObject = Conversion->getReturnType()->isRecordType();
  7770. }
  7771. if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
  7772. return ExprError();
  7773. CurInit = ImplicitCastExpr::Create(
  7774. S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
  7775. CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
  7776. if (shouldBindAsTemporary(Entity))
  7777. // The overall entity is temporary, so this expression should be
  7778. // destroyed at the end of its full-expression.
  7779. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  7780. else if (CreatedObject && shouldDestroyEntity(Entity)) {
  7781. // The object outlasts the full-expression, but we need to prepare for
  7782. // a destructor being run on it.
  7783. // FIXME: It makes no sense to do this here. This should happen
  7784. // regardless of how we initialized the entity.
  7785. QualType T = CurInit.get()->getType();
  7786. if (const RecordType *Record = T->getAs<RecordType>()) {
  7787. CXXDestructorDecl *Destructor
  7788. = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
  7789. S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
  7790. S.PDiag(diag::err_access_dtor_temp) << T);
  7791. S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
  7792. if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
  7793. return ExprError();
  7794. }
  7795. }
  7796. break;
  7797. }
  7798. case SK_QualificationConversionLValue:
  7799. case SK_QualificationConversionXValue:
  7800. case SK_QualificationConversionPRValue: {
  7801. // Perform a qualification conversion; these can never go wrong.
  7802. ExprValueKind VK =
  7803. Step->Kind == SK_QualificationConversionLValue
  7804. ? VK_LValue
  7805. : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
  7806. : VK_PRValue);
  7807. CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
  7808. break;
  7809. }
  7810. case SK_FunctionReferenceConversion:
  7811. assert(CurInit.get()->isLValue() &&
  7812. "function reference should be lvalue");
  7813. CurInit =
  7814. S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
  7815. break;
  7816. case SK_AtomicConversion: {
  7817. assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
  7818. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7819. CK_NonAtomicToAtomic, VK_PRValue);
  7820. break;
  7821. }
  7822. case SK_ConversionSequence:
  7823. case SK_ConversionSequenceNoNarrowing: {
  7824. if (const auto *FromPtrType =
  7825. CurInit.get()->getType()->getAs<PointerType>()) {
  7826. if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
  7827. if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7828. !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7829. // Do not check static casts here because they are checked earlier
  7830. // in Sema::ActOnCXXNamedCast()
  7831. if (!Kind.isStaticCast()) {
  7832. S.Diag(CurInit.get()->getExprLoc(),
  7833. diag::warn_noderef_to_dereferenceable_pointer)
  7834. << CurInit.get()->getSourceRange();
  7835. }
  7836. }
  7837. }
  7838. }
  7839. Sema::CheckedConversionKind CCK
  7840. = Kind.isCStyleCast()? Sema::CCK_CStyleCast
  7841. : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
  7842. : Kind.isExplicitCast()? Sema::CCK_OtherCast
  7843. : Sema::CCK_ImplicitConversion;
  7844. ExprResult CurInitExprRes =
  7845. S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
  7846. getAssignmentAction(Entity), CCK);
  7847. if (CurInitExprRes.isInvalid())
  7848. return ExprError();
  7849. S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
  7850. CurInit = CurInitExprRes;
  7851. if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
  7852. S.getLangOpts().CPlusPlus)
  7853. DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
  7854. CurInit.get());
  7855. break;
  7856. }
  7857. case SK_ListInitialization: {
  7858. if (checkAbstractType(Step->Type))
  7859. return ExprError();
  7860. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  7861. // If we're not initializing the top-level entity, we need to create an
  7862. // InitializeTemporary entity for our target type.
  7863. QualType Ty = Step->Type;
  7864. bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
  7865. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
  7866. InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
  7867. InitListChecker PerformInitList(S, InitEntity,
  7868. InitList, Ty, /*VerifyOnly=*/false,
  7869. /*TreatUnavailableAsInvalid=*/false);
  7870. if (PerformInitList.HadError())
  7871. return ExprError();
  7872. // Hack: We must update *ResultType if available in order to set the
  7873. // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  7874. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  7875. if (ResultType &&
  7876. ResultType->getNonReferenceType()->isIncompleteArrayType()) {
  7877. if ((*ResultType)->isRValueReferenceType())
  7878. Ty = S.Context.getRValueReferenceType(Ty);
  7879. else if ((*ResultType)->isLValueReferenceType())
  7880. Ty = S.Context.getLValueReferenceType(Ty,
  7881. (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
  7882. *ResultType = Ty;
  7883. }
  7884. InitListExpr *StructuredInitList =
  7885. PerformInitList.getFullyStructuredList();
  7886. CurInit.get();
  7887. CurInit = shouldBindAsTemporary(InitEntity)
  7888. ? S.MaybeBindToTemporary(StructuredInitList)
  7889. : StructuredInitList;
  7890. break;
  7891. }
  7892. case SK_ConstructorInitializationFromList: {
  7893. if (checkAbstractType(Step->Type))
  7894. return ExprError();
  7895. // When an initializer list is passed for a parameter of type "reference
  7896. // to object", we don't get an EK_Temporary entity, but instead an
  7897. // EK_Parameter entity with reference type.
  7898. // FIXME: This is a hack. What we really should do is create a user
  7899. // conversion step for this case, but this makes it considerably more
  7900. // complicated. For now, this will do.
  7901. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  7902. Entity.getType().getNonReferenceType());
  7903. bool UseTemporary = Entity.getType()->isReferenceType();
  7904. assert(Args.size() == 1 && "expected a single argument for list init");
  7905. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  7906. S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
  7907. << InitList->getSourceRange();
  7908. MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
  7909. CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
  7910. Entity,
  7911. Kind, Arg, *Step,
  7912. ConstructorInitRequiresZeroInit,
  7913. /*IsListInitialization*/true,
  7914. /*IsStdInitListInit*/false,
  7915. InitList->getLBraceLoc(),
  7916. InitList->getRBraceLoc());
  7917. break;
  7918. }
  7919. case SK_UnwrapInitList:
  7920. CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
  7921. break;
  7922. case SK_RewrapInitList: {
  7923. Expr *E = CurInit.get();
  7924. InitListExpr *Syntactic = Step->WrappingSyntacticList;
  7925. InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
  7926. Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
  7927. ILE->setSyntacticForm(Syntactic);
  7928. ILE->setType(E->getType());
  7929. ILE->setValueKind(E->getValueKind());
  7930. CurInit = ILE;
  7931. break;
  7932. }
  7933. case SK_ConstructorInitialization:
  7934. case SK_StdInitializerListConstructorCall: {
  7935. if (checkAbstractType(Step->Type))
  7936. return ExprError();
  7937. // When an initializer list is passed for a parameter of type "reference
  7938. // to object", we don't get an EK_Temporary entity, but instead an
  7939. // EK_Parameter entity with reference type.
  7940. // FIXME: This is a hack. What we really should do is create a user
  7941. // conversion step for this case, but this makes it considerably more
  7942. // complicated. For now, this will do.
  7943. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  7944. Entity.getType().getNonReferenceType());
  7945. bool UseTemporary = Entity.getType()->isReferenceType();
  7946. bool IsStdInitListInit =
  7947. Step->Kind == SK_StdInitializerListConstructorCall;
  7948. Expr *Source = CurInit.get();
  7949. SourceRange Range = Kind.hasParenOrBraceRange()
  7950. ? Kind.getParenOrBraceRange()
  7951. : SourceRange();
  7952. CurInit = PerformConstructorInitialization(
  7953. S, UseTemporary ? TempEntity : Entity, Kind,
  7954. Source ? MultiExprArg(Source) : Args, *Step,
  7955. ConstructorInitRequiresZeroInit,
  7956. /*IsListInitialization*/ IsStdInitListInit,
  7957. /*IsStdInitListInitialization*/ IsStdInitListInit,
  7958. /*LBraceLoc*/ Range.getBegin(),
  7959. /*RBraceLoc*/ Range.getEnd());
  7960. break;
  7961. }
  7962. case SK_ZeroInitialization: {
  7963. step_iterator NextStep = Step;
  7964. ++NextStep;
  7965. if (NextStep != StepEnd &&
  7966. (NextStep->Kind == SK_ConstructorInitialization ||
  7967. NextStep->Kind == SK_ConstructorInitializationFromList)) {
  7968. // The need for zero-initialization is recorded directly into
  7969. // the call to the object's constructor within the next step.
  7970. ConstructorInitRequiresZeroInit = true;
  7971. } else if (Kind.getKind() == InitializationKind::IK_Value &&
  7972. S.getLangOpts().CPlusPlus &&
  7973. !Kind.isImplicitValueInit()) {
  7974. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  7975. if (!TSInfo)
  7976. TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
  7977. Kind.getRange().getBegin());
  7978. CurInit = new (S.Context) CXXScalarValueInitExpr(
  7979. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  7980. Kind.getRange().getEnd());
  7981. } else {
  7982. CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
  7983. }
  7984. break;
  7985. }
  7986. case SK_CAssignment: {
  7987. QualType SourceType = CurInit.get()->getType();
  7988. // Save off the initial CurInit in case we need to emit a diagnostic
  7989. ExprResult InitialCurInit = CurInit;
  7990. ExprResult Result = CurInit;
  7991. Sema::AssignConvertType ConvTy =
  7992. S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
  7993. Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
  7994. if (Result.isInvalid())
  7995. return ExprError();
  7996. CurInit = Result;
  7997. // If this is a call, allow conversion to a transparent union.
  7998. ExprResult CurInitExprRes = CurInit;
  7999. if (ConvTy != Sema::Compatible &&
  8000. Entity.isParameterKind() &&
  8001. S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
  8002. == Sema::Compatible)
  8003. ConvTy = Sema::Compatible;
  8004. if (CurInitExprRes.isInvalid())
  8005. return ExprError();
  8006. CurInit = CurInitExprRes;
  8007. bool Complained;
  8008. if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
  8009. Step->Type, SourceType,
  8010. InitialCurInit.get(),
  8011. getAssignmentAction(Entity, true),
  8012. &Complained)) {
  8013. PrintInitLocationNote(S, Entity);
  8014. return ExprError();
  8015. } else if (Complained)
  8016. PrintInitLocationNote(S, Entity);
  8017. break;
  8018. }
  8019. case SK_StringInit: {
  8020. QualType Ty = Step->Type;
  8021. bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
  8022. CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
  8023. S.Context.getAsArrayType(Ty), S);
  8024. break;
  8025. }
  8026. case SK_ObjCObjectConversion:
  8027. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  8028. CK_ObjCObjectLValueCast,
  8029. CurInit.get()->getValueKind());
  8030. break;
  8031. case SK_ArrayLoopIndex: {
  8032. Expr *Cur = CurInit.get();
  8033. Expr *BaseExpr = new (S.Context)
  8034. OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
  8035. Cur->getValueKind(), Cur->getObjectKind(), Cur);
  8036. Expr *IndexExpr =
  8037. new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
  8038. CurInit = S.CreateBuiltinArraySubscriptExpr(
  8039. BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
  8040. ArrayLoopCommonExprs.push_back(BaseExpr);
  8041. break;
  8042. }
  8043. case SK_ArrayLoopInit: {
  8044. assert(!ArrayLoopCommonExprs.empty() &&
  8045. "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
  8046. Expr *Common = ArrayLoopCommonExprs.pop_back_val();
  8047. CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
  8048. CurInit.get());
  8049. break;
  8050. }
  8051. case SK_GNUArrayInit:
  8052. // Okay: we checked everything before creating this step. Note that
  8053. // this is a GNU extension.
  8054. S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
  8055. << Step->Type << CurInit.get()->getType()
  8056. << CurInit.get()->getSourceRange();
  8057. updateGNUCompoundLiteralRValue(CurInit.get());
  8058. [[fallthrough]];
  8059. case SK_ArrayInit:
  8060. // If the destination type is an incomplete array type, update the
  8061. // type accordingly.
  8062. if (ResultType) {
  8063. if (const IncompleteArrayType *IncompleteDest
  8064. = S.Context.getAsIncompleteArrayType(Step->Type)) {
  8065. if (const ConstantArrayType *ConstantSource
  8066. = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
  8067. *ResultType = S.Context.getConstantArrayType(
  8068. IncompleteDest->getElementType(),
  8069. ConstantSource->getSize(),
  8070. ConstantSource->getSizeExpr(),
  8071. ArrayType::Normal, 0);
  8072. }
  8073. }
  8074. }
  8075. break;
  8076. case SK_ParenthesizedArrayInit:
  8077. // Okay: we checked everything before creating this step. Note that
  8078. // this is a GNU extension.
  8079. S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
  8080. << CurInit.get()->getSourceRange();
  8081. break;
  8082. case SK_PassByIndirectCopyRestore:
  8083. case SK_PassByIndirectRestore:
  8084. checkIndirectCopyRestoreSource(S, CurInit.get());
  8085. CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
  8086. CurInit.get(), Step->Type,
  8087. Step->Kind == SK_PassByIndirectCopyRestore);
  8088. break;
  8089. case SK_ProduceObjCObject:
  8090. CurInit = ImplicitCastExpr::Create(
  8091. S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
  8092. VK_PRValue, FPOptionsOverride());
  8093. break;
  8094. case SK_StdInitializerList: {
  8095. S.Diag(CurInit.get()->getExprLoc(),
  8096. diag::warn_cxx98_compat_initializer_list_init)
  8097. << CurInit.get()->getSourceRange();
  8098. // Materialize the temporary into memory.
  8099. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  8100. CurInit.get()->getType(), CurInit.get(),
  8101. /*BoundToLvalueReference=*/false);
  8102. // Wrap it in a construction of a std::initializer_list<T>.
  8103. CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
  8104. // Bind the result, in case the library has given initializer_list a
  8105. // non-trivial destructor.
  8106. if (shouldBindAsTemporary(Entity))
  8107. CurInit = S.MaybeBindToTemporary(CurInit.get());
  8108. break;
  8109. }
  8110. case SK_OCLSamplerInit: {
  8111. // Sampler initialization have 5 cases:
  8112. // 1. function argument passing
  8113. // 1a. argument is a file-scope variable
  8114. // 1b. argument is a function-scope variable
  8115. // 1c. argument is one of caller function's parameters
  8116. // 2. variable initialization
  8117. // 2a. initializing a file-scope variable
  8118. // 2b. initializing a function-scope variable
  8119. //
  8120. // For file-scope variables, since they cannot be initialized by function
  8121. // call of __translate_sampler_initializer in LLVM IR, their references
  8122. // need to be replaced by a cast from their literal initializers to
  8123. // sampler type. Since sampler variables can only be used in function
  8124. // calls as arguments, we only need to replace them when handling the
  8125. // argument passing.
  8126. assert(Step->Type->isSamplerT() &&
  8127. "Sampler initialization on non-sampler type.");
  8128. Expr *Init = CurInit.get()->IgnoreParens();
  8129. QualType SourceType = Init->getType();
  8130. // Case 1
  8131. if (Entity.isParameterKind()) {
  8132. if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
  8133. S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
  8134. << SourceType;
  8135. break;
  8136. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
  8137. auto Var = cast<VarDecl>(DRE->getDecl());
  8138. // Case 1b and 1c
  8139. // No cast from integer to sampler is needed.
  8140. if (!Var->hasGlobalStorage()) {
  8141. CurInit = ImplicitCastExpr::Create(
  8142. S.Context, Step->Type, CK_LValueToRValue, Init,
  8143. /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
  8144. break;
  8145. }
  8146. // Case 1a
  8147. // For function call with a file-scope sampler variable as argument,
  8148. // get the integer literal.
  8149. // Do not diagnose if the file-scope variable does not have initializer
  8150. // since this has already been diagnosed when parsing the variable
  8151. // declaration.
  8152. if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
  8153. break;
  8154. Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
  8155. Var->getInit()))->getSubExpr();
  8156. SourceType = Init->getType();
  8157. }
  8158. } else {
  8159. // Case 2
  8160. // Check initializer is 32 bit integer constant.
  8161. // If the initializer is taken from global variable, do not diagnose since
  8162. // this has already been done when parsing the variable declaration.
  8163. if (!Init->isConstantInitializer(S.Context, false))
  8164. break;
  8165. if (!SourceType->isIntegerType() ||
  8166. 32 != S.Context.getIntWidth(SourceType)) {
  8167. S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
  8168. << SourceType;
  8169. break;
  8170. }
  8171. Expr::EvalResult EVResult;
  8172. Init->EvaluateAsInt(EVResult, S.Context);
  8173. llvm::APSInt Result = EVResult.Val.getInt();
  8174. const uint64_t SamplerValue = Result.getLimitedValue();
  8175. // 32-bit value of sampler's initializer is interpreted as
  8176. // bit-field with the following structure:
  8177. // |unspecified|Filter|Addressing Mode| Normalized Coords|
  8178. // |31 6|5 4|3 1| 0|
  8179. // This structure corresponds to enum values of sampler properties
  8180. // defined in SPIR spec v1.2 and also opencl-c.h
  8181. unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
  8182. unsigned FilterMode = (0x30 & SamplerValue) >> 4;
  8183. if (FilterMode != 1 && FilterMode != 2 &&
  8184. !S.getOpenCLOptions().isAvailableOption(
  8185. "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
  8186. S.Diag(Kind.getLocation(),
  8187. diag::warn_sampler_initializer_invalid_bits)
  8188. << "Filter Mode";
  8189. if (AddressingMode > 4)
  8190. S.Diag(Kind.getLocation(),
  8191. diag::warn_sampler_initializer_invalid_bits)
  8192. << "Addressing Mode";
  8193. }
  8194. // Cases 1a, 2a and 2b
  8195. // Insert cast from integer to sampler.
  8196. CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
  8197. CK_IntToOCLSampler);
  8198. break;
  8199. }
  8200. case SK_OCLZeroOpaqueType: {
  8201. assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
  8202. Step->Type->isOCLIntelSubgroupAVCType()) &&
  8203. "Wrong type for initialization of OpenCL opaque type.");
  8204. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  8205. CK_ZeroToOCLOpaqueType,
  8206. CurInit.get()->getValueKind());
  8207. break;
  8208. }
  8209. case SK_ParenthesizedListInit: {
  8210. CurInit = nullptr;
  8211. TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
  8212. /*VerifyOnly=*/false, &CurInit);
  8213. if (CurInit.get() && ResultType)
  8214. *ResultType = CurInit.get()->getType();
  8215. break;
  8216. }
  8217. }
  8218. }
  8219. // Check whether the initializer has a shorter lifetime than the initialized
  8220. // entity, and if not, either lifetime-extend or warn as appropriate.
  8221. if (auto *Init = CurInit.get())
  8222. S.checkInitializerLifetime(Entity, Init);
  8223. // Diagnose non-fatal problems with the completed initialization.
  8224. if (Entity.getKind() == InitializedEntity::EK_Member &&
  8225. cast<FieldDecl>(Entity.getDecl())->isBitField())
  8226. S.CheckBitFieldInitialization(Kind.getLocation(),
  8227. cast<FieldDecl>(Entity.getDecl()),
  8228. CurInit.get());
  8229. // Check for std::move on construction.
  8230. if (const Expr *E = CurInit.get()) {
  8231. CheckMoveOnConstruction(S, E,
  8232. Entity.getKind() == InitializedEntity::EK_Result);
  8233. }
  8234. return CurInit;
  8235. }
  8236. /// Somewhere within T there is an uninitialized reference subobject.
  8237. /// Dig it out and diagnose it.
  8238. static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
  8239. QualType T) {
  8240. if (T->isReferenceType()) {
  8241. S.Diag(Loc, diag::err_reference_without_init)
  8242. << T.getNonReferenceType();
  8243. return true;
  8244. }
  8245. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  8246. if (!RD || !RD->hasUninitializedReferenceMember())
  8247. return false;
  8248. for (const auto *FI : RD->fields()) {
  8249. if (FI->isUnnamedBitfield())
  8250. continue;
  8251. if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
  8252. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  8253. return true;
  8254. }
  8255. }
  8256. for (const auto &BI : RD->bases()) {
  8257. if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
  8258. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  8259. return true;
  8260. }
  8261. }
  8262. return false;
  8263. }
  8264. //===----------------------------------------------------------------------===//
  8265. // Diagnose initialization failures
  8266. //===----------------------------------------------------------------------===//
  8267. /// Emit notes associated with an initialization that failed due to a
  8268. /// "simple" conversion failure.
  8269. static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
  8270. Expr *op) {
  8271. QualType destType = entity.getType();
  8272. if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
  8273. op->getType()->isObjCObjectPointerType()) {
  8274. // Emit a possible note about the conversion failing because the
  8275. // operand is a message send with a related result type.
  8276. S.EmitRelatedResultTypeNote(op);
  8277. // Emit a possible note about a return failing because we're
  8278. // expecting a related result type.
  8279. if (entity.getKind() == InitializedEntity::EK_Result)
  8280. S.EmitRelatedResultTypeNoteForReturn(destType);
  8281. }
  8282. QualType fromType = op->getType();
  8283. QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
  8284. QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
  8285. auto *fromDecl = fromType->getPointeeCXXRecordDecl();
  8286. auto *destDecl = destType->getPointeeCXXRecordDecl();
  8287. if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
  8288. destDecl->getDeclKind() == Decl::CXXRecord &&
  8289. !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
  8290. !fromDecl->hasDefinition() &&
  8291. destPointeeType.getQualifiers().compatiblyIncludes(
  8292. fromPointeeType.getQualifiers()))
  8293. S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
  8294. << S.getASTContext().getTagDeclType(fromDecl)
  8295. << S.getASTContext().getTagDeclType(destDecl);
  8296. }
  8297. static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
  8298. InitListExpr *InitList) {
  8299. QualType DestType = Entity.getType();
  8300. QualType E;
  8301. if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
  8302. QualType ArrayType = S.Context.getConstantArrayType(
  8303. E.withConst(),
  8304. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  8305. InitList->getNumInits()),
  8306. nullptr, clang::ArrayType::Normal, 0);
  8307. InitializedEntity HiddenArray =
  8308. InitializedEntity::InitializeTemporary(ArrayType);
  8309. return diagnoseListInit(S, HiddenArray, InitList);
  8310. }
  8311. if (DestType->isReferenceType()) {
  8312. // A list-initialization failure for a reference means that we tried to
  8313. // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
  8314. // inner initialization failed.
  8315. QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
  8316. diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
  8317. SourceLocation Loc = InitList->getBeginLoc();
  8318. if (auto *D = Entity.getDecl())
  8319. Loc = D->getLocation();
  8320. S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
  8321. return;
  8322. }
  8323. InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
  8324. /*VerifyOnly=*/false,
  8325. /*TreatUnavailableAsInvalid=*/false);
  8326. assert(DiagnoseInitList.HadError() &&
  8327. "Inconsistent init list check result.");
  8328. }
  8329. bool InitializationSequence::Diagnose(Sema &S,
  8330. const InitializedEntity &Entity,
  8331. const InitializationKind &Kind,
  8332. ArrayRef<Expr *> Args) {
  8333. if (!Failed())
  8334. return false;
  8335. // When we want to diagnose only one element of a braced-init-list,
  8336. // we need to factor it out.
  8337. Expr *OnlyArg;
  8338. if (Args.size() == 1) {
  8339. auto *List = dyn_cast<InitListExpr>(Args[0]);
  8340. if (List && List->getNumInits() == 1)
  8341. OnlyArg = List->getInit(0);
  8342. else
  8343. OnlyArg = Args[0];
  8344. }
  8345. else
  8346. OnlyArg = nullptr;
  8347. QualType DestType = Entity.getType();
  8348. switch (Failure) {
  8349. case FK_TooManyInitsForReference:
  8350. // FIXME: Customize for the initialized entity?
  8351. if (Args.empty()) {
  8352. // Dig out the reference subobject which is uninitialized and diagnose it.
  8353. // If this is value-initialization, this could be nested some way within
  8354. // the target type.
  8355. assert(Kind.getKind() == InitializationKind::IK_Value ||
  8356. DestType->isReferenceType());
  8357. bool Diagnosed =
  8358. DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
  8359. assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
  8360. (void)Diagnosed;
  8361. } else // FIXME: diagnostic below could be better!
  8362. S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
  8363. << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  8364. break;
  8365. case FK_ParenthesizedListInitForReference:
  8366. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  8367. << 1 << Entity.getType() << Args[0]->getSourceRange();
  8368. break;
  8369. case FK_ArrayNeedsInitList:
  8370. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
  8371. break;
  8372. case FK_ArrayNeedsInitListOrStringLiteral:
  8373. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
  8374. break;
  8375. case FK_ArrayNeedsInitListOrWideStringLiteral:
  8376. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
  8377. break;
  8378. case FK_NarrowStringIntoWideCharArray:
  8379. S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
  8380. break;
  8381. case FK_WideStringIntoCharArray:
  8382. S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
  8383. break;
  8384. case FK_IncompatWideStringIntoWideChar:
  8385. S.Diag(Kind.getLocation(),
  8386. diag::err_array_init_incompat_wide_string_into_wchar);
  8387. break;
  8388. case FK_PlainStringIntoUTF8Char:
  8389. S.Diag(Kind.getLocation(),
  8390. diag::err_array_init_plain_string_into_char8_t);
  8391. S.Diag(Args.front()->getBeginLoc(),
  8392. diag::note_array_init_plain_string_into_char8_t)
  8393. << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
  8394. break;
  8395. case FK_UTF8StringIntoPlainChar:
  8396. S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
  8397. << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
  8398. break;
  8399. case FK_ArrayTypeMismatch:
  8400. case FK_NonConstantArrayInit:
  8401. S.Diag(Kind.getLocation(),
  8402. (Failure == FK_ArrayTypeMismatch
  8403. ? diag::err_array_init_different_type
  8404. : diag::err_array_init_non_constant_array))
  8405. << DestType.getNonReferenceType()
  8406. << OnlyArg->getType()
  8407. << Args[0]->getSourceRange();
  8408. break;
  8409. case FK_VariableLengthArrayHasInitializer:
  8410. S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
  8411. << Args[0]->getSourceRange();
  8412. break;
  8413. case FK_AddressOfOverloadFailed: {
  8414. DeclAccessPair Found;
  8415. S.ResolveAddressOfOverloadedFunction(OnlyArg,
  8416. DestType.getNonReferenceType(),
  8417. true,
  8418. Found);
  8419. break;
  8420. }
  8421. case FK_AddressOfUnaddressableFunction: {
  8422. auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
  8423. S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  8424. OnlyArg->getBeginLoc());
  8425. break;
  8426. }
  8427. case FK_ReferenceInitOverloadFailed:
  8428. case FK_UserConversionOverloadFailed:
  8429. switch (FailedOverloadResult) {
  8430. case OR_Ambiguous:
  8431. FailedCandidateSet.NoteCandidates(
  8432. PartialDiagnosticAt(
  8433. Kind.getLocation(),
  8434. Failure == FK_UserConversionOverloadFailed
  8435. ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
  8436. << OnlyArg->getType() << DestType
  8437. << Args[0]->getSourceRange())
  8438. : (S.PDiag(diag::err_ref_init_ambiguous)
  8439. << DestType << OnlyArg->getType()
  8440. << Args[0]->getSourceRange())),
  8441. S, OCD_AmbiguousCandidates, Args);
  8442. break;
  8443. case OR_No_Viable_Function: {
  8444. auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
  8445. if (!S.RequireCompleteType(Kind.getLocation(),
  8446. DestType.getNonReferenceType(),
  8447. diag::err_typecheck_nonviable_condition_incomplete,
  8448. OnlyArg->getType(), Args[0]->getSourceRange()))
  8449. S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
  8450. << (Entity.getKind() == InitializedEntity::EK_Result)
  8451. << OnlyArg->getType() << Args[0]->getSourceRange()
  8452. << DestType.getNonReferenceType();
  8453. FailedCandidateSet.NoteCandidates(S, Args, Cands);
  8454. break;
  8455. }
  8456. case OR_Deleted: {
  8457. S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
  8458. << OnlyArg->getType() << DestType.getNonReferenceType()
  8459. << Args[0]->getSourceRange();
  8460. OverloadCandidateSet::iterator Best;
  8461. OverloadingResult Ovl
  8462. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  8463. if (Ovl == OR_Deleted) {
  8464. S.NoteDeletedFunction(Best->Function);
  8465. } else {
  8466. llvm_unreachable("Inconsistent overload resolution?");
  8467. }
  8468. break;
  8469. }
  8470. case OR_Success:
  8471. llvm_unreachable("Conversion did not fail!");
  8472. }
  8473. break;
  8474. case FK_NonConstLValueReferenceBindingToTemporary:
  8475. if (isa<InitListExpr>(Args[0])) {
  8476. S.Diag(Kind.getLocation(),
  8477. diag::err_lvalue_reference_bind_to_initlist)
  8478. << DestType.getNonReferenceType().isVolatileQualified()
  8479. << DestType.getNonReferenceType()
  8480. << Args[0]->getSourceRange();
  8481. break;
  8482. }
  8483. [[fallthrough]];
  8484. case FK_NonConstLValueReferenceBindingToUnrelated:
  8485. S.Diag(Kind.getLocation(),
  8486. Failure == FK_NonConstLValueReferenceBindingToTemporary
  8487. ? diag::err_lvalue_reference_bind_to_temporary
  8488. : diag::err_lvalue_reference_bind_to_unrelated)
  8489. << DestType.getNonReferenceType().isVolatileQualified()
  8490. << DestType.getNonReferenceType()
  8491. << OnlyArg->getType()
  8492. << Args[0]->getSourceRange();
  8493. break;
  8494. case FK_NonConstLValueReferenceBindingToBitfield: {
  8495. // We don't necessarily have an unambiguous source bit-field.
  8496. FieldDecl *BitField = Args[0]->getSourceBitField();
  8497. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
  8498. << DestType.isVolatileQualified()
  8499. << (BitField ? BitField->getDeclName() : DeclarationName())
  8500. << (BitField != nullptr)
  8501. << Args[0]->getSourceRange();
  8502. if (BitField)
  8503. S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
  8504. break;
  8505. }
  8506. case FK_NonConstLValueReferenceBindingToVectorElement:
  8507. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
  8508. << DestType.isVolatileQualified()
  8509. << Args[0]->getSourceRange();
  8510. break;
  8511. case FK_NonConstLValueReferenceBindingToMatrixElement:
  8512. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
  8513. << DestType.isVolatileQualified() << Args[0]->getSourceRange();
  8514. break;
  8515. case FK_RValueReferenceBindingToLValue:
  8516. S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
  8517. << DestType.getNonReferenceType() << OnlyArg->getType()
  8518. << Args[0]->getSourceRange();
  8519. break;
  8520. case FK_ReferenceAddrspaceMismatchTemporary:
  8521. S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
  8522. << DestType << Args[0]->getSourceRange();
  8523. break;
  8524. case FK_ReferenceInitDropsQualifiers: {
  8525. QualType SourceType = OnlyArg->getType();
  8526. QualType NonRefType = DestType.getNonReferenceType();
  8527. Qualifiers DroppedQualifiers =
  8528. SourceType.getQualifiers() - NonRefType.getQualifiers();
  8529. if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
  8530. SourceType.getQualifiers()))
  8531. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  8532. << NonRefType << SourceType << 1 /*addr space*/
  8533. << Args[0]->getSourceRange();
  8534. else if (DroppedQualifiers.hasQualifiers())
  8535. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  8536. << NonRefType << SourceType << 0 /*cv quals*/
  8537. << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
  8538. << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
  8539. else
  8540. // FIXME: Consider decomposing the type and explaining which qualifiers
  8541. // were dropped where, or on which level a 'const' is missing, etc.
  8542. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  8543. << NonRefType << SourceType << 2 /*incompatible quals*/
  8544. << Args[0]->getSourceRange();
  8545. break;
  8546. }
  8547. case FK_ReferenceInitFailed:
  8548. S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
  8549. << DestType.getNonReferenceType()
  8550. << DestType.getNonReferenceType()->isIncompleteType()
  8551. << OnlyArg->isLValue()
  8552. << OnlyArg->getType()
  8553. << Args[0]->getSourceRange();
  8554. emitBadConversionNotes(S, Entity, Args[0]);
  8555. break;
  8556. case FK_ConversionFailed: {
  8557. QualType FromType = OnlyArg->getType();
  8558. PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
  8559. << (int)Entity.getKind()
  8560. << DestType
  8561. << OnlyArg->isLValue()
  8562. << FromType
  8563. << Args[0]->getSourceRange();
  8564. S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
  8565. S.Diag(Kind.getLocation(), PDiag);
  8566. emitBadConversionNotes(S, Entity, Args[0]);
  8567. break;
  8568. }
  8569. case FK_ConversionFromPropertyFailed:
  8570. // No-op. This error has already been reported.
  8571. break;
  8572. case FK_TooManyInitsForScalar: {
  8573. SourceRange R;
  8574. auto *InitList = dyn_cast<InitListExpr>(Args[0]);
  8575. if (InitList && InitList->getNumInits() >= 1) {
  8576. R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
  8577. } else {
  8578. assert(Args.size() > 1 && "Expected multiple initializers!");
  8579. R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
  8580. }
  8581. R.setBegin(S.getLocForEndOfToken(R.getBegin()));
  8582. if (Kind.isCStyleOrFunctionalCast())
  8583. S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
  8584. << R;
  8585. else
  8586. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  8587. << /*scalar=*/2 << R;
  8588. break;
  8589. }
  8590. case FK_ParenthesizedListInitForScalar:
  8591. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  8592. << 0 << Entity.getType() << Args[0]->getSourceRange();
  8593. break;
  8594. case FK_ReferenceBindingToInitList:
  8595. S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
  8596. << DestType.getNonReferenceType() << Args[0]->getSourceRange();
  8597. break;
  8598. case FK_InitListBadDestinationType:
  8599. S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
  8600. << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
  8601. break;
  8602. case FK_ListConstructorOverloadFailed:
  8603. case FK_ConstructorOverloadFailed: {
  8604. SourceRange ArgsRange;
  8605. if (Args.size())
  8606. ArgsRange =
  8607. SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  8608. if (Failure == FK_ListConstructorOverloadFailed) {
  8609. assert(Args.size() == 1 &&
  8610. "List construction from other than 1 argument.");
  8611. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  8612. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  8613. }
  8614. // FIXME: Using "DestType" for the entity we're printing is probably
  8615. // bad.
  8616. switch (FailedOverloadResult) {
  8617. case OR_Ambiguous:
  8618. FailedCandidateSet.NoteCandidates(
  8619. PartialDiagnosticAt(Kind.getLocation(),
  8620. S.PDiag(diag::err_ovl_ambiguous_init)
  8621. << DestType << ArgsRange),
  8622. S, OCD_AmbiguousCandidates, Args);
  8623. break;
  8624. case OR_No_Viable_Function:
  8625. if (Kind.getKind() == InitializationKind::IK_Default &&
  8626. (Entity.getKind() == InitializedEntity::EK_Base ||
  8627. Entity.getKind() == InitializedEntity::EK_Member) &&
  8628. isa<CXXConstructorDecl>(S.CurContext)) {
  8629. // This is implicit default initialization of a member or
  8630. // base within a constructor. If no viable function was
  8631. // found, notify the user that they need to explicitly
  8632. // initialize this base/member.
  8633. CXXConstructorDecl *Constructor
  8634. = cast<CXXConstructorDecl>(S.CurContext);
  8635. const CXXRecordDecl *InheritedFrom = nullptr;
  8636. if (auto Inherited = Constructor->getInheritedConstructor())
  8637. InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
  8638. if (Entity.getKind() == InitializedEntity::EK_Base) {
  8639. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  8640. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  8641. << S.Context.getTypeDeclType(Constructor->getParent())
  8642. << /*base=*/0
  8643. << Entity.getType()
  8644. << InheritedFrom;
  8645. RecordDecl *BaseDecl
  8646. = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
  8647. ->getDecl();
  8648. S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  8649. << S.Context.getTagDeclType(BaseDecl);
  8650. } else {
  8651. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  8652. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  8653. << S.Context.getTypeDeclType(Constructor->getParent())
  8654. << /*member=*/1
  8655. << Entity.getName()
  8656. << InheritedFrom;
  8657. S.Diag(Entity.getDecl()->getLocation(),
  8658. diag::note_member_declared_at);
  8659. if (const RecordType *Record
  8660. = Entity.getType()->getAs<RecordType>())
  8661. S.Diag(Record->getDecl()->getLocation(),
  8662. diag::note_previous_decl)
  8663. << S.Context.getTagDeclType(Record->getDecl());
  8664. }
  8665. break;
  8666. }
  8667. FailedCandidateSet.NoteCandidates(
  8668. PartialDiagnosticAt(
  8669. Kind.getLocation(),
  8670. S.PDiag(diag::err_ovl_no_viable_function_in_init)
  8671. << DestType << ArgsRange),
  8672. S, OCD_AllCandidates, Args);
  8673. break;
  8674. case OR_Deleted: {
  8675. OverloadCandidateSet::iterator Best;
  8676. OverloadingResult Ovl
  8677. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  8678. if (Ovl != OR_Deleted) {
  8679. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  8680. << DestType << ArgsRange;
  8681. llvm_unreachable("Inconsistent overload resolution?");
  8682. break;
  8683. }
  8684. // If this is a defaulted or implicitly-declared function, then
  8685. // it was implicitly deleted. Make it clear that the deletion was
  8686. // implicit.
  8687. if (S.isImplicitlyDeleted(Best->Function))
  8688. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
  8689. << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
  8690. << DestType << ArgsRange;
  8691. else
  8692. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  8693. << DestType << ArgsRange;
  8694. S.NoteDeletedFunction(Best->Function);
  8695. break;
  8696. }
  8697. case OR_Success:
  8698. llvm_unreachable("Conversion did not fail!");
  8699. }
  8700. }
  8701. break;
  8702. case FK_DefaultInitOfConst:
  8703. if (Entity.getKind() == InitializedEntity::EK_Member &&
  8704. isa<CXXConstructorDecl>(S.CurContext)) {
  8705. // This is implicit default-initialization of a const member in
  8706. // a constructor. Complain that it needs to be explicitly
  8707. // initialized.
  8708. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
  8709. S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
  8710. << (Constructor->getInheritedConstructor() ? 2 :
  8711. Constructor->isImplicit() ? 1 : 0)
  8712. << S.Context.getTypeDeclType(Constructor->getParent())
  8713. << /*const=*/1
  8714. << Entity.getName();
  8715. S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
  8716. << Entity.getName();
  8717. } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
  8718. VD && VD->isConstexpr()) {
  8719. S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
  8720. << VD;
  8721. } else {
  8722. S.Diag(Kind.getLocation(), diag::err_default_init_const)
  8723. << DestType << (bool)DestType->getAs<RecordType>();
  8724. }
  8725. break;
  8726. case FK_Incomplete:
  8727. S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
  8728. diag::err_init_incomplete_type);
  8729. break;
  8730. case FK_ListInitializationFailed: {
  8731. // Run the init list checker again to emit diagnostics.
  8732. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  8733. diagnoseListInit(S, Entity, InitList);
  8734. break;
  8735. }
  8736. case FK_PlaceholderType: {
  8737. // FIXME: Already diagnosed!
  8738. break;
  8739. }
  8740. case FK_ExplicitConstructor: {
  8741. S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
  8742. << Args[0]->getSourceRange();
  8743. OverloadCandidateSet::iterator Best;
  8744. OverloadingResult Ovl
  8745. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  8746. (void)Ovl;
  8747. assert(Ovl == OR_Success && "Inconsistent overload resolution");
  8748. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  8749. S.Diag(CtorDecl->getLocation(),
  8750. diag::note_explicit_ctor_deduction_guide_here) << false;
  8751. break;
  8752. }
  8753. case FK_ParenthesizedListInitFailed:
  8754. TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
  8755. /*VerifyOnly=*/false);
  8756. break;
  8757. }
  8758. PrintInitLocationNote(S, Entity);
  8759. return true;
  8760. }
  8761. void InitializationSequence::dump(raw_ostream &OS) const {
  8762. switch (SequenceKind) {
  8763. case FailedSequence: {
  8764. OS << "Failed sequence: ";
  8765. switch (Failure) {
  8766. case FK_TooManyInitsForReference:
  8767. OS << "too many initializers for reference";
  8768. break;
  8769. case FK_ParenthesizedListInitForReference:
  8770. OS << "parenthesized list init for reference";
  8771. break;
  8772. case FK_ArrayNeedsInitList:
  8773. OS << "array requires initializer list";
  8774. break;
  8775. case FK_AddressOfUnaddressableFunction:
  8776. OS << "address of unaddressable function was taken";
  8777. break;
  8778. case FK_ArrayNeedsInitListOrStringLiteral:
  8779. OS << "array requires initializer list or string literal";
  8780. break;
  8781. case FK_ArrayNeedsInitListOrWideStringLiteral:
  8782. OS << "array requires initializer list or wide string literal";
  8783. break;
  8784. case FK_NarrowStringIntoWideCharArray:
  8785. OS << "narrow string into wide char array";
  8786. break;
  8787. case FK_WideStringIntoCharArray:
  8788. OS << "wide string into char array";
  8789. break;
  8790. case FK_IncompatWideStringIntoWideChar:
  8791. OS << "incompatible wide string into wide char array";
  8792. break;
  8793. case FK_PlainStringIntoUTF8Char:
  8794. OS << "plain string literal into char8_t array";
  8795. break;
  8796. case FK_UTF8StringIntoPlainChar:
  8797. OS << "u8 string literal into char array";
  8798. break;
  8799. case FK_ArrayTypeMismatch:
  8800. OS << "array type mismatch";
  8801. break;
  8802. case FK_NonConstantArrayInit:
  8803. OS << "non-constant array initializer";
  8804. break;
  8805. case FK_AddressOfOverloadFailed:
  8806. OS << "address of overloaded function failed";
  8807. break;
  8808. case FK_ReferenceInitOverloadFailed:
  8809. OS << "overload resolution for reference initialization failed";
  8810. break;
  8811. case FK_NonConstLValueReferenceBindingToTemporary:
  8812. OS << "non-const lvalue reference bound to temporary";
  8813. break;
  8814. case FK_NonConstLValueReferenceBindingToBitfield:
  8815. OS << "non-const lvalue reference bound to bit-field";
  8816. break;
  8817. case FK_NonConstLValueReferenceBindingToVectorElement:
  8818. OS << "non-const lvalue reference bound to vector element";
  8819. break;
  8820. case FK_NonConstLValueReferenceBindingToMatrixElement:
  8821. OS << "non-const lvalue reference bound to matrix element";
  8822. break;
  8823. case FK_NonConstLValueReferenceBindingToUnrelated:
  8824. OS << "non-const lvalue reference bound to unrelated type";
  8825. break;
  8826. case FK_RValueReferenceBindingToLValue:
  8827. OS << "rvalue reference bound to an lvalue";
  8828. break;
  8829. case FK_ReferenceInitDropsQualifiers:
  8830. OS << "reference initialization drops qualifiers";
  8831. break;
  8832. case FK_ReferenceAddrspaceMismatchTemporary:
  8833. OS << "reference with mismatching address space bound to temporary";
  8834. break;
  8835. case FK_ReferenceInitFailed:
  8836. OS << "reference initialization failed";
  8837. break;
  8838. case FK_ConversionFailed:
  8839. OS << "conversion failed";
  8840. break;
  8841. case FK_ConversionFromPropertyFailed:
  8842. OS << "conversion from property failed";
  8843. break;
  8844. case FK_TooManyInitsForScalar:
  8845. OS << "too many initializers for scalar";
  8846. break;
  8847. case FK_ParenthesizedListInitForScalar:
  8848. OS << "parenthesized list init for reference";
  8849. break;
  8850. case FK_ReferenceBindingToInitList:
  8851. OS << "referencing binding to initializer list";
  8852. break;
  8853. case FK_InitListBadDestinationType:
  8854. OS << "initializer list for non-aggregate, non-scalar type";
  8855. break;
  8856. case FK_UserConversionOverloadFailed:
  8857. OS << "overloading failed for user-defined conversion";
  8858. break;
  8859. case FK_ConstructorOverloadFailed:
  8860. OS << "constructor overloading failed";
  8861. break;
  8862. case FK_DefaultInitOfConst:
  8863. OS << "default initialization of a const variable";
  8864. break;
  8865. case FK_Incomplete:
  8866. OS << "initialization of incomplete type";
  8867. break;
  8868. case FK_ListInitializationFailed:
  8869. OS << "list initialization checker failure";
  8870. break;
  8871. case FK_VariableLengthArrayHasInitializer:
  8872. OS << "variable length array has an initializer";
  8873. break;
  8874. case FK_PlaceholderType:
  8875. OS << "initializer expression isn't contextually valid";
  8876. break;
  8877. case FK_ListConstructorOverloadFailed:
  8878. OS << "list constructor overloading failed";
  8879. break;
  8880. case FK_ExplicitConstructor:
  8881. OS << "list copy initialization chose explicit constructor";
  8882. break;
  8883. case FK_ParenthesizedListInitFailed:
  8884. OS << "parenthesized list initialization failed";
  8885. break;
  8886. }
  8887. OS << '\n';
  8888. return;
  8889. }
  8890. case DependentSequence:
  8891. OS << "Dependent sequence\n";
  8892. return;
  8893. case NormalSequence:
  8894. OS << "Normal sequence: ";
  8895. break;
  8896. }
  8897. for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
  8898. if (S != step_begin()) {
  8899. OS << " -> ";
  8900. }
  8901. switch (S->Kind) {
  8902. case SK_ResolveAddressOfOverloadedFunction:
  8903. OS << "resolve address of overloaded function";
  8904. break;
  8905. case SK_CastDerivedToBasePRValue:
  8906. OS << "derived-to-base (prvalue)";
  8907. break;
  8908. case SK_CastDerivedToBaseXValue:
  8909. OS << "derived-to-base (xvalue)";
  8910. break;
  8911. case SK_CastDerivedToBaseLValue:
  8912. OS << "derived-to-base (lvalue)";
  8913. break;
  8914. case SK_BindReference:
  8915. OS << "bind reference to lvalue";
  8916. break;
  8917. case SK_BindReferenceToTemporary:
  8918. OS << "bind reference to a temporary";
  8919. break;
  8920. case SK_FinalCopy:
  8921. OS << "final copy in class direct-initialization";
  8922. break;
  8923. case SK_ExtraneousCopyToTemporary:
  8924. OS << "extraneous C++03 copy to temporary";
  8925. break;
  8926. case SK_UserConversion:
  8927. OS << "user-defined conversion via " << *S->Function.Function;
  8928. break;
  8929. case SK_QualificationConversionPRValue:
  8930. OS << "qualification conversion (prvalue)";
  8931. break;
  8932. case SK_QualificationConversionXValue:
  8933. OS << "qualification conversion (xvalue)";
  8934. break;
  8935. case SK_QualificationConversionLValue:
  8936. OS << "qualification conversion (lvalue)";
  8937. break;
  8938. case SK_FunctionReferenceConversion:
  8939. OS << "function reference conversion";
  8940. break;
  8941. case SK_AtomicConversion:
  8942. OS << "non-atomic-to-atomic conversion";
  8943. break;
  8944. case SK_ConversionSequence:
  8945. OS << "implicit conversion sequence (";
  8946. S->ICS->dump(); // FIXME: use OS
  8947. OS << ")";
  8948. break;
  8949. case SK_ConversionSequenceNoNarrowing:
  8950. OS << "implicit conversion sequence with narrowing prohibited (";
  8951. S->ICS->dump(); // FIXME: use OS
  8952. OS << ")";
  8953. break;
  8954. case SK_ListInitialization:
  8955. OS << "list aggregate initialization";
  8956. break;
  8957. case SK_UnwrapInitList:
  8958. OS << "unwrap reference initializer list";
  8959. break;
  8960. case SK_RewrapInitList:
  8961. OS << "rewrap reference initializer list";
  8962. break;
  8963. case SK_ConstructorInitialization:
  8964. OS << "constructor initialization";
  8965. break;
  8966. case SK_ConstructorInitializationFromList:
  8967. OS << "list initialization via constructor";
  8968. break;
  8969. case SK_ZeroInitialization:
  8970. OS << "zero initialization";
  8971. break;
  8972. case SK_CAssignment:
  8973. OS << "C assignment";
  8974. break;
  8975. case SK_StringInit:
  8976. OS << "string initialization";
  8977. break;
  8978. case SK_ObjCObjectConversion:
  8979. OS << "Objective-C object conversion";
  8980. break;
  8981. case SK_ArrayLoopIndex:
  8982. OS << "indexing for array initialization loop";
  8983. break;
  8984. case SK_ArrayLoopInit:
  8985. OS << "array initialization loop";
  8986. break;
  8987. case SK_ArrayInit:
  8988. OS << "array initialization";
  8989. break;
  8990. case SK_GNUArrayInit:
  8991. OS << "array initialization (GNU extension)";
  8992. break;
  8993. case SK_ParenthesizedArrayInit:
  8994. OS << "parenthesized array initialization";
  8995. break;
  8996. case SK_PassByIndirectCopyRestore:
  8997. OS << "pass by indirect copy and restore";
  8998. break;
  8999. case SK_PassByIndirectRestore:
  9000. OS << "pass by indirect restore";
  9001. break;
  9002. case SK_ProduceObjCObject:
  9003. OS << "Objective-C object retension";
  9004. break;
  9005. case SK_StdInitializerList:
  9006. OS << "std::initializer_list from initializer list";
  9007. break;
  9008. case SK_StdInitializerListConstructorCall:
  9009. OS << "list initialization from std::initializer_list";
  9010. break;
  9011. case SK_OCLSamplerInit:
  9012. OS << "OpenCL sampler_t from integer constant";
  9013. break;
  9014. case SK_OCLZeroOpaqueType:
  9015. OS << "OpenCL opaque type from zero";
  9016. break;
  9017. case SK_ParenthesizedListInit:
  9018. OS << "initialization from a parenthesized list of values";
  9019. break;
  9020. }
  9021. OS << " [" << S->Type << ']';
  9022. }
  9023. OS << '\n';
  9024. }
  9025. void InitializationSequence::dump() const {
  9026. dump(llvm::errs());
  9027. }
  9028. static bool NarrowingErrs(const LangOptions &L) {
  9029. return L.CPlusPlus11 &&
  9030. (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
  9031. }
  9032. static void DiagnoseNarrowingInInitList(Sema &S,
  9033. const ImplicitConversionSequence &ICS,
  9034. QualType PreNarrowingType,
  9035. QualType EntityType,
  9036. const Expr *PostInit) {
  9037. const StandardConversionSequence *SCS = nullptr;
  9038. switch (ICS.getKind()) {
  9039. case ImplicitConversionSequence::StandardConversion:
  9040. SCS = &ICS.Standard;
  9041. break;
  9042. case ImplicitConversionSequence::UserDefinedConversion:
  9043. SCS = &ICS.UserDefined.After;
  9044. break;
  9045. case ImplicitConversionSequence::AmbiguousConversion:
  9046. case ImplicitConversionSequence::StaticObjectArgumentConversion:
  9047. case ImplicitConversionSequence::EllipsisConversion:
  9048. case ImplicitConversionSequence::BadConversion:
  9049. return;
  9050. }
  9051. // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
  9052. APValue ConstantValue;
  9053. QualType ConstantType;
  9054. switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
  9055. ConstantType)) {
  9056. case NK_Not_Narrowing:
  9057. case NK_Dependent_Narrowing:
  9058. // No narrowing occurred.
  9059. return;
  9060. case NK_Type_Narrowing:
  9061. // This was a floating-to-integer conversion, which is always considered a
  9062. // narrowing conversion even if the value is a constant and can be
  9063. // represented exactly as an integer.
  9064. S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
  9065. ? diag::ext_init_list_type_narrowing
  9066. : diag::warn_init_list_type_narrowing)
  9067. << PostInit->getSourceRange()
  9068. << PreNarrowingType.getLocalUnqualifiedType()
  9069. << EntityType.getLocalUnqualifiedType();
  9070. break;
  9071. case NK_Constant_Narrowing:
  9072. // A constant value was narrowed.
  9073. S.Diag(PostInit->getBeginLoc(),
  9074. NarrowingErrs(S.getLangOpts())
  9075. ? diag::ext_init_list_constant_narrowing
  9076. : diag::warn_init_list_constant_narrowing)
  9077. << PostInit->getSourceRange()
  9078. << ConstantValue.getAsString(S.getASTContext(), ConstantType)
  9079. << EntityType.getLocalUnqualifiedType();
  9080. break;
  9081. case NK_Variable_Narrowing:
  9082. // A variable's value may have been narrowed.
  9083. S.Diag(PostInit->getBeginLoc(),
  9084. NarrowingErrs(S.getLangOpts())
  9085. ? diag::ext_init_list_variable_narrowing
  9086. : diag::warn_init_list_variable_narrowing)
  9087. << PostInit->getSourceRange()
  9088. << PreNarrowingType.getLocalUnqualifiedType()
  9089. << EntityType.getLocalUnqualifiedType();
  9090. break;
  9091. }
  9092. SmallString<128> StaticCast;
  9093. llvm::raw_svector_ostream OS(StaticCast);
  9094. OS << "static_cast<";
  9095. if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
  9096. // It's important to use the typedef's name if there is one so that the
  9097. // fixit doesn't break code using types like int64_t.
  9098. //
  9099. // FIXME: This will break if the typedef requires qualification. But
  9100. // getQualifiedNameAsString() includes non-machine-parsable components.
  9101. OS << *TT->getDecl();
  9102. } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
  9103. OS << BT->getName(S.getLangOpts());
  9104. else {
  9105. // Oops, we didn't find the actual type of the variable. Don't emit a fixit
  9106. // with a broken cast.
  9107. return;
  9108. }
  9109. OS << ">(";
  9110. S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
  9111. << PostInit->getSourceRange()
  9112. << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
  9113. << FixItHint::CreateInsertion(
  9114. S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
  9115. }
  9116. //===----------------------------------------------------------------------===//
  9117. // Initialization helper functions
  9118. //===----------------------------------------------------------------------===//
  9119. bool
  9120. Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
  9121. ExprResult Init) {
  9122. if (Init.isInvalid())
  9123. return false;
  9124. Expr *InitE = Init.get();
  9125. assert(InitE && "No initialization expression");
  9126. InitializationKind Kind =
  9127. InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
  9128. InitializationSequence Seq(*this, Entity, Kind, InitE);
  9129. return !Seq.Failed();
  9130. }
  9131. ExprResult
  9132. Sema::PerformCopyInitialization(const InitializedEntity &Entity,
  9133. SourceLocation EqualLoc,
  9134. ExprResult Init,
  9135. bool TopLevelOfInitList,
  9136. bool AllowExplicit) {
  9137. if (Init.isInvalid())
  9138. return ExprError();
  9139. Expr *InitE = Init.get();
  9140. assert(InitE && "No initialization expression?");
  9141. if (EqualLoc.isInvalid())
  9142. EqualLoc = InitE->getBeginLoc();
  9143. InitializationKind Kind = InitializationKind::CreateCopy(
  9144. InitE->getBeginLoc(), EqualLoc, AllowExplicit);
  9145. InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
  9146. // Prevent infinite recursion when performing parameter copy-initialization.
  9147. const bool ShouldTrackCopy =
  9148. Entity.isParameterKind() && Seq.isConstructorInitialization();
  9149. if (ShouldTrackCopy) {
  9150. if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
  9151. Seq.SetOverloadFailure(
  9152. InitializationSequence::FK_ConstructorOverloadFailed,
  9153. OR_No_Viable_Function);
  9154. // Try to give a meaningful diagnostic note for the problematic
  9155. // constructor.
  9156. const auto LastStep = Seq.step_end() - 1;
  9157. assert(LastStep->Kind ==
  9158. InitializationSequence::SK_ConstructorInitialization);
  9159. const FunctionDecl *Function = LastStep->Function.Function;
  9160. auto Candidate =
  9161. llvm::find_if(Seq.getFailedCandidateSet(),
  9162. [Function](const OverloadCandidate &Candidate) -> bool {
  9163. return Candidate.Viable &&
  9164. Candidate.Function == Function &&
  9165. Candidate.Conversions.size() > 0;
  9166. });
  9167. if (Candidate != Seq.getFailedCandidateSet().end() &&
  9168. Function->getNumParams() > 0) {
  9169. Candidate->Viable = false;
  9170. Candidate->FailureKind = ovl_fail_bad_conversion;
  9171. Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
  9172. InitE,
  9173. Function->getParamDecl(0)->getType());
  9174. }
  9175. }
  9176. CurrentParameterCopyTypes.push_back(Entity.getType());
  9177. }
  9178. ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
  9179. if (ShouldTrackCopy)
  9180. CurrentParameterCopyTypes.pop_back();
  9181. return Result;
  9182. }
  9183. /// Determine whether RD is, or is derived from, a specialization of CTD.
  9184. static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
  9185. ClassTemplateDecl *CTD) {
  9186. auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
  9187. auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
  9188. return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
  9189. };
  9190. return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
  9191. }
  9192. QualType Sema::DeduceTemplateSpecializationFromInitializer(
  9193. TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
  9194. const InitializationKind &Kind, MultiExprArg Inits) {
  9195. auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
  9196. TSInfo->getType()->getContainedDeducedType());
  9197. assert(DeducedTST && "not a deduced template specialization type");
  9198. auto TemplateName = DeducedTST->getTemplateName();
  9199. if (TemplateName.isDependent())
  9200. return SubstAutoTypeDependent(TSInfo->getType());
  9201. // We can only perform deduction for class templates.
  9202. auto *Template =
  9203. dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
  9204. if (!Template) {
  9205. Diag(Kind.getLocation(),
  9206. diag::err_deduced_non_class_template_specialization_type)
  9207. << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
  9208. if (auto *TD = TemplateName.getAsTemplateDecl())
  9209. Diag(TD->getLocation(), diag::note_template_decl_here);
  9210. return QualType();
  9211. }
  9212. // Can't deduce from dependent arguments.
  9213. if (Expr::hasAnyTypeDependentArguments(Inits)) {
  9214. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  9215. diag::warn_cxx14_compat_class_template_argument_deduction)
  9216. << TSInfo->getTypeLoc().getSourceRange() << 0;
  9217. return SubstAutoTypeDependent(TSInfo->getType());
  9218. }
  9219. // FIXME: Perform "exact type" matching first, per CWG discussion?
  9220. // Or implement this via an implied 'T(T) -> T' deduction guide?
  9221. // FIXME: Do we need/want a std::initializer_list<T> special case?
  9222. // Look up deduction guides, including those synthesized from constructors.
  9223. //
  9224. // C++1z [over.match.class.deduct]p1:
  9225. // A set of functions and function templates is formed comprising:
  9226. // - For each constructor of the class template designated by the
  9227. // template-name, a function template [...]
  9228. // - For each deduction-guide, a function or function template [...]
  9229. DeclarationNameInfo NameInfo(
  9230. Context.DeclarationNames.getCXXDeductionGuideName(Template),
  9231. TSInfo->getTypeLoc().getEndLoc());
  9232. LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
  9233. LookupQualifiedName(Guides, Template->getDeclContext());
  9234. // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
  9235. // clear on this, but they're not found by name so access does not apply.
  9236. Guides.suppressDiagnostics();
  9237. // Figure out if this is list-initialization.
  9238. InitListExpr *ListInit =
  9239. (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
  9240. ? dyn_cast<InitListExpr>(Inits[0])
  9241. : nullptr;
  9242. // C++1z [over.match.class.deduct]p1:
  9243. // Initialization and overload resolution are performed as described in
  9244. // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
  9245. // (as appropriate for the type of initialization performed) for an object
  9246. // of a hypothetical class type, where the selected functions and function
  9247. // templates are considered to be the constructors of that class type
  9248. //
  9249. // Since we know we're initializing a class type of a type unrelated to that
  9250. // of the initializer, this reduces to something fairly reasonable.
  9251. OverloadCandidateSet Candidates(Kind.getLocation(),
  9252. OverloadCandidateSet::CSK_Normal);
  9253. OverloadCandidateSet::iterator Best;
  9254. bool HasAnyDeductionGuide = false;
  9255. bool AllowExplicit = !Kind.isCopyInit() || ListInit;
  9256. auto tryToResolveOverload =
  9257. [&](bool OnlyListConstructors) -> OverloadingResult {
  9258. Candidates.clear(OverloadCandidateSet::CSK_Normal);
  9259. HasAnyDeductionGuide = false;
  9260. for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
  9261. NamedDecl *D = (*I)->getUnderlyingDecl();
  9262. if (D->isInvalidDecl())
  9263. continue;
  9264. auto *TD = dyn_cast<FunctionTemplateDecl>(D);
  9265. auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
  9266. TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
  9267. if (!GD)
  9268. continue;
  9269. if (!GD->isImplicit())
  9270. HasAnyDeductionGuide = true;
  9271. // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
  9272. // For copy-initialization, the candidate functions are all the
  9273. // converting constructors (12.3.1) of that class.
  9274. // C++ [over.match.copy]p1: (non-list copy-initialization from class)
  9275. // The converting constructors of T are candidate functions.
  9276. if (!AllowExplicit) {
  9277. // Overload resolution checks whether the deduction guide is declared
  9278. // explicit for us.
  9279. // When looking for a converting constructor, deduction guides that
  9280. // could never be called with one argument are not interesting to
  9281. // check or note.
  9282. if (GD->getMinRequiredArguments() > 1 ||
  9283. (GD->getNumParams() == 0 && !GD->isVariadic()))
  9284. continue;
  9285. }
  9286. // C++ [over.match.list]p1.1: (first phase list initialization)
  9287. // Initially, the candidate functions are the initializer-list
  9288. // constructors of the class T
  9289. if (OnlyListConstructors && !isInitListConstructor(GD))
  9290. continue;
  9291. // C++ [over.match.list]p1.2: (second phase list initialization)
  9292. // the candidate functions are all the constructors of the class T
  9293. // C++ [over.match.ctor]p1: (all other cases)
  9294. // the candidate functions are all the constructors of the class of
  9295. // the object being initialized
  9296. // C++ [over.best.ics]p4:
  9297. // When [...] the constructor [...] is a candidate by
  9298. // - [over.match.copy] (in all cases)
  9299. // FIXME: The "second phase of [over.match.list] case can also
  9300. // theoretically happen here, but it's not clear whether we can
  9301. // ever have a parameter of the right type.
  9302. bool SuppressUserConversions = Kind.isCopyInit();
  9303. if (TD)
  9304. AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
  9305. Inits, Candidates, SuppressUserConversions,
  9306. /*PartialOverloading*/ false,
  9307. AllowExplicit);
  9308. else
  9309. AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
  9310. SuppressUserConversions,
  9311. /*PartialOverloading*/ false, AllowExplicit);
  9312. }
  9313. return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
  9314. };
  9315. OverloadingResult Result = OR_No_Viable_Function;
  9316. // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
  9317. // try initializer-list constructors.
  9318. if (ListInit) {
  9319. bool TryListConstructors = true;
  9320. // Try list constructors unless the list is empty and the class has one or
  9321. // more default constructors, in which case those constructors win.
  9322. if (!ListInit->getNumInits()) {
  9323. for (NamedDecl *D : Guides) {
  9324. auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
  9325. if (FD && FD->getMinRequiredArguments() == 0) {
  9326. TryListConstructors = false;
  9327. break;
  9328. }
  9329. }
  9330. } else if (ListInit->getNumInits() == 1) {
  9331. // C++ [over.match.class.deduct]:
  9332. // As an exception, the first phase in [over.match.list] (considering
  9333. // initializer-list constructors) is omitted if the initializer list
  9334. // consists of a single expression of type cv U, where U is a
  9335. // specialization of C or a class derived from a specialization of C.
  9336. Expr *E = ListInit->getInit(0);
  9337. auto *RD = E->getType()->getAsCXXRecordDecl();
  9338. if (!isa<InitListExpr>(E) && RD &&
  9339. isCompleteType(Kind.getLocation(), E->getType()) &&
  9340. isOrIsDerivedFromSpecializationOf(RD, Template))
  9341. TryListConstructors = false;
  9342. }
  9343. if (TryListConstructors)
  9344. Result = tryToResolveOverload(/*OnlyListConstructor*/true);
  9345. // Then unwrap the initializer list and try again considering all
  9346. // constructors.
  9347. Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
  9348. }
  9349. // If list-initialization fails, or if we're doing any other kind of
  9350. // initialization, we (eventually) consider constructors.
  9351. if (Result == OR_No_Viable_Function)
  9352. Result = tryToResolveOverload(/*OnlyListConstructor*/false);
  9353. switch (Result) {
  9354. case OR_Ambiguous:
  9355. // FIXME: For list-initialization candidates, it'd usually be better to
  9356. // list why they were not viable when given the initializer list itself as
  9357. // an argument.
  9358. Candidates.NoteCandidates(
  9359. PartialDiagnosticAt(
  9360. Kind.getLocation(),
  9361. PDiag(diag::err_deduced_class_template_ctor_ambiguous)
  9362. << TemplateName),
  9363. *this, OCD_AmbiguousCandidates, Inits);
  9364. return QualType();
  9365. case OR_No_Viable_Function: {
  9366. CXXRecordDecl *Primary =
  9367. cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
  9368. bool Complete =
  9369. isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
  9370. Candidates.NoteCandidates(
  9371. PartialDiagnosticAt(
  9372. Kind.getLocation(),
  9373. PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
  9374. : diag::err_deduced_class_template_incomplete)
  9375. << TemplateName << !Guides.empty()),
  9376. *this, OCD_AllCandidates, Inits);
  9377. return QualType();
  9378. }
  9379. case OR_Deleted: {
  9380. Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
  9381. << TemplateName;
  9382. NoteDeletedFunction(Best->Function);
  9383. return QualType();
  9384. }
  9385. case OR_Success:
  9386. // C++ [over.match.list]p1:
  9387. // In copy-list-initialization, if an explicit constructor is chosen, the
  9388. // initialization is ill-formed.
  9389. if (Kind.isCopyInit() && ListInit &&
  9390. cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
  9391. bool IsDeductionGuide = !Best->Function->isImplicit();
  9392. Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
  9393. << TemplateName << IsDeductionGuide;
  9394. Diag(Best->Function->getLocation(),
  9395. diag::note_explicit_ctor_deduction_guide_here)
  9396. << IsDeductionGuide;
  9397. return QualType();
  9398. }
  9399. // Make sure we didn't select an unusable deduction guide, and mark it
  9400. // as referenced.
  9401. DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
  9402. MarkFunctionReferenced(Kind.getLocation(), Best->Function);
  9403. break;
  9404. }
  9405. // C++ [dcl.type.class.deduct]p1:
  9406. // The placeholder is replaced by the return type of the function selected
  9407. // by overload resolution for class template deduction.
  9408. QualType DeducedType =
  9409. SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
  9410. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  9411. diag::warn_cxx14_compat_class_template_argument_deduction)
  9412. << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
  9413. // Warn if CTAD was used on a type that does not have any user-defined
  9414. // deduction guides.
  9415. if (!HasAnyDeductionGuide) {
  9416. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  9417. diag::warn_ctad_maybe_unsupported)
  9418. << TemplateName;
  9419. Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
  9420. }
  9421. return DeducedType;
  9422. }