SemaInit.cpp 388 KB

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