SemaInit.cpp 388 KB

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