SemaInit.cpp 328 KB

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