SemaInit.cpp 300 KB

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