SemaInit.cpp 340 KB

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