SemaDeclCXX.cpp 587 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for C++ declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/ComparisonCategories.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/LiteralSupport.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CXXFieldCollector.h"
  32. #include "clang/Sema/DeclSpec.h"
  33. #include "clang/Sema/Initialization.h"
  34. #include "clang/Sema/Lookup.h"
  35. #include "clang/Sema/ParsedTemplate.h"
  36. #include "clang/Sema/Scope.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/SemaInternal.h"
  39. #include "clang/Sema/Template.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/StringExtras.h"
  43. #include <map>
  44. #include <set>
  45. using namespace clang;
  46. //===----------------------------------------------------------------------===//
  47. // CheckDefaultArgumentVisitor
  48. //===----------------------------------------------------------------------===//
  49. namespace {
  50. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  51. /// the default argument of a parameter to determine whether it
  52. /// contains any ill-formed subexpressions. For example, this will
  53. /// diagnose the use of local variables or parameters within the
  54. /// default argument expression.
  55. class CheckDefaultArgumentVisitor
  56. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  57. Expr *DefaultArg;
  58. Sema *S;
  59. public:
  60. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  61. : DefaultArg(defarg), S(s) {}
  62. bool VisitExpr(Expr *Node);
  63. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  64. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  65. bool VisitLambdaExpr(LambdaExpr *Lambda);
  66. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  67. };
  68. /// VisitExpr - Visit all of the children of this expression.
  69. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  70. bool IsInvalid = false;
  71. for (Stmt *SubStmt : Node->children())
  72. IsInvalid |= Visit(SubStmt);
  73. return IsInvalid;
  74. }
  75. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  76. /// determine whether this declaration can be used in the default
  77. /// argument expression.
  78. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  79. NamedDecl *Decl = DRE->getDecl();
  80. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  81. // C++ [dcl.fct.default]p9
  82. // Default arguments are evaluated each time the function is
  83. // called. The order of evaluation of function arguments is
  84. // unspecified. Consequently, parameters of a function shall not
  85. // be used in default argument expressions, even if they are not
  86. // evaluated. Parameters of a function declared before a default
  87. // argument expression are in scope and can hide namespace and
  88. // class member names.
  89. return S->Diag(DRE->getBeginLoc(),
  90. diag::err_param_default_argument_references_param)
  91. << Param->getDeclName() << DefaultArg->getSourceRange();
  92. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  93. // C++ [dcl.fct.default]p7
  94. // Local variables shall not be used in default argument
  95. // expressions.
  96. if (VDecl->isLocalVarDecl())
  97. return S->Diag(DRE->getBeginLoc(),
  98. diag::err_param_default_argument_references_local)
  99. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  100. }
  101. return false;
  102. }
  103. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  104. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  105. // C++ [dcl.fct.default]p8:
  106. // The keyword this shall not be used in a default argument of a
  107. // member function.
  108. return S->Diag(ThisE->getBeginLoc(),
  109. diag::err_param_default_argument_references_this)
  110. << ThisE->getSourceRange();
  111. }
  112. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  113. bool Invalid = false;
  114. for (PseudoObjectExpr::semantics_iterator
  115. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  116. Expr *E = *i;
  117. // Look through bindings.
  118. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  119. E = OVE->getSourceExpr();
  120. assert(E && "pseudo-object binding without source expression?");
  121. }
  122. Invalid |= Visit(E);
  123. }
  124. return Invalid;
  125. }
  126. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  127. // C++11 [expr.lambda.prim]p13:
  128. // A lambda-expression appearing in a default argument shall not
  129. // implicitly or explicitly capture any entity.
  130. if (Lambda->capture_begin() == Lambda->capture_end())
  131. return false;
  132. return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
  133. }
  134. }
  135. void
  136. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  137. const CXXMethodDecl *Method) {
  138. // If we have an MSAny spec already, don't bother.
  139. if (!Method || ComputedEST == EST_MSAny)
  140. return;
  141. const FunctionProtoType *Proto
  142. = Method->getType()->getAs<FunctionProtoType>();
  143. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  144. if (!Proto)
  145. return;
  146. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  147. // If we have a throw-all spec at this point, ignore the function.
  148. if (ComputedEST == EST_None)
  149. return;
  150. if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
  151. EST = EST_BasicNoexcept;
  152. switch (EST) {
  153. case EST_Unparsed:
  154. case EST_Uninstantiated:
  155. case EST_Unevaluated:
  156. llvm_unreachable("should not see unresolved exception specs here");
  157. // If this function can throw any exceptions, make a note of that.
  158. case EST_MSAny:
  159. case EST_None:
  160. // FIXME: Whichever we see last of MSAny and None determines our result.
  161. // We should make a consistent, order-independent choice here.
  162. ClearExceptions();
  163. ComputedEST = EST;
  164. return;
  165. case EST_NoexceptFalse:
  166. ClearExceptions();
  167. ComputedEST = EST_None;
  168. return;
  169. // FIXME: If the call to this decl is using any of its default arguments, we
  170. // need to search them for potentially-throwing calls.
  171. // If this function has a basic noexcept, it doesn't affect the outcome.
  172. case EST_BasicNoexcept:
  173. case EST_NoexceptTrue:
  174. return;
  175. // If we're still at noexcept(true) and there's a throw() callee,
  176. // change to that specification.
  177. case EST_DynamicNone:
  178. if (ComputedEST == EST_BasicNoexcept)
  179. ComputedEST = EST_DynamicNone;
  180. return;
  181. case EST_DependentNoexcept:
  182. llvm_unreachable(
  183. "should not generate implicit declarations for dependent cases");
  184. case EST_Dynamic:
  185. break;
  186. }
  187. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  188. assert(ComputedEST != EST_None &&
  189. "Shouldn't collect exceptions when throw-all is guaranteed.");
  190. ComputedEST = EST_Dynamic;
  191. // Record the exceptions in this function's exception specification.
  192. for (const auto &E : Proto->exceptions())
  193. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  194. Exceptions.push_back(E);
  195. }
  196. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  197. if (!E || ComputedEST == EST_MSAny)
  198. return;
  199. // FIXME:
  200. //
  201. // C++0x [except.spec]p14:
  202. // [An] implicit exception-specification specifies the type-id T if and
  203. // only if T is allowed by the exception-specification of a function directly
  204. // invoked by f's implicit definition; f shall allow all exceptions if any
  205. // function it directly invokes allows all exceptions, and f shall allow no
  206. // exceptions if every function it directly invokes allows no exceptions.
  207. //
  208. // Note in particular that if an implicit exception-specification is generated
  209. // for a function containing a throw-expression, that specification can still
  210. // be noexcept(true).
  211. //
  212. // Note also that 'directly invoked' is not defined in the standard, and there
  213. // is no indication that we should only consider potentially-evaluated calls.
  214. //
  215. // Ultimately we should implement the intent of the standard: the exception
  216. // specification should be the set of exceptions which can be thrown by the
  217. // implicit definition. For now, we assume that any non-nothrow expression can
  218. // throw any exception.
  219. if (Self->canThrow(E))
  220. ComputedEST = EST_None;
  221. }
  222. bool
  223. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  224. SourceLocation EqualLoc) {
  225. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  226. diag::err_typecheck_decl_incomplete_type)) {
  227. Param->setInvalidDecl();
  228. return true;
  229. }
  230. // C++ [dcl.fct.default]p5
  231. // A default argument expression is implicitly converted (clause
  232. // 4) to the parameter type. The default argument expression has
  233. // the same semantic constraints as the initializer expression in
  234. // a declaration of a variable of the parameter type, using the
  235. // copy-initialization semantics (8.5).
  236. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  237. Param);
  238. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  239. EqualLoc);
  240. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  241. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  242. if (Result.isInvalid())
  243. return true;
  244. Arg = Result.getAs<Expr>();
  245. CheckCompletedExpr(Arg, EqualLoc);
  246. Arg = MaybeCreateExprWithCleanups(Arg);
  247. // Okay: add the default argument to the parameter
  248. Param->setDefaultArg(Arg);
  249. // We have already instantiated this parameter; provide each of the
  250. // instantiations with the uninstantiated default argument.
  251. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  252. = UnparsedDefaultArgInstantiations.find(Param);
  253. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  254. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  255. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  256. // We're done tracking this parameter's instantiations.
  257. UnparsedDefaultArgInstantiations.erase(InstPos);
  258. }
  259. return false;
  260. }
  261. /// ActOnParamDefaultArgument - Check whether the default argument
  262. /// provided for a function parameter is well-formed. If so, attach it
  263. /// to the parameter declaration.
  264. void
  265. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  266. Expr *DefaultArg) {
  267. if (!param || !DefaultArg)
  268. return;
  269. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  270. UnparsedDefaultArgLocs.erase(Param);
  271. // Default arguments are only permitted in C++
  272. if (!getLangOpts().CPlusPlus) {
  273. Diag(EqualLoc, diag::err_param_default_argument)
  274. << DefaultArg->getSourceRange();
  275. Param->setInvalidDecl();
  276. return;
  277. }
  278. // Check for unexpanded parameter packs.
  279. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  280. Param->setInvalidDecl();
  281. return;
  282. }
  283. // C++11 [dcl.fct.default]p3
  284. // A default argument expression [...] shall not be specified for a
  285. // parameter pack.
  286. if (Param->isParameterPack()) {
  287. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  288. << DefaultArg->getSourceRange();
  289. return;
  290. }
  291. // Check that the default argument is well-formed
  292. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  293. if (DefaultArgChecker.Visit(DefaultArg)) {
  294. Param->setInvalidDecl();
  295. return;
  296. }
  297. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  298. }
  299. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  300. /// argument for a function parameter, but we can't parse it yet
  301. /// because we're inside a class definition. Note that this default
  302. /// argument will be parsed later.
  303. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  304. SourceLocation EqualLoc,
  305. SourceLocation ArgLoc) {
  306. if (!param)
  307. return;
  308. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  309. Param->setUnparsedDefaultArg();
  310. UnparsedDefaultArgLocs[Param] = ArgLoc;
  311. }
  312. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  313. /// the default argument for the parameter param failed.
  314. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  315. SourceLocation EqualLoc) {
  316. if (!param)
  317. return;
  318. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  319. Param->setInvalidDecl();
  320. UnparsedDefaultArgLocs.erase(Param);
  321. Param->setDefaultArg(new(Context)
  322. OpaqueValueExpr(EqualLoc,
  323. Param->getType().getNonReferenceType(),
  324. VK_RValue));
  325. }
  326. /// CheckExtraCXXDefaultArguments - Check for any extra default
  327. /// arguments in the declarator, which is not a function declaration
  328. /// or definition and therefore is not permitted to have default
  329. /// arguments. This routine should be invoked for every declarator
  330. /// that is not a function declaration or definition.
  331. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  332. // C++ [dcl.fct.default]p3
  333. // A default argument expression shall be specified only in the
  334. // parameter-declaration-clause of a function declaration or in a
  335. // template-parameter (14.1). It shall not be specified for a
  336. // parameter pack. If it is specified in a
  337. // parameter-declaration-clause, it shall not occur within a
  338. // declarator or abstract-declarator of a parameter-declaration.
  339. bool MightBeFunction = D.isFunctionDeclarationContext();
  340. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  341. DeclaratorChunk &chunk = D.getTypeObject(i);
  342. if (chunk.Kind == DeclaratorChunk::Function) {
  343. if (MightBeFunction) {
  344. // This is a function declaration. It can have default arguments, but
  345. // keep looking in case its return type is a function type with default
  346. // arguments.
  347. MightBeFunction = false;
  348. continue;
  349. }
  350. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  351. ++argIdx) {
  352. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  353. if (Param->hasUnparsedDefaultArg()) {
  354. std::unique_ptr<CachedTokens> Toks =
  355. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  356. SourceRange SR;
  357. if (Toks->size() > 1)
  358. SR = SourceRange((*Toks)[1].getLocation(),
  359. Toks->back().getLocation());
  360. else
  361. SR = UnparsedDefaultArgLocs[Param];
  362. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  363. << SR;
  364. } else if (Param->getDefaultArg()) {
  365. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  366. << Param->getDefaultArg()->getSourceRange();
  367. Param->setDefaultArg(nullptr);
  368. }
  369. }
  370. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  371. MightBeFunction = false;
  372. }
  373. }
  374. }
  375. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  376. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  377. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  378. if (!PVD->hasDefaultArg())
  379. return false;
  380. if (!PVD->hasInheritedDefaultArg())
  381. return true;
  382. }
  383. return false;
  384. }
  385. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  386. /// function, once we already know that they have the same
  387. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  388. /// error, false otherwise.
  389. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  390. Scope *S) {
  391. bool Invalid = false;
  392. // The declaration context corresponding to the scope is the semantic
  393. // parent, unless this is a local function declaration, in which case
  394. // it is that surrounding function.
  395. DeclContext *ScopeDC = New->isLocalExternDecl()
  396. ? New->getLexicalDeclContext()
  397. : New->getDeclContext();
  398. // Find the previous declaration for the purpose of default arguments.
  399. FunctionDecl *PrevForDefaultArgs = Old;
  400. for (/**/; PrevForDefaultArgs;
  401. // Don't bother looking back past the latest decl if this is a local
  402. // extern declaration; nothing else could work.
  403. PrevForDefaultArgs = New->isLocalExternDecl()
  404. ? nullptr
  405. : PrevForDefaultArgs->getPreviousDecl()) {
  406. // Ignore hidden declarations.
  407. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  408. continue;
  409. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  410. !New->isCXXClassMember()) {
  411. // Ignore default arguments of old decl if they are not in
  412. // the same scope and this is not an out-of-line definition of
  413. // a member function.
  414. continue;
  415. }
  416. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  417. // If only one of these is a local function declaration, then they are
  418. // declared in different scopes, even though isDeclInScope may think
  419. // they're in the same scope. (If both are local, the scope check is
  420. // sufficient, and if neither is local, then they are in the same scope.)
  421. continue;
  422. }
  423. // We found the right previous declaration.
  424. break;
  425. }
  426. // C++ [dcl.fct.default]p4:
  427. // For non-template functions, default arguments can be added in
  428. // later declarations of a function in the same
  429. // scope. Declarations in different scopes have completely
  430. // distinct sets of default arguments. That is, declarations in
  431. // inner scopes do not acquire default arguments from
  432. // declarations in outer scopes, and vice versa. In a given
  433. // function declaration, all parameters subsequent to a
  434. // parameter with a default argument shall have default
  435. // arguments supplied in this or previous declarations. A
  436. // default argument shall not be redefined by a later
  437. // declaration (not even to the same value).
  438. //
  439. // C++ [dcl.fct.default]p6:
  440. // Except for member functions of class templates, the default arguments
  441. // in a member function definition that appears outside of the class
  442. // definition are added to the set of default arguments provided by the
  443. // member function declaration in the class definition.
  444. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  445. ? PrevForDefaultArgs->getNumParams()
  446. : 0;
  447. p < NumParams; ++p) {
  448. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  449. ParmVarDecl *NewParam = New->getParamDecl(p);
  450. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  451. bool NewParamHasDfl = NewParam->hasDefaultArg();
  452. if (OldParamHasDfl && NewParamHasDfl) {
  453. unsigned DiagDefaultParamID =
  454. diag::err_param_default_argument_redefinition;
  455. // MSVC accepts that default parameters be redefined for member functions
  456. // of template class. The new default parameter's value is ignored.
  457. Invalid = true;
  458. if (getLangOpts().MicrosoftExt) {
  459. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  460. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  461. // Merge the old default argument into the new parameter.
  462. NewParam->setHasInheritedDefaultArg();
  463. if (OldParam->hasUninstantiatedDefaultArg())
  464. NewParam->setUninstantiatedDefaultArg(
  465. OldParam->getUninstantiatedDefaultArg());
  466. else
  467. NewParam->setDefaultArg(OldParam->getInit());
  468. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  469. Invalid = false;
  470. }
  471. }
  472. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  473. // hint here. Alternatively, we could walk the type-source information
  474. // for NewParam to find the last source location in the type... but it
  475. // isn't worth the effort right now. This is the kind of test case that
  476. // is hard to get right:
  477. // int f(int);
  478. // void g(int (*fp)(int) = f);
  479. // void g(int (*fp)(int) = &f);
  480. Diag(NewParam->getLocation(), DiagDefaultParamID)
  481. << NewParam->getDefaultArgRange();
  482. // Look for the function declaration where the default argument was
  483. // actually written, which may be a declaration prior to Old.
  484. for (auto Older = PrevForDefaultArgs;
  485. OldParam->hasInheritedDefaultArg(); /**/) {
  486. Older = Older->getPreviousDecl();
  487. OldParam = Older->getParamDecl(p);
  488. }
  489. Diag(OldParam->getLocation(), diag::note_previous_definition)
  490. << OldParam->getDefaultArgRange();
  491. } else if (OldParamHasDfl) {
  492. // Merge the old default argument into the new parameter unless the new
  493. // function is a friend declaration in a template class. In the latter
  494. // case the default arguments will be inherited when the friend
  495. // declaration will be instantiated.
  496. if (New->getFriendObjectKind() == Decl::FOK_None ||
  497. !New->getLexicalDeclContext()->isDependentContext()) {
  498. // It's important to use getInit() here; getDefaultArg()
  499. // strips off any top-level ExprWithCleanups.
  500. NewParam->setHasInheritedDefaultArg();
  501. if (OldParam->hasUnparsedDefaultArg())
  502. NewParam->setUnparsedDefaultArg();
  503. else if (OldParam->hasUninstantiatedDefaultArg())
  504. NewParam->setUninstantiatedDefaultArg(
  505. OldParam->getUninstantiatedDefaultArg());
  506. else
  507. NewParam->setDefaultArg(OldParam->getInit());
  508. }
  509. } else if (NewParamHasDfl) {
  510. if (New->getDescribedFunctionTemplate()) {
  511. // Paragraph 4, quoted above, only applies to non-template functions.
  512. Diag(NewParam->getLocation(),
  513. diag::err_param_default_argument_template_redecl)
  514. << NewParam->getDefaultArgRange();
  515. Diag(PrevForDefaultArgs->getLocation(),
  516. diag::note_template_prev_declaration)
  517. << false;
  518. } else if (New->getTemplateSpecializationKind()
  519. != TSK_ImplicitInstantiation &&
  520. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  521. // C++ [temp.expr.spec]p21:
  522. // Default function arguments shall not be specified in a declaration
  523. // or a definition for one of the following explicit specializations:
  524. // - the explicit specialization of a function template;
  525. // - the explicit specialization of a member function template;
  526. // - the explicit specialization of a member function of a class
  527. // template where the class template specialization to which the
  528. // member function specialization belongs is implicitly
  529. // instantiated.
  530. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  531. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  532. << New->getDeclName()
  533. << NewParam->getDefaultArgRange();
  534. } else if (New->getDeclContext()->isDependentContext()) {
  535. // C++ [dcl.fct.default]p6 (DR217):
  536. // Default arguments for a member function of a class template shall
  537. // be specified on the initial declaration of the member function
  538. // within the class template.
  539. //
  540. // Reading the tea leaves a bit in DR217 and its reference to DR205
  541. // leads me to the conclusion that one cannot add default function
  542. // arguments for an out-of-line definition of a member function of a
  543. // dependent type.
  544. int WhichKind = 2;
  545. if (CXXRecordDecl *Record
  546. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  547. if (Record->getDescribedClassTemplate())
  548. WhichKind = 0;
  549. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  550. WhichKind = 1;
  551. else
  552. WhichKind = 2;
  553. }
  554. Diag(NewParam->getLocation(),
  555. diag::err_param_default_argument_member_template_redecl)
  556. << WhichKind
  557. << NewParam->getDefaultArgRange();
  558. }
  559. }
  560. }
  561. // DR1344: If a default argument is added outside a class definition and that
  562. // default argument makes the function a special member function, the program
  563. // is ill-formed. This can only happen for constructors.
  564. if (isa<CXXConstructorDecl>(New) &&
  565. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  566. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  567. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  568. if (NewSM != OldSM) {
  569. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  570. assert(NewParam->hasDefaultArg());
  571. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  572. << NewParam->getDefaultArgRange() << NewSM;
  573. Diag(Old->getLocation(), diag::note_previous_declaration);
  574. }
  575. }
  576. const FunctionDecl *Def;
  577. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  578. // template has a constexpr specifier then all its declarations shall
  579. // contain the constexpr specifier.
  580. if (New->isConstexpr() != Old->isConstexpr()) {
  581. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  582. << New << New->isConstexpr();
  583. Diag(Old->getLocation(), diag::note_previous_declaration);
  584. Invalid = true;
  585. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  586. Old->isDefined(Def) &&
  587. // If a friend function is inlined but does not have 'inline'
  588. // specifier, it is a definition. Do not report attribute conflict
  589. // in this case, redefinition will be diagnosed later.
  590. (New->isInlineSpecified() ||
  591. New->getFriendObjectKind() == Decl::FOK_None)) {
  592. // C++11 [dcl.fcn.spec]p4:
  593. // If the definition of a function appears in a translation unit before its
  594. // first declaration as inline, the program is ill-formed.
  595. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  596. Diag(Def->getLocation(), diag::note_previous_definition);
  597. Invalid = true;
  598. }
  599. // FIXME: It's not clear what should happen if multiple declarations of a
  600. // deduction guide have different explicitness. For now at least we simply
  601. // reject any case where the explicitness changes.
  602. auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
  603. if (NewGuide && NewGuide->isExplicitSpecified() !=
  604. cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
  605. Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
  606. << NewGuide->isExplicitSpecified();
  607. Diag(Old->getLocation(), diag::note_previous_declaration);
  608. }
  609. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  610. // argument expression, that declaration shall be a definition and shall be
  611. // the only declaration of the function or function template in the
  612. // translation unit.
  613. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  614. functionDeclHasDefaultArgument(Old)) {
  615. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  616. Diag(Old->getLocation(), diag::note_previous_declaration);
  617. Invalid = true;
  618. }
  619. return Invalid;
  620. }
  621. NamedDecl *
  622. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  623. MultiTemplateParamsArg TemplateParamLists) {
  624. assert(D.isDecompositionDeclarator());
  625. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  626. // The syntax only allows a decomposition declarator as a simple-declaration,
  627. // a for-range-declaration, or a condition in Clang, but we parse it in more
  628. // cases than that.
  629. if (!D.mayHaveDecompositionDeclarator()) {
  630. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  631. << Decomp.getSourceRange();
  632. return nullptr;
  633. }
  634. if (!TemplateParamLists.empty()) {
  635. // FIXME: There's no rule against this, but there are also no rules that
  636. // would actually make it usable, so we reject it for now.
  637. Diag(TemplateParamLists.front()->getTemplateLoc(),
  638. diag::err_decomp_decl_template);
  639. return nullptr;
  640. }
  641. Diag(Decomp.getLSquareLoc(),
  642. !getLangOpts().CPlusPlus17
  643. ? diag::ext_decomp_decl
  644. : D.getContext() == DeclaratorContext::ConditionContext
  645. ? diag::ext_decomp_decl_cond
  646. : diag::warn_cxx14_compat_decomp_decl)
  647. << Decomp.getSourceRange();
  648. // The semantic context is always just the current context.
  649. DeclContext *const DC = CurContext;
  650. // C++1z [dcl.dcl]/8:
  651. // The decl-specifier-seq shall contain only the type-specifier auto
  652. // and cv-qualifiers.
  653. auto &DS = D.getDeclSpec();
  654. {
  655. SmallVector<StringRef, 8> BadSpecifiers;
  656. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  657. if (auto SCS = DS.getStorageClassSpec()) {
  658. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  659. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  660. }
  661. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  662. BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  663. BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  664. }
  665. if (DS.isConstexprSpecified()) {
  666. BadSpecifiers.push_back("constexpr");
  667. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  668. }
  669. if (DS.isInlineSpecified()) {
  670. BadSpecifiers.push_back("inline");
  671. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  672. }
  673. if (!BadSpecifiers.empty()) {
  674. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  675. Err << (int)BadSpecifiers.size()
  676. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  677. // Don't add FixItHints to remove the specifiers; we do still respect
  678. // them when building the underlying variable.
  679. for (auto Loc : BadSpecifierLocs)
  680. Err << SourceRange(Loc, Loc);
  681. }
  682. // We can't recover from it being declared as a typedef.
  683. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  684. return nullptr;
  685. }
  686. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  687. QualType R = TInfo->getType();
  688. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  689. UPPC_DeclarationType))
  690. D.setInvalidType();
  691. // The syntax only allows a single ref-qualifier prior to the decomposition
  692. // declarator. No other declarator chunks are permitted. Also check the type
  693. // specifier here.
  694. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  695. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  696. (D.getNumTypeObjects() == 1 &&
  697. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  698. Diag(Decomp.getLSquareLoc(),
  699. (D.hasGroupingParens() ||
  700. (D.getNumTypeObjects() &&
  701. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  702. ? diag::err_decomp_decl_parens
  703. : diag::err_decomp_decl_type)
  704. << R;
  705. // In most cases, there's no actual problem with an explicitly-specified
  706. // type, but a function type won't work here, and ActOnVariableDeclarator
  707. // shouldn't be called for such a type.
  708. if (R->isFunctionType())
  709. D.setInvalidType();
  710. }
  711. // Build the BindingDecls.
  712. SmallVector<BindingDecl*, 8> Bindings;
  713. // Build the BindingDecls.
  714. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  715. // Check for name conflicts.
  716. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  717. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  718. ForVisibleRedeclaration);
  719. LookupName(Previous, S,
  720. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  721. // It's not permitted to shadow a template parameter name.
  722. if (Previous.isSingleResult() &&
  723. Previous.getFoundDecl()->isTemplateParameter()) {
  724. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  725. Previous.getFoundDecl());
  726. Previous.clear();
  727. }
  728. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  729. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  730. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  731. /*AllowInlineNamespace*/false);
  732. if (!Previous.empty()) {
  733. auto *Old = Previous.getRepresentativeDecl();
  734. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  735. Diag(Old->getLocation(), diag::note_previous_definition);
  736. }
  737. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  738. PushOnScopeChains(BD, S, true);
  739. Bindings.push_back(BD);
  740. ParsingInitForAutoVars.insert(BD);
  741. }
  742. // There are no prior lookup results for the variable itself, because it
  743. // is unnamed.
  744. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  745. Decomp.getLSquareLoc());
  746. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  747. ForVisibleRedeclaration);
  748. // Build the variable that holds the non-decomposed object.
  749. bool AddToScope = true;
  750. NamedDecl *New =
  751. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  752. MultiTemplateParamsArg(), AddToScope, Bindings);
  753. if (AddToScope) {
  754. S->AddDecl(New);
  755. CurContext->addHiddenDecl(New);
  756. }
  757. if (isInOpenMPDeclareTargetContext())
  758. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  759. return New;
  760. }
  761. static bool checkSimpleDecomposition(
  762. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  763. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  764. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  765. if ((int64_t)Bindings.size() != NumElems) {
  766. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  767. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  768. << (NumElems < Bindings.size());
  769. return true;
  770. }
  771. unsigned I = 0;
  772. for (auto *B : Bindings) {
  773. SourceLocation Loc = B->getLocation();
  774. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  775. if (E.isInvalid())
  776. return true;
  777. E = GetInit(Loc, E.get(), I++);
  778. if (E.isInvalid())
  779. return true;
  780. B->setBinding(ElemType, E.get());
  781. }
  782. return false;
  783. }
  784. static bool checkArrayLikeDecomposition(Sema &S,
  785. ArrayRef<BindingDecl *> Bindings,
  786. ValueDecl *Src, QualType DecompType,
  787. const llvm::APSInt &NumElems,
  788. QualType ElemType) {
  789. return checkSimpleDecomposition(
  790. S, Bindings, Src, DecompType, NumElems, ElemType,
  791. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  792. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  793. if (E.isInvalid())
  794. return ExprError();
  795. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  796. });
  797. }
  798. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  799. ValueDecl *Src, QualType DecompType,
  800. const ConstantArrayType *CAT) {
  801. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  802. llvm::APSInt(CAT->getSize()),
  803. CAT->getElementType());
  804. }
  805. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  806. ValueDecl *Src, QualType DecompType,
  807. const VectorType *VT) {
  808. return checkArrayLikeDecomposition(
  809. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  810. S.Context.getQualifiedType(VT->getElementType(),
  811. DecompType.getQualifiers()));
  812. }
  813. static bool checkComplexDecomposition(Sema &S,
  814. ArrayRef<BindingDecl *> Bindings,
  815. ValueDecl *Src, QualType DecompType,
  816. const ComplexType *CT) {
  817. return checkSimpleDecomposition(
  818. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  819. S.Context.getQualifiedType(CT->getElementType(),
  820. DecompType.getQualifiers()),
  821. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  822. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  823. });
  824. }
  825. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  826. TemplateArgumentListInfo &Args) {
  827. SmallString<128> SS;
  828. llvm::raw_svector_ostream OS(SS);
  829. bool First = true;
  830. for (auto &Arg : Args.arguments()) {
  831. if (!First)
  832. OS << ", ";
  833. Arg.getArgument().print(PrintingPolicy, OS);
  834. First = false;
  835. }
  836. return OS.str();
  837. }
  838. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  839. SourceLocation Loc, StringRef Trait,
  840. TemplateArgumentListInfo &Args,
  841. unsigned DiagID) {
  842. auto DiagnoseMissing = [&] {
  843. if (DiagID)
  844. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  845. Args);
  846. return true;
  847. };
  848. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  849. NamespaceDecl *Std = S.getStdNamespace();
  850. if (!Std)
  851. return DiagnoseMissing();
  852. // Look up the trait itself, within namespace std. We can diagnose various
  853. // problems with this lookup even if we've been asked to not diagnose a
  854. // missing specialization, because this can only fail if the user has been
  855. // declaring their own names in namespace std or we don't support the
  856. // standard library implementation in use.
  857. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  858. Loc, Sema::LookupOrdinaryName);
  859. if (!S.LookupQualifiedName(Result, Std))
  860. return DiagnoseMissing();
  861. if (Result.isAmbiguous())
  862. return true;
  863. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  864. if (!TraitTD) {
  865. Result.suppressDiagnostics();
  866. NamedDecl *Found = *Result.begin();
  867. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  868. S.Diag(Found->getLocation(), diag::note_declared_at);
  869. return true;
  870. }
  871. // Build the template-id.
  872. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  873. if (TraitTy.isNull())
  874. return true;
  875. if (!S.isCompleteType(Loc, TraitTy)) {
  876. if (DiagID)
  877. S.RequireCompleteType(
  878. Loc, TraitTy, DiagID,
  879. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  880. return true;
  881. }
  882. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  883. assert(RD && "specialization of class template is not a class?");
  884. // Look up the member of the trait type.
  885. S.LookupQualifiedName(TraitMemberLookup, RD);
  886. return TraitMemberLookup.isAmbiguous();
  887. }
  888. static TemplateArgumentLoc
  889. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  890. uint64_t I) {
  891. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  892. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  893. }
  894. static TemplateArgumentLoc
  895. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  896. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  897. }
  898. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  899. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  900. llvm::APSInt &Size) {
  901. EnterExpressionEvaluationContext ContextRAII(
  902. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  903. DeclarationName Value = S.PP.getIdentifierInfo("value");
  904. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  905. // Form template argument list for tuple_size<T>.
  906. TemplateArgumentListInfo Args(Loc, Loc);
  907. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  908. // If there's no tuple_size specialization, it's not tuple-like.
  909. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
  910. return IsTupleLike::NotTupleLike;
  911. // If we get this far, we've committed to the tuple interpretation, but
  912. // we can still fail if there actually isn't a usable ::value.
  913. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  914. LookupResult &R;
  915. TemplateArgumentListInfo &Args;
  916. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  917. : R(R), Args(Args) {}
  918. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  919. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  920. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  921. }
  922. } Diagnoser(R, Args);
  923. if (R.empty()) {
  924. Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
  925. return IsTupleLike::Error;
  926. }
  927. ExprResult E =
  928. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  929. if (E.isInvalid())
  930. return IsTupleLike::Error;
  931. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  932. if (E.isInvalid())
  933. return IsTupleLike::Error;
  934. return IsTupleLike::TupleLike;
  935. }
  936. /// \return std::tuple_element<I, T>::type.
  937. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  938. unsigned I, QualType T) {
  939. // Form template argument list for tuple_element<I, T>.
  940. TemplateArgumentListInfo Args(Loc, Loc);
  941. Args.addArgument(
  942. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  943. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  944. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  945. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  946. if (lookupStdTypeTraitMember(
  947. S, R, Loc, "tuple_element", Args,
  948. diag::err_decomp_decl_std_tuple_element_not_specialized))
  949. return QualType();
  950. auto *TD = R.getAsSingle<TypeDecl>();
  951. if (!TD) {
  952. R.suppressDiagnostics();
  953. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  954. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  955. if (!R.empty())
  956. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  957. return QualType();
  958. }
  959. return S.Context.getTypeDeclType(TD);
  960. }
  961. namespace {
  962. struct BindingDiagnosticTrap {
  963. Sema &S;
  964. DiagnosticErrorTrap Trap;
  965. BindingDecl *BD;
  966. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  967. : S(S), Trap(S.Diags), BD(BD) {}
  968. ~BindingDiagnosticTrap() {
  969. if (Trap.hasErrorOccurred())
  970. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  971. }
  972. };
  973. }
  974. static bool checkTupleLikeDecomposition(Sema &S,
  975. ArrayRef<BindingDecl *> Bindings,
  976. VarDecl *Src, QualType DecompType,
  977. const llvm::APSInt &TupleSize) {
  978. if ((int64_t)Bindings.size() != TupleSize) {
  979. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  980. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  981. << (TupleSize < Bindings.size());
  982. return true;
  983. }
  984. if (Bindings.empty())
  985. return false;
  986. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  987. // [dcl.decomp]p3:
  988. // The unqualified-id get is looked up in the scope of E by class member
  989. // access lookup ...
  990. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  991. bool UseMemberGet = false;
  992. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  993. if (auto *RD = DecompType->getAsCXXRecordDecl())
  994. S.LookupQualifiedName(MemberGet, RD);
  995. if (MemberGet.isAmbiguous())
  996. return true;
  997. // ... and if that finds at least one declaration that is a function
  998. // template whose first template parameter is a non-type parameter ...
  999. for (NamedDecl *D : MemberGet) {
  1000. if (FunctionTemplateDecl *FTD =
  1001. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1002. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1003. if (TPL->size() != 0 &&
  1004. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1005. // ... the initializer is e.get<i>().
  1006. UseMemberGet = true;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. S.FilterAcceptableTemplateNames(MemberGet);
  1012. }
  1013. unsigned I = 0;
  1014. for (auto *B : Bindings) {
  1015. BindingDiagnosticTrap Trap(S, B);
  1016. SourceLocation Loc = B->getLocation();
  1017. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1018. if (E.isInvalid())
  1019. return true;
  1020. // e is an lvalue if the type of the entity is an lvalue reference and
  1021. // an xvalue otherwise
  1022. if (!Src->getType()->isLValueReferenceType())
  1023. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1024. E.get(), nullptr, VK_XValue);
  1025. TemplateArgumentListInfo Args(Loc, Loc);
  1026. Args.addArgument(
  1027. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1028. if (UseMemberGet) {
  1029. // if [lookup of member get] finds at least one declaration, the
  1030. // initializer is e.get<i-1>().
  1031. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1032. CXXScopeSpec(), SourceLocation(), nullptr,
  1033. MemberGet, &Args, nullptr);
  1034. if (E.isInvalid())
  1035. return true;
  1036. E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
  1037. } else {
  1038. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1039. // in the associated namespaces.
  1040. Expr *Get = UnresolvedLookupExpr::Create(
  1041. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1042. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1043. UnresolvedSetIterator(), UnresolvedSetIterator());
  1044. Expr *Arg = E.get();
  1045. E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
  1046. }
  1047. if (E.isInvalid())
  1048. return true;
  1049. Expr *Init = E.get();
  1050. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1051. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1052. if (T.isNull())
  1053. return true;
  1054. // each vi is a variable of type "reference to T" initialized with the
  1055. // initializer, where the reference is an lvalue reference if the
  1056. // initializer is an lvalue and an rvalue reference otherwise
  1057. QualType RefType =
  1058. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1059. if (RefType.isNull())
  1060. return true;
  1061. auto *RefVD = VarDecl::Create(
  1062. S.Context, Src->getDeclContext(), Loc, Loc,
  1063. B->getDeclName().getAsIdentifierInfo(), RefType,
  1064. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1065. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1066. RefVD->setTSCSpec(Src->getTSCSpec());
  1067. RefVD->setImplicit();
  1068. if (Src->isInlineSpecified())
  1069. RefVD->setInlineSpecified();
  1070. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1071. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1072. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1073. InitializationSequence Seq(S, Entity, Kind, Init);
  1074. E = Seq.Perform(S, Entity, Kind, Init);
  1075. if (E.isInvalid())
  1076. return true;
  1077. E = S.ActOnFinishFullExpr(E.get(), Loc);
  1078. if (E.isInvalid())
  1079. return true;
  1080. RefVD->setInit(E.get());
  1081. RefVD->checkInitIsICE();
  1082. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1083. DeclarationNameInfo(B->getDeclName(), Loc),
  1084. RefVD);
  1085. if (E.isInvalid())
  1086. return true;
  1087. B->setBinding(T, E.get());
  1088. I++;
  1089. }
  1090. return false;
  1091. }
  1092. /// Find the base class to decompose in a built-in decomposition of a class type.
  1093. /// This base class search is, unfortunately, not quite like any other that we
  1094. /// perform anywhere else in C++.
  1095. static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
  1096. SourceLocation Loc,
  1097. const CXXRecordDecl *RD,
  1098. CXXCastPath &BasePath) {
  1099. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1100. CXXBasePath &Path) {
  1101. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1102. };
  1103. const CXXRecordDecl *ClassWithFields = nullptr;
  1104. if (RD->hasDirectFields())
  1105. // [dcl.decomp]p4:
  1106. // Otherwise, all of E's non-static data members shall be public direct
  1107. // members of E ...
  1108. ClassWithFields = RD;
  1109. else {
  1110. // ... or of ...
  1111. CXXBasePaths Paths;
  1112. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1113. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1114. // If no classes have fields, just decompose RD itself. (This will work
  1115. // if and only if zero bindings were provided.)
  1116. return RD;
  1117. }
  1118. CXXBasePath *BestPath = nullptr;
  1119. for (auto &P : Paths) {
  1120. if (!BestPath)
  1121. BestPath = &P;
  1122. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1123. BestPath->back().Base->getType())) {
  1124. // ... the same ...
  1125. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1126. << false << RD << BestPath->back().Base->getType()
  1127. << P.back().Base->getType();
  1128. return nullptr;
  1129. } else if (P.Access < BestPath->Access) {
  1130. BestPath = &P;
  1131. }
  1132. }
  1133. // ... unambiguous ...
  1134. QualType BaseType = BestPath->back().Base->getType();
  1135. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1136. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1137. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1138. return nullptr;
  1139. }
  1140. // ... public base class of E.
  1141. if (BestPath->Access != AS_public) {
  1142. S.Diag(Loc, diag::err_decomp_decl_non_public_base)
  1143. << RD << BaseType;
  1144. for (auto &BS : *BestPath) {
  1145. if (BS.Base->getAccessSpecifier() != AS_public) {
  1146. S.Diag(BS.Base->getBeginLoc(), diag::note_access_constrained_by_path)
  1147. << (BS.Base->getAccessSpecifier() == AS_protected)
  1148. << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
  1149. break;
  1150. }
  1151. }
  1152. return nullptr;
  1153. }
  1154. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1155. S.BuildBasePathArray(Paths, BasePath);
  1156. }
  1157. // The above search did not check whether the selected class itself has base
  1158. // classes with fields, so check that now.
  1159. CXXBasePaths Paths;
  1160. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1161. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1162. << (ClassWithFields == RD) << RD << ClassWithFields
  1163. << Paths.front().back().Base->getType();
  1164. return nullptr;
  1165. }
  1166. return ClassWithFields;
  1167. }
  1168. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1169. ValueDecl *Src, QualType DecompType,
  1170. const CXXRecordDecl *RD) {
  1171. CXXCastPath BasePath;
  1172. RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
  1173. if (!RD)
  1174. return true;
  1175. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1176. DecompType.getQualifiers());
  1177. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1178. unsigned NumFields =
  1179. std::count_if(RD->field_begin(), RD->field_end(),
  1180. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1181. assert(Bindings.size() != NumFields);
  1182. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1183. << DecompType << (unsigned)Bindings.size() << NumFields
  1184. << (NumFields < Bindings.size());
  1185. return true;
  1186. };
  1187. // all of E's non-static data members shall be public [...] members,
  1188. // E shall not have an anonymous union member, ...
  1189. unsigned I = 0;
  1190. for (auto *FD : RD->fields()) {
  1191. if (FD->isUnnamedBitfield())
  1192. continue;
  1193. if (FD->isAnonymousStructOrUnion()) {
  1194. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1195. << DecompType << FD->getType()->isUnionType();
  1196. S.Diag(FD->getLocation(), diag::note_declared_at);
  1197. return true;
  1198. }
  1199. // We have a real field to bind.
  1200. if (I >= Bindings.size())
  1201. return DiagnoseBadNumberOfBindings();
  1202. auto *B = Bindings[I++];
  1203. SourceLocation Loc = B->getLocation();
  1204. if (FD->getAccess() != AS_public) {
  1205. S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
  1206. // Determine whether the access specifier was explicit.
  1207. bool Implicit = true;
  1208. for (const auto *D : RD->decls()) {
  1209. if (declaresSameEntity(D, FD))
  1210. break;
  1211. if (isa<AccessSpecDecl>(D)) {
  1212. Implicit = false;
  1213. break;
  1214. }
  1215. }
  1216. S.Diag(FD->getLocation(), diag::note_access_natural)
  1217. << (FD->getAccess() == AS_protected) << Implicit;
  1218. return true;
  1219. }
  1220. // Initialize the binding to Src.FD.
  1221. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1222. if (E.isInvalid())
  1223. return true;
  1224. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1225. VK_LValue, &BasePath);
  1226. if (E.isInvalid())
  1227. return true;
  1228. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1229. CXXScopeSpec(), FD,
  1230. DeclAccessPair::make(FD, FD->getAccess()),
  1231. DeclarationNameInfo(FD->getDeclName(), Loc));
  1232. if (E.isInvalid())
  1233. return true;
  1234. // If the type of the member is T, the referenced type is cv T, where cv is
  1235. // the cv-qualification of the decomposition expression.
  1236. //
  1237. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1238. // 'const' to the type of the field.
  1239. Qualifiers Q = DecompType.getQualifiers();
  1240. if (FD->isMutable())
  1241. Q.removeConst();
  1242. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1243. }
  1244. if (I != Bindings.size())
  1245. return DiagnoseBadNumberOfBindings();
  1246. return false;
  1247. }
  1248. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1249. QualType DecompType = DD->getType();
  1250. // If the type of the decomposition is dependent, then so is the type of
  1251. // each binding.
  1252. if (DecompType->isDependentType()) {
  1253. for (auto *B : DD->bindings())
  1254. B->setType(Context.DependentTy);
  1255. return;
  1256. }
  1257. DecompType = DecompType.getNonReferenceType();
  1258. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1259. // C++1z [dcl.decomp]/2:
  1260. // If E is an array type [...]
  1261. // As an extension, we also support decomposition of built-in complex and
  1262. // vector types.
  1263. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1264. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1265. DD->setInvalidDecl();
  1266. return;
  1267. }
  1268. if (auto *VT = DecompType->getAs<VectorType>()) {
  1269. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1270. DD->setInvalidDecl();
  1271. return;
  1272. }
  1273. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1274. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1275. DD->setInvalidDecl();
  1276. return;
  1277. }
  1278. // C++1z [dcl.decomp]/3:
  1279. // if the expression std::tuple_size<E>::value is a well-formed integral
  1280. // constant expression, [...]
  1281. llvm::APSInt TupleSize(32);
  1282. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1283. case IsTupleLike::Error:
  1284. DD->setInvalidDecl();
  1285. return;
  1286. case IsTupleLike::TupleLike:
  1287. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1288. DD->setInvalidDecl();
  1289. return;
  1290. case IsTupleLike::NotTupleLike:
  1291. break;
  1292. }
  1293. // C++1z [dcl.dcl]/8:
  1294. // [E shall be of array or non-union class type]
  1295. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1296. if (!RD || RD->isUnion()) {
  1297. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1298. << DD << !RD << DecompType;
  1299. DD->setInvalidDecl();
  1300. return;
  1301. }
  1302. // C++1z [dcl.decomp]/4:
  1303. // all of E's non-static data members shall be [...] direct members of
  1304. // E or of the same unambiguous public base class of E, ...
  1305. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1306. DD->setInvalidDecl();
  1307. }
  1308. /// Merge the exception specifications of two variable declarations.
  1309. ///
  1310. /// This is called when there's a redeclaration of a VarDecl. The function
  1311. /// checks if the redeclaration might have an exception specification and
  1312. /// validates compatibility and merges the specs if necessary.
  1313. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1314. // Shortcut if exceptions are disabled.
  1315. if (!getLangOpts().CXXExceptions)
  1316. return;
  1317. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1318. "Should only be called if types are otherwise the same.");
  1319. QualType NewType = New->getType();
  1320. QualType OldType = Old->getType();
  1321. // We're only interested in pointers and references to functions, as well
  1322. // as pointers to member functions.
  1323. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1324. NewType = R->getPointeeType();
  1325. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1326. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1327. NewType = P->getPointeeType();
  1328. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1329. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1330. NewType = M->getPointeeType();
  1331. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1332. }
  1333. if (!NewType->isFunctionProtoType())
  1334. return;
  1335. // There's lots of special cases for functions. For function pointers, system
  1336. // libraries are hopefully not as broken so that we don't need these
  1337. // workarounds.
  1338. if (CheckEquivalentExceptionSpec(
  1339. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1340. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1341. New->setInvalidDecl();
  1342. }
  1343. }
  1344. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1345. /// function declaration are well-formed according to C++
  1346. /// [dcl.fct.default].
  1347. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1348. unsigned NumParams = FD->getNumParams();
  1349. unsigned p;
  1350. // Find first parameter with a default argument
  1351. for (p = 0; p < NumParams; ++p) {
  1352. ParmVarDecl *Param = FD->getParamDecl(p);
  1353. if (Param->hasDefaultArg())
  1354. break;
  1355. }
  1356. // C++11 [dcl.fct.default]p4:
  1357. // In a given function declaration, each parameter subsequent to a parameter
  1358. // with a default argument shall have a default argument supplied in this or
  1359. // a previous declaration or shall be a function parameter pack. A default
  1360. // argument shall not be redefined by a later declaration (not even to the
  1361. // same value).
  1362. unsigned LastMissingDefaultArg = 0;
  1363. for (; p < NumParams; ++p) {
  1364. ParmVarDecl *Param = FD->getParamDecl(p);
  1365. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1366. if (Param->isInvalidDecl())
  1367. /* We already complained about this parameter. */;
  1368. else if (Param->getIdentifier())
  1369. Diag(Param->getLocation(),
  1370. diag::err_param_default_argument_missing_name)
  1371. << Param->getIdentifier();
  1372. else
  1373. Diag(Param->getLocation(),
  1374. diag::err_param_default_argument_missing);
  1375. LastMissingDefaultArg = p;
  1376. }
  1377. }
  1378. if (LastMissingDefaultArg > 0) {
  1379. // Some default arguments were missing. Clear out all of the
  1380. // default arguments up to (and including) the last missing
  1381. // default argument, so that we leave the function parameters
  1382. // in a semantically valid state.
  1383. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1384. ParmVarDecl *Param = FD->getParamDecl(p);
  1385. if (Param->hasDefaultArg()) {
  1386. Param->setDefaultArg(nullptr);
  1387. }
  1388. }
  1389. }
  1390. }
  1391. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1392. // are all literal types. If so, return true. If not, produce a suitable
  1393. // diagnostic and return false.
  1394. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1395. const FunctionDecl *FD) {
  1396. unsigned ArgIndex = 0;
  1397. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1398. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1399. e = FT->param_type_end();
  1400. i != e; ++i, ++ArgIndex) {
  1401. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1402. SourceLocation ParamLoc = PD->getLocation();
  1403. if (!(*i)->isDependentType() &&
  1404. SemaRef.RequireLiteralType(ParamLoc, *i,
  1405. diag::err_constexpr_non_literal_param,
  1406. ArgIndex+1, PD->getSourceRange(),
  1407. isa<CXXConstructorDecl>(FD)))
  1408. return false;
  1409. }
  1410. return true;
  1411. }
  1412. /// Get diagnostic %select index for tag kind for
  1413. /// record diagnostic message.
  1414. /// WARNING: Indexes apply to particular diagnostics only!
  1415. ///
  1416. /// \returns diagnostic %select index.
  1417. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1418. switch (Tag) {
  1419. case TTK_Struct: return 0;
  1420. case TTK_Interface: return 1;
  1421. case TTK_Class: return 2;
  1422. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1423. }
  1424. }
  1425. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  1426. // the requirements of a constexpr function definition or a constexpr
  1427. // constructor definition. If so, return true. If not, produce appropriate
  1428. // diagnostics and return false.
  1429. //
  1430. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1431. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  1432. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1433. if (MD && MD->isInstance()) {
  1434. // C++11 [dcl.constexpr]p4:
  1435. // The definition of a constexpr constructor shall satisfy the following
  1436. // constraints:
  1437. // - the class shall not have any virtual base classes;
  1438. const CXXRecordDecl *RD = MD->getParent();
  1439. if (RD->getNumVBases()) {
  1440. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1441. << isa<CXXConstructorDecl>(NewFD)
  1442. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1443. for (const auto &I : RD->vbases())
  1444. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1445. << I.getSourceRange();
  1446. return false;
  1447. }
  1448. }
  1449. if (!isa<CXXConstructorDecl>(NewFD)) {
  1450. // C++11 [dcl.constexpr]p3:
  1451. // The definition of a constexpr function shall satisfy the following
  1452. // constraints:
  1453. // - it shall not be virtual;
  1454. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1455. if (Method && Method->isVirtual()) {
  1456. Method = Method->getCanonicalDecl();
  1457. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1458. // If it's not obvious why this function is virtual, find an overridden
  1459. // function which uses the 'virtual' keyword.
  1460. const CXXMethodDecl *WrittenVirtual = Method;
  1461. while (!WrittenVirtual->isVirtualAsWritten())
  1462. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1463. if (WrittenVirtual != Method)
  1464. Diag(WrittenVirtual->getLocation(),
  1465. diag::note_overridden_virtual_function);
  1466. return false;
  1467. }
  1468. // - its return type shall be a literal type;
  1469. QualType RT = NewFD->getReturnType();
  1470. if (!RT->isDependentType() &&
  1471. RequireLiteralType(NewFD->getLocation(), RT,
  1472. diag::err_constexpr_non_literal_return))
  1473. return false;
  1474. }
  1475. // - each of its parameter types shall be a literal type;
  1476. if (!CheckConstexprParameterTypes(*this, NewFD))
  1477. return false;
  1478. return true;
  1479. }
  1480. /// Check the given declaration statement is legal within a constexpr function
  1481. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1482. ///
  1483. /// \return true if the body is OK (maybe only as an extension), false if we
  1484. /// have diagnosed a problem.
  1485. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1486. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  1487. // C++11 [dcl.constexpr]p3 and p4:
  1488. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1489. // contain only
  1490. for (const auto *DclIt : DS->decls()) {
  1491. switch (DclIt->getKind()) {
  1492. case Decl::StaticAssert:
  1493. case Decl::Using:
  1494. case Decl::UsingShadow:
  1495. case Decl::UsingDirective:
  1496. case Decl::UnresolvedUsingTypename:
  1497. case Decl::UnresolvedUsingValue:
  1498. // - static_assert-declarations
  1499. // - using-declarations,
  1500. // - using-directives,
  1501. continue;
  1502. case Decl::Typedef:
  1503. case Decl::TypeAlias: {
  1504. // - typedef declarations and alias-declarations that do not define
  1505. // classes or enumerations,
  1506. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1507. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1508. // Don't allow variably-modified types in constexpr functions.
  1509. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1510. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1511. << TL.getSourceRange() << TL.getType()
  1512. << isa<CXXConstructorDecl>(Dcl);
  1513. return false;
  1514. }
  1515. continue;
  1516. }
  1517. case Decl::Enum:
  1518. case Decl::CXXRecord:
  1519. // C++1y allows types to be defined, not just declared.
  1520. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  1521. SemaRef.Diag(DS->getBeginLoc(),
  1522. SemaRef.getLangOpts().CPlusPlus14
  1523. ? diag::warn_cxx11_compat_constexpr_type_definition
  1524. : diag::ext_constexpr_type_definition)
  1525. << isa<CXXConstructorDecl>(Dcl);
  1526. continue;
  1527. case Decl::EnumConstant:
  1528. case Decl::IndirectField:
  1529. case Decl::ParmVar:
  1530. // These can only appear with other declarations which are banned in
  1531. // C++11 and permitted in C++1y, so ignore them.
  1532. continue;
  1533. case Decl::Var:
  1534. case Decl::Decomposition: {
  1535. // C++1y [dcl.constexpr]p3 allows anything except:
  1536. // a definition of a variable of non-literal type or of static or
  1537. // thread storage duration or for which no initialization is performed.
  1538. const auto *VD = cast<VarDecl>(DclIt);
  1539. if (VD->isThisDeclarationADefinition()) {
  1540. if (VD->isStaticLocal()) {
  1541. SemaRef.Diag(VD->getLocation(),
  1542. diag::err_constexpr_local_var_static)
  1543. << isa<CXXConstructorDecl>(Dcl)
  1544. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1545. return false;
  1546. }
  1547. if (!VD->getType()->isDependentType() &&
  1548. SemaRef.RequireLiteralType(
  1549. VD->getLocation(), VD->getType(),
  1550. diag::err_constexpr_local_var_non_literal_type,
  1551. isa<CXXConstructorDecl>(Dcl)))
  1552. return false;
  1553. if (!VD->getType()->isDependentType() &&
  1554. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1555. SemaRef.Diag(VD->getLocation(),
  1556. diag::err_constexpr_local_var_no_init)
  1557. << isa<CXXConstructorDecl>(Dcl);
  1558. return false;
  1559. }
  1560. }
  1561. SemaRef.Diag(VD->getLocation(),
  1562. SemaRef.getLangOpts().CPlusPlus14
  1563. ? diag::warn_cxx11_compat_constexpr_local_var
  1564. : diag::ext_constexpr_local_var)
  1565. << isa<CXXConstructorDecl>(Dcl);
  1566. continue;
  1567. }
  1568. case Decl::NamespaceAlias:
  1569. case Decl::Function:
  1570. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1571. // everywhere as an extension.
  1572. if (!Cxx1yLoc.isValid())
  1573. Cxx1yLoc = DS->getBeginLoc();
  1574. continue;
  1575. default:
  1576. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1577. << isa<CXXConstructorDecl>(Dcl);
  1578. return false;
  1579. }
  1580. }
  1581. return true;
  1582. }
  1583. /// Check that the given field is initialized within a constexpr constructor.
  1584. ///
  1585. /// \param Dcl The constexpr constructor being checked.
  1586. /// \param Field The field being checked. This may be a member of an anonymous
  1587. /// struct or union nested within the class being checked.
  1588. /// \param Inits All declarations, including anonymous struct/union members and
  1589. /// indirect members, for which any initialization was provided.
  1590. /// \param Diagnosed Set to true if an error is produced.
  1591. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  1592. const FunctionDecl *Dcl,
  1593. FieldDecl *Field,
  1594. llvm::SmallSet<Decl*, 16> &Inits,
  1595. bool &Diagnosed) {
  1596. if (Field->isInvalidDecl())
  1597. return;
  1598. if (Field->isUnnamedBitfield())
  1599. return;
  1600. // Anonymous unions with no variant members and empty anonymous structs do not
  1601. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1602. // indirect fields don't need initializing.
  1603. if (Field->isAnonymousStructOrUnion() &&
  1604. (Field->getType()->isUnionType()
  1605. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1606. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1607. return;
  1608. if (!Inits.count(Field)) {
  1609. if (!Diagnosed) {
  1610. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  1611. Diagnosed = true;
  1612. }
  1613. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  1614. } else if (Field->isAnonymousStructOrUnion()) {
  1615. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1616. for (auto *I : RD->fields())
  1617. // If an anonymous union contains an anonymous struct of which any member
  1618. // is initialized, all members must be initialized.
  1619. if (!RD->isUnion() || Inits.count(I))
  1620. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  1621. }
  1622. }
  1623. /// Check the provided statement is allowed in a constexpr function
  1624. /// definition.
  1625. static bool
  1626. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1627. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1628. SourceLocation &Cxx1yLoc) {
  1629. // - its function-body shall be [...] a compound-statement that contains only
  1630. switch (S->getStmtClass()) {
  1631. case Stmt::NullStmtClass:
  1632. // - null statements,
  1633. return true;
  1634. case Stmt::DeclStmtClass:
  1635. // - static_assert-declarations
  1636. // - using-declarations,
  1637. // - using-directives,
  1638. // - typedef declarations and alias-declarations that do not define
  1639. // classes or enumerations,
  1640. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  1641. return false;
  1642. return true;
  1643. case Stmt::ReturnStmtClass:
  1644. // - and exactly one return statement;
  1645. if (isa<CXXConstructorDecl>(Dcl)) {
  1646. // C++1y allows return statements in constexpr constructors.
  1647. if (!Cxx1yLoc.isValid())
  1648. Cxx1yLoc = S->getBeginLoc();
  1649. return true;
  1650. }
  1651. ReturnStmts.push_back(S->getBeginLoc());
  1652. return true;
  1653. case Stmt::CompoundStmtClass: {
  1654. // C++1y allows compound-statements.
  1655. if (!Cxx1yLoc.isValid())
  1656. Cxx1yLoc = S->getBeginLoc();
  1657. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1658. for (auto *BodyIt : CompStmt->body()) {
  1659. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1660. Cxx1yLoc))
  1661. return false;
  1662. }
  1663. return true;
  1664. }
  1665. case Stmt::AttributedStmtClass:
  1666. if (!Cxx1yLoc.isValid())
  1667. Cxx1yLoc = S->getBeginLoc();
  1668. return true;
  1669. case Stmt::IfStmtClass: {
  1670. // C++1y allows if-statements.
  1671. if (!Cxx1yLoc.isValid())
  1672. Cxx1yLoc = S->getBeginLoc();
  1673. IfStmt *If = cast<IfStmt>(S);
  1674. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1675. Cxx1yLoc))
  1676. return false;
  1677. if (If->getElse() &&
  1678. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1679. Cxx1yLoc))
  1680. return false;
  1681. return true;
  1682. }
  1683. case Stmt::WhileStmtClass:
  1684. case Stmt::DoStmtClass:
  1685. case Stmt::ForStmtClass:
  1686. case Stmt::CXXForRangeStmtClass:
  1687. case Stmt::ContinueStmtClass:
  1688. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1689. // because they don't make sense without variable mutation.
  1690. if (!SemaRef.getLangOpts().CPlusPlus14)
  1691. break;
  1692. if (!Cxx1yLoc.isValid())
  1693. Cxx1yLoc = S->getBeginLoc();
  1694. for (Stmt *SubStmt : S->children())
  1695. if (SubStmt &&
  1696. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1697. Cxx1yLoc))
  1698. return false;
  1699. return true;
  1700. case Stmt::SwitchStmtClass:
  1701. case Stmt::CaseStmtClass:
  1702. case Stmt::DefaultStmtClass:
  1703. case Stmt::BreakStmtClass:
  1704. // C++1y allows switch-statements, and since they don't need variable
  1705. // mutation, we can reasonably allow them in C++11 as an extension.
  1706. if (!Cxx1yLoc.isValid())
  1707. Cxx1yLoc = S->getBeginLoc();
  1708. for (Stmt *SubStmt : S->children())
  1709. if (SubStmt &&
  1710. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1711. Cxx1yLoc))
  1712. return false;
  1713. return true;
  1714. default:
  1715. if (!isa<Expr>(S))
  1716. break;
  1717. // C++1y allows expression-statements.
  1718. if (!Cxx1yLoc.isValid())
  1719. Cxx1yLoc = S->getBeginLoc();
  1720. return true;
  1721. }
  1722. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1723. << isa<CXXConstructorDecl>(Dcl);
  1724. return false;
  1725. }
  1726. /// Check the body for the given constexpr function declaration only contains
  1727. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1728. ///
  1729. /// \return true if the body is OK, false if we have diagnosed a problem.
  1730. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1731. if (isa<CXXTryStmt>(Body)) {
  1732. // C++11 [dcl.constexpr]p3:
  1733. // The definition of a constexpr function shall satisfy the following
  1734. // constraints: [...]
  1735. // - its function-body shall be = delete, = default, or a
  1736. // compound-statement
  1737. //
  1738. // C++11 [dcl.constexpr]p4:
  1739. // In the definition of a constexpr constructor, [...]
  1740. // - its function-body shall not be a function-try-block;
  1741. Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
  1742. << isa<CXXConstructorDecl>(Dcl);
  1743. return false;
  1744. }
  1745. SmallVector<SourceLocation, 4> ReturnStmts;
  1746. // - its function-body shall be [...] a compound-statement that contains only
  1747. // [... list of cases ...]
  1748. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  1749. SourceLocation Cxx1yLoc;
  1750. for (auto *BodyIt : CompBody->body()) {
  1751. if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
  1752. return false;
  1753. }
  1754. if (Cxx1yLoc.isValid())
  1755. Diag(Cxx1yLoc,
  1756. getLangOpts().CPlusPlus14
  1757. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1758. : diag::ext_constexpr_body_invalid_stmt)
  1759. << isa<CXXConstructorDecl>(Dcl);
  1760. if (const CXXConstructorDecl *Constructor
  1761. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1762. const CXXRecordDecl *RD = Constructor->getParent();
  1763. // DR1359:
  1764. // - every non-variant non-static data member and base class sub-object
  1765. // shall be initialized;
  1766. // DR1460:
  1767. // - if the class is a union having variant members, exactly one of them
  1768. // shall be initialized;
  1769. if (RD->isUnion()) {
  1770. if (Constructor->getNumCtorInitializers() == 0 &&
  1771. RD->hasVariantMembers()) {
  1772. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1773. return false;
  1774. }
  1775. } else if (!Constructor->isDependentContext() &&
  1776. !Constructor->isDelegatingConstructor()) {
  1777. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1778. // Skip detailed checking if we have enough initializers, and we would
  1779. // allow at most one initializer per member.
  1780. bool AnyAnonStructUnionMembers = false;
  1781. unsigned Fields = 0;
  1782. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1783. E = RD->field_end(); I != E; ++I, ++Fields) {
  1784. if (I->isAnonymousStructOrUnion()) {
  1785. AnyAnonStructUnionMembers = true;
  1786. break;
  1787. }
  1788. }
  1789. // DR1460:
  1790. // - if the class is a union-like class, but is not a union, for each of
  1791. // its anonymous union members having variant members, exactly one of
  1792. // them shall be initialized;
  1793. if (AnyAnonStructUnionMembers ||
  1794. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1795. // Check initialization of non-static data members. Base classes are
  1796. // always initialized so do not need to be checked. Dependent bases
  1797. // might not have initializers in the member initializer list.
  1798. llvm::SmallSet<Decl*, 16> Inits;
  1799. for (const auto *I: Constructor->inits()) {
  1800. if (FieldDecl *FD = I->getMember())
  1801. Inits.insert(FD);
  1802. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1803. Inits.insert(ID->chain_begin(), ID->chain_end());
  1804. }
  1805. bool Diagnosed = false;
  1806. for (auto *I : RD->fields())
  1807. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1808. if (Diagnosed)
  1809. return false;
  1810. }
  1811. }
  1812. } else {
  1813. if (ReturnStmts.empty()) {
  1814. // C++1y doesn't require constexpr functions to contain a 'return'
  1815. // statement. We still do, unless the return type might be void, because
  1816. // otherwise if there's no return statement, the function cannot
  1817. // be used in a core constant expression.
  1818. bool OK = getLangOpts().CPlusPlus14 &&
  1819. (Dcl->getReturnType()->isVoidType() ||
  1820. Dcl->getReturnType()->isDependentType());
  1821. Diag(Dcl->getLocation(),
  1822. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1823. : diag::err_constexpr_body_no_return);
  1824. if (!OK)
  1825. return false;
  1826. } else if (ReturnStmts.size() > 1) {
  1827. Diag(ReturnStmts.back(),
  1828. getLangOpts().CPlusPlus14
  1829. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1830. : diag::ext_constexpr_body_multiple_return);
  1831. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1832. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1833. }
  1834. }
  1835. // C++11 [dcl.constexpr]p5:
  1836. // if no function argument values exist such that the function invocation
  1837. // substitution would produce a constant expression, the program is
  1838. // ill-formed; no diagnostic required.
  1839. // C++11 [dcl.constexpr]p3:
  1840. // - every constructor call and implicit conversion used in initializing the
  1841. // return value shall be one of those allowed in a constant expression.
  1842. // C++11 [dcl.constexpr]p4:
  1843. // - every constructor involved in initializing non-static data members and
  1844. // base class sub-objects shall be a constexpr constructor.
  1845. SmallVector<PartialDiagnosticAt, 8> Diags;
  1846. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1847. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1848. << isa<CXXConstructorDecl>(Dcl);
  1849. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1850. Diag(Diags[I].first, Diags[I].second);
  1851. // Don't return false here: we allow this for compatibility in
  1852. // system headers.
  1853. }
  1854. return true;
  1855. }
  1856. /// Get the class that is directly named by the current context. This is the
  1857. /// class for which an unqualified-id in this scope could name a constructor
  1858. /// or destructor.
  1859. ///
  1860. /// If the scope specifier denotes a class, this will be that class.
  1861. /// If the scope specifier is empty, this will be the class whose
  1862. /// member-specification we are currently within. Otherwise, there
  1863. /// is no such class.
  1864. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  1865. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1866. if (SS && SS->isInvalid())
  1867. return nullptr;
  1868. if (SS && SS->isNotEmpty()) {
  1869. DeclContext *DC = computeDeclContext(*SS, true);
  1870. return dyn_cast_or_null<CXXRecordDecl>(DC);
  1871. }
  1872. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1873. }
  1874. /// isCurrentClassName - Determine whether the identifier II is the
  1875. /// name of the class type currently being defined. In the case of
  1876. /// nested classes, this will only return true if II is the name of
  1877. /// the innermost class.
  1878. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  1879. const CXXScopeSpec *SS) {
  1880. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  1881. return CurDecl && &II == CurDecl->getIdentifier();
  1882. }
  1883. /// Determine whether the identifier II is a typo for the name of
  1884. /// the class type currently being defined. If so, update it to the identifier
  1885. /// that should have been used.
  1886. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1887. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1888. if (!getLangOpts().SpellChecking)
  1889. return false;
  1890. CXXRecordDecl *CurDecl;
  1891. if (SS && SS->isSet() && !SS->isInvalid()) {
  1892. DeclContext *DC = computeDeclContext(*SS, true);
  1893. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1894. } else
  1895. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1896. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1897. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1898. < II->getLength()) {
  1899. II = CurDecl->getIdentifier();
  1900. return true;
  1901. }
  1902. return false;
  1903. }
  1904. /// Determine whether the given class is a base class of the given
  1905. /// class, including looking at dependent bases.
  1906. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1907. const CXXRecordDecl *Current) {
  1908. SmallVector<const CXXRecordDecl*, 8> Queue;
  1909. Class = Class->getCanonicalDecl();
  1910. while (true) {
  1911. for (const auto &I : Current->bases()) {
  1912. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1913. if (!Base)
  1914. continue;
  1915. Base = Base->getDefinition();
  1916. if (!Base)
  1917. continue;
  1918. if (Base->getCanonicalDecl() == Class)
  1919. return true;
  1920. Queue.push_back(Base);
  1921. }
  1922. if (Queue.empty())
  1923. return false;
  1924. Current = Queue.pop_back_val();
  1925. }
  1926. return false;
  1927. }
  1928. /// Check the validity of a C++ base class specifier.
  1929. ///
  1930. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1931. /// and returns NULL otherwise.
  1932. CXXBaseSpecifier *
  1933. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1934. SourceRange SpecifierRange,
  1935. bool Virtual, AccessSpecifier Access,
  1936. TypeSourceInfo *TInfo,
  1937. SourceLocation EllipsisLoc) {
  1938. QualType BaseType = TInfo->getType();
  1939. // C++ [class.union]p1:
  1940. // A union shall not have base classes.
  1941. if (Class->isUnion()) {
  1942. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1943. << SpecifierRange;
  1944. return nullptr;
  1945. }
  1946. if (EllipsisLoc.isValid() &&
  1947. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1948. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1949. << TInfo->getTypeLoc().getSourceRange();
  1950. EllipsisLoc = SourceLocation();
  1951. }
  1952. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  1953. if (BaseType->isDependentType()) {
  1954. // Make sure that we don't have circular inheritance among our dependent
  1955. // bases. For non-dependent bases, the check for completeness below handles
  1956. // this.
  1957. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  1958. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  1959. ((BaseDecl = BaseDecl->getDefinition()) &&
  1960. findCircularInheritance(Class, BaseDecl))) {
  1961. Diag(BaseLoc, diag::err_circular_inheritance)
  1962. << BaseType << Context.getTypeDeclType(Class);
  1963. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  1964. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  1965. << BaseType;
  1966. return nullptr;
  1967. }
  1968. }
  1969. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1970. Class->getTagKind() == TTK_Class,
  1971. Access, TInfo, EllipsisLoc);
  1972. }
  1973. // Base specifiers must be record types.
  1974. if (!BaseType->isRecordType()) {
  1975. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  1976. return nullptr;
  1977. }
  1978. // C++ [class.union]p1:
  1979. // A union shall not be used as a base class.
  1980. if (BaseType->isUnionType()) {
  1981. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  1982. return nullptr;
  1983. }
  1984. // For the MS ABI, propagate DLL attributes to base class templates.
  1985. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1986. if (Attr *ClassAttr = getDLLAttr(Class)) {
  1987. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1988. BaseType->getAsCXXRecordDecl())) {
  1989. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  1990. BaseLoc);
  1991. }
  1992. }
  1993. }
  1994. // C++ [class.derived]p2:
  1995. // The class-name in a base-specifier shall not be an incompletely
  1996. // defined class.
  1997. if (RequireCompleteType(BaseLoc, BaseType,
  1998. diag::err_incomplete_base_class, SpecifierRange)) {
  1999. Class->setInvalidDecl();
  2000. return nullptr;
  2001. }
  2002. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2003. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  2004. assert(BaseDecl && "Record type has no declaration");
  2005. BaseDecl = BaseDecl->getDefinition();
  2006. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2007. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2008. assert(CXXBaseDecl && "Base type is not a C++ type");
  2009. // Microsoft docs say:
  2010. // "If a base-class has a code_seg attribute, derived classes must have the
  2011. // same attribute."
  2012. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2013. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2014. if ((DerivedCSA || BaseCSA) &&
  2015. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2016. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2017. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2018. << CXXBaseDecl;
  2019. return nullptr;
  2020. }
  2021. // A class which contains a flexible array member is not suitable for use as a
  2022. // base class:
  2023. // - If the layout determines that a base comes before another base,
  2024. // the flexible array member would index into the subsequent base.
  2025. // - If the layout determines that base comes before the derived class,
  2026. // the flexible array member would index into the derived class.
  2027. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2028. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2029. << CXXBaseDecl->getDeclName();
  2030. return nullptr;
  2031. }
  2032. // C++ [class]p3:
  2033. // If a class is marked final and it appears as a base-type-specifier in
  2034. // base-clause, the program is ill-formed.
  2035. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2036. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2037. << CXXBaseDecl->getDeclName()
  2038. << FA->isSpelledAsSealed();
  2039. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2040. << CXXBaseDecl->getDeclName() << FA->getRange();
  2041. return nullptr;
  2042. }
  2043. if (BaseDecl->isInvalidDecl())
  2044. Class->setInvalidDecl();
  2045. // Create the base specifier.
  2046. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2047. Class->getTagKind() == TTK_Class,
  2048. Access, TInfo, EllipsisLoc);
  2049. }
  2050. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2051. /// one entry in the base class list of a class specifier, for
  2052. /// example:
  2053. /// class foo : public bar, virtual private baz {
  2054. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2055. BaseResult
  2056. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2057. ParsedAttributes &Attributes,
  2058. bool Virtual, AccessSpecifier Access,
  2059. ParsedType basetype, SourceLocation BaseLoc,
  2060. SourceLocation EllipsisLoc) {
  2061. if (!classdecl)
  2062. return true;
  2063. AdjustDeclIfTemplate(classdecl);
  2064. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2065. if (!Class)
  2066. return true;
  2067. // We haven't yet attached the base specifiers.
  2068. Class->setIsParsingBaseSpecifiers();
  2069. // We do not support any C++11 attributes on base-specifiers yet.
  2070. // Diagnose any attributes we see.
  2071. for (const ParsedAttr &AL : Attributes) {
  2072. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2073. continue;
  2074. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2075. ? diag::warn_unknown_attribute_ignored
  2076. : diag::err_base_specifier_attribute)
  2077. << AL.getName();
  2078. }
  2079. TypeSourceInfo *TInfo = nullptr;
  2080. GetTypeFromParser(basetype, &TInfo);
  2081. if (EllipsisLoc.isInvalid() &&
  2082. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2083. UPPC_BaseType))
  2084. return true;
  2085. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2086. Virtual, Access, TInfo,
  2087. EllipsisLoc))
  2088. return BaseSpec;
  2089. else
  2090. Class->setInvalidDecl();
  2091. return true;
  2092. }
  2093. /// Use small set to collect indirect bases. As this is only used
  2094. /// locally, there's no need to abstract the small size parameter.
  2095. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2096. /// Recursively add the bases of Type. Don't add Type itself.
  2097. static void
  2098. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2099. const QualType &Type)
  2100. {
  2101. // Even though the incoming type is a base, it might not be
  2102. // a class -- it could be a template parm, for instance.
  2103. if (auto Rec = Type->getAs<RecordType>()) {
  2104. auto Decl = Rec->getAsCXXRecordDecl();
  2105. // Iterate over its bases.
  2106. for (const auto &BaseSpec : Decl->bases()) {
  2107. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2108. .getUnqualifiedType();
  2109. if (Set.insert(Base).second)
  2110. // If we've not already seen it, recurse.
  2111. NoteIndirectBases(Context, Set, Base);
  2112. }
  2113. }
  2114. }
  2115. /// Performs the actual work of attaching the given base class
  2116. /// specifiers to a C++ class.
  2117. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2118. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2119. if (Bases.empty())
  2120. return false;
  2121. // Used to keep track of which base types we have already seen, so
  2122. // that we can properly diagnose redundant direct base types. Note
  2123. // that the key is always the unqualified canonical type of the base
  2124. // class.
  2125. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2126. // Used to track indirect bases so we can see if a direct base is
  2127. // ambiguous.
  2128. IndirectBaseSet IndirectBaseTypes;
  2129. // Copy non-redundant base specifiers into permanent storage.
  2130. unsigned NumGoodBases = 0;
  2131. bool Invalid = false;
  2132. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2133. QualType NewBaseType
  2134. = Context.getCanonicalType(Bases[idx]->getType());
  2135. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2136. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2137. if (KnownBase) {
  2138. // C++ [class.mi]p3:
  2139. // A class shall not be specified as a direct base class of a
  2140. // derived class more than once.
  2141. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2142. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2143. // Delete the duplicate base class specifier; we're going to
  2144. // overwrite its pointer later.
  2145. Context.Deallocate(Bases[idx]);
  2146. Invalid = true;
  2147. } else {
  2148. // Okay, add this new base class.
  2149. KnownBase = Bases[idx];
  2150. Bases[NumGoodBases++] = Bases[idx];
  2151. // Note this base's direct & indirect bases, if there could be ambiguity.
  2152. if (Bases.size() > 1)
  2153. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2154. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2155. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2156. if (Class->isInterface() &&
  2157. (!RD->isInterfaceLike() ||
  2158. KnownBase->getAccessSpecifier() != AS_public)) {
  2159. // The Microsoft extension __interface does not permit bases that
  2160. // are not themselves public interfaces.
  2161. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2162. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2163. << RD->getSourceRange();
  2164. Invalid = true;
  2165. }
  2166. if (RD->hasAttr<WeakAttr>())
  2167. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2168. }
  2169. }
  2170. }
  2171. // Attach the remaining base class specifiers to the derived class.
  2172. Class->setBases(Bases.data(), NumGoodBases);
  2173. // Check that the only base classes that are duplicate are virtual.
  2174. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2175. // Check whether this direct base is inaccessible due to ambiguity.
  2176. QualType BaseType = Bases[idx]->getType();
  2177. // Skip all dependent types in templates being used as base specifiers.
  2178. // Checks below assume that the base specifier is a CXXRecord.
  2179. if (BaseType->isDependentType())
  2180. continue;
  2181. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2182. .getUnqualifiedType();
  2183. if (IndirectBaseTypes.count(CanonicalBase)) {
  2184. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2185. /*DetectVirtual=*/true);
  2186. bool found
  2187. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2188. assert(found);
  2189. (void)found;
  2190. if (Paths.isAmbiguous(CanonicalBase))
  2191. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2192. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2193. << Bases[idx]->getSourceRange();
  2194. else
  2195. assert(Bases[idx]->isVirtual());
  2196. }
  2197. // Delete the base class specifier, since its data has been copied
  2198. // into the CXXRecordDecl.
  2199. Context.Deallocate(Bases[idx]);
  2200. }
  2201. return Invalid;
  2202. }
  2203. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2204. /// class, after checking whether there are any duplicate base
  2205. /// classes.
  2206. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2207. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2208. if (!ClassDecl || Bases.empty())
  2209. return;
  2210. AdjustDeclIfTemplate(ClassDecl);
  2211. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2212. }
  2213. /// Determine whether the type \p Derived is a C++ class that is
  2214. /// derived from the type \p Base.
  2215. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2216. if (!getLangOpts().CPlusPlus)
  2217. return false;
  2218. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2219. if (!DerivedRD)
  2220. return false;
  2221. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2222. if (!BaseRD)
  2223. return false;
  2224. // If either the base or the derived type is invalid, don't try to
  2225. // check whether one is derived from the other.
  2226. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2227. return false;
  2228. // FIXME: In a modules build, do we need the entire path to be visible for us
  2229. // to be able to use the inheritance relationship?
  2230. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2231. return false;
  2232. return DerivedRD->isDerivedFrom(BaseRD);
  2233. }
  2234. /// Determine whether the type \p Derived is a C++ class that is
  2235. /// derived from the type \p Base.
  2236. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2237. CXXBasePaths &Paths) {
  2238. if (!getLangOpts().CPlusPlus)
  2239. return false;
  2240. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2241. if (!DerivedRD)
  2242. return false;
  2243. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2244. if (!BaseRD)
  2245. return false;
  2246. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2247. return false;
  2248. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2249. }
  2250. static void BuildBasePathArray(const CXXBasePath &Path,
  2251. CXXCastPath &BasePathArray) {
  2252. // We first go backward and check if we have a virtual base.
  2253. // FIXME: It would be better if CXXBasePath had the base specifier for
  2254. // the nearest virtual base.
  2255. unsigned Start = 0;
  2256. for (unsigned I = Path.size(); I != 0; --I) {
  2257. if (Path[I - 1].Base->isVirtual()) {
  2258. Start = I - 1;
  2259. break;
  2260. }
  2261. }
  2262. // Now add all bases.
  2263. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2264. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2265. }
  2266. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2267. CXXCastPath &BasePathArray) {
  2268. assert(BasePathArray.empty() && "Base path array must be empty!");
  2269. assert(Paths.isRecordingPaths() && "Must record paths!");
  2270. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2271. }
  2272. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2273. /// conversion (where Derived and Base are class types) is
  2274. /// well-formed, meaning that the conversion is unambiguous (and
  2275. /// that all of the base classes are accessible). Returns true
  2276. /// and emits a diagnostic if the code is ill-formed, returns false
  2277. /// otherwise. Loc is the location where this routine should point to
  2278. /// if there is an error, and Range is the source range to highlight
  2279. /// if there is an error.
  2280. ///
  2281. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2282. /// diagnostic for the respective type of error will be suppressed, but the
  2283. /// check for ill-formed code will still be performed.
  2284. bool
  2285. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2286. unsigned InaccessibleBaseID,
  2287. unsigned AmbigiousBaseConvID,
  2288. SourceLocation Loc, SourceRange Range,
  2289. DeclarationName Name,
  2290. CXXCastPath *BasePath,
  2291. bool IgnoreAccess) {
  2292. // First, determine whether the path from Derived to Base is
  2293. // ambiguous. This is slightly more expensive than checking whether
  2294. // the Derived to Base conversion exists, because here we need to
  2295. // explore multiple paths to determine if there is an ambiguity.
  2296. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2297. /*DetectVirtual=*/false);
  2298. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2299. if (!DerivationOkay)
  2300. return true;
  2301. const CXXBasePath *Path = nullptr;
  2302. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2303. Path = &Paths.front();
  2304. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2305. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2306. // user to access such bases.
  2307. if (!Path && getLangOpts().MSVCCompat) {
  2308. for (const CXXBasePath &PossiblePath : Paths) {
  2309. if (PossiblePath.size() == 1) {
  2310. Path = &PossiblePath;
  2311. if (AmbigiousBaseConvID)
  2312. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2313. << Base << Derived << Range;
  2314. break;
  2315. }
  2316. }
  2317. }
  2318. if (Path) {
  2319. if (!IgnoreAccess) {
  2320. // Check that the base class can be accessed.
  2321. switch (
  2322. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2323. case AR_inaccessible:
  2324. return true;
  2325. case AR_accessible:
  2326. case AR_dependent:
  2327. case AR_delayed:
  2328. break;
  2329. }
  2330. }
  2331. // Build a base path if necessary.
  2332. if (BasePath)
  2333. ::BuildBasePathArray(*Path, *BasePath);
  2334. return false;
  2335. }
  2336. if (AmbigiousBaseConvID) {
  2337. // We know that the derived-to-base conversion is ambiguous, and
  2338. // we're going to produce a diagnostic. Perform the derived-to-base
  2339. // search just one more time to compute all of the possible paths so
  2340. // that we can print them out. This is more expensive than any of
  2341. // the previous derived-to-base checks we've done, but at this point
  2342. // performance isn't as much of an issue.
  2343. Paths.clear();
  2344. Paths.setRecordingPaths(true);
  2345. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2346. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2347. (void)StillOkay;
  2348. // Build up a textual representation of the ambiguous paths, e.g.,
  2349. // D -> B -> A, that will be used to illustrate the ambiguous
  2350. // conversions in the diagnostic. We only print one of the paths
  2351. // to each base class subobject.
  2352. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2353. Diag(Loc, AmbigiousBaseConvID)
  2354. << Derived << Base << PathDisplayStr << Range << Name;
  2355. }
  2356. return true;
  2357. }
  2358. bool
  2359. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2360. SourceLocation Loc, SourceRange Range,
  2361. CXXCastPath *BasePath,
  2362. bool IgnoreAccess) {
  2363. return CheckDerivedToBaseConversion(
  2364. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2365. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2366. BasePath, IgnoreAccess);
  2367. }
  2368. /// Builds a string representing ambiguous paths from a
  2369. /// specific derived class to different subobjects of the same base
  2370. /// class.
  2371. ///
  2372. /// This function builds a string that can be used in error messages
  2373. /// to show the different paths that one can take through the
  2374. /// inheritance hierarchy to go from the derived class to different
  2375. /// subobjects of a base class. The result looks something like this:
  2376. /// @code
  2377. /// struct D -> struct B -> struct A
  2378. /// struct D -> struct C -> struct A
  2379. /// @endcode
  2380. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2381. std::string PathDisplayStr;
  2382. std::set<unsigned> DisplayedPaths;
  2383. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2384. Path != Paths.end(); ++Path) {
  2385. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2386. // We haven't displayed a path to this particular base
  2387. // class subobject yet.
  2388. PathDisplayStr += "\n ";
  2389. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2390. for (CXXBasePath::const_iterator Element = Path->begin();
  2391. Element != Path->end(); ++Element)
  2392. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2393. }
  2394. }
  2395. return PathDisplayStr;
  2396. }
  2397. //===----------------------------------------------------------------------===//
  2398. // C++ class member Handling
  2399. //===----------------------------------------------------------------------===//
  2400. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2401. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2402. SourceLocation ColonLoc,
  2403. const ParsedAttributesView &Attrs) {
  2404. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2405. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2406. ASLoc, ColonLoc);
  2407. CurContext->addHiddenDecl(ASDecl);
  2408. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2409. }
  2410. /// CheckOverrideControl - Check C++11 override control semantics.
  2411. void Sema::CheckOverrideControl(NamedDecl *D) {
  2412. if (D->isInvalidDecl())
  2413. return;
  2414. // We only care about "override" and "final" declarations.
  2415. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2416. return;
  2417. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2418. // We can't check dependent instance methods.
  2419. if (MD && MD->isInstance() &&
  2420. (MD->getParent()->hasAnyDependentBases() ||
  2421. MD->getType()->isDependentType()))
  2422. return;
  2423. if (MD && !MD->isVirtual()) {
  2424. // If we have a non-virtual method, check if if hides a virtual method.
  2425. // (In that case, it's most likely the method has the wrong type.)
  2426. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2427. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2428. if (!OverloadedMethods.empty()) {
  2429. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2430. Diag(OA->getLocation(),
  2431. diag::override_keyword_hides_virtual_member_function)
  2432. << "override" << (OverloadedMethods.size() > 1);
  2433. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2434. Diag(FA->getLocation(),
  2435. diag::override_keyword_hides_virtual_member_function)
  2436. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2437. << (OverloadedMethods.size() > 1);
  2438. }
  2439. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2440. MD->setInvalidDecl();
  2441. return;
  2442. }
  2443. // Fall through into the general case diagnostic.
  2444. // FIXME: We might want to attempt typo correction here.
  2445. }
  2446. if (!MD || !MD->isVirtual()) {
  2447. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2448. Diag(OA->getLocation(),
  2449. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2450. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2451. D->dropAttr<OverrideAttr>();
  2452. }
  2453. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2454. Diag(FA->getLocation(),
  2455. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2456. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2457. << FixItHint::CreateRemoval(FA->getLocation());
  2458. D->dropAttr<FinalAttr>();
  2459. }
  2460. return;
  2461. }
  2462. // C++11 [class.virtual]p5:
  2463. // If a function is marked with the virt-specifier override and
  2464. // does not override a member function of a base class, the program is
  2465. // ill-formed.
  2466. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2467. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2468. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2469. << MD->getDeclName();
  2470. }
  2471. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2472. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2473. return;
  2474. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2475. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2476. return;
  2477. SourceLocation Loc = MD->getLocation();
  2478. SourceLocation SpellingLoc = Loc;
  2479. if (getSourceManager().isMacroArgExpansion(Loc))
  2480. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2481. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2482. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2483. return;
  2484. if (MD->size_overridden_methods() > 0) {
  2485. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2486. ? diag::warn_destructor_marked_not_override_overriding
  2487. : diag::warn_function_marked_not_override_overriding;
  2488. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2489. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2490. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2491. }
  2492. }
  2493. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2494. /// function overrides a virtual member function marked 'final', according to
  2495. /// C++11 [class.virtual]p4.
  2496. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2497. const CXXMethodDecl *Old) {
  2498. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2499. if (!FA)
  2500. return false;
  2501. Diag(New->getLocation(), diag::err_final_function_overridden)
  2502. << New->getDeclName()
  2503. << FA->isSpelledAsSealed();
  2504. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2505. return true;
  2506. }
  2507. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2508. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2509. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2510. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2511. return !RD->isCompleteDefinition() ||
  2512. !RD->hasTrivialDefaultConstructor() ||
  2513. !RD->hasTrivialDestructor();
  2514. return false;
  2515. }
  2516. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2517. ParsedAttributesView::const_iterator Itr =
  2518. llvm::find_if(list, [](const ParsedAttr &AL) {
  2519. return AL.isDeclspecPropertyAttribute();
  2520. });
  2521. if (Itr != list.end())
  2522. return &*Itr;
  2523. return nullptr;
  2524. }
  2525. // Check if there is a field shadowing.
  2526. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2527. DeclarationName FieldName,
  2528. const CXXRecordDecl *RD) {
  2529. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2530. return;
  2531. // To record a shadowed field in a base
  2532. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2533. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2534. CXXBasePath &Path) {
  2535. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2536. // Record an ambiguous path directly
  2537. if (Bases.find(Base) != Bases.end())
  2538. return true;
  2539. for (const auto Field : Base->lookup(FieldName)) {
  2540. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2541. Field->getAccess() != AS_private) {
  2542. assert(Field->getAccess() != AS_none);
  2543. assert(Bases.find(Base) == Bases.end());
  2544. Bases[Base] = Field;
  2545. return true;
  2546. }
  2547. }
  2548. return false;
  2549. };
  2550. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2551. /*DetectVirtual=*/true);
  2552. if (!RD->lookupInBases(FieldShadowed, Paths))
  2553. return;
  2554. for (const auto &P : Paths) {
  2555. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2556. auto It = Bases.find(Base);
  2557. // Skip duplicated bases
  2558. if (It == Bases.end())
  2559. continue;
  2560. auto BaseField = It->second;
  2561. assert(BaseField->getAccess() != AS_private);
  2562. if (AS_none !=
  2563. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2564. Diag(Loc, diag::warn_shadow_field)
  2565. << FieldName << RD << Base;
  2566. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2567. Bases.erase(It);
  2568. }
  2569. }
  2570. }
  2571. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2572. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2573. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2574. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2575. /// present (but parsing it has been deferred).
  2576. NamedDecl *
  2577. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2578. MultiTemplateParamsArg TemplateParameterLists,
  2579. Expr *BW, const VirtSpecifiers &VS,
  2580. InClassInitStyle InitStyle) {
  2581. const DeclSpec &DS = D.getDeclSpec();
  2582. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2583. DeclarationName Name = NameInfo.getName();
  2584. SourceLocation Loc = NameInfo.getLoc();
  2585. // For anonymous bitfields, the location should point to the type.
  2586. if (Loc.isInvalid())
  2587. Loc = D.getBeginLoc();
  2588. Expr *BitWidth = static_cast<Expr*>(BW);
  2589. assert(isa<CXXRecordDecl>(CurContext));
  2590. assert(!DS.isFriendSpecified());
  2591. bool isFunc = D.isDeclarationOfFunction();
  2592. const ParsedAttr *MSPropertyAttr =
  2593. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2594. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2595. // The Microsoft extension __interface only permits public member functions
  2596. // and prohibits constructors, destructors, operators, non-public member
  2597. // functions, static methods and data members.
  2598. unsigned InvalidDecl;
  2599. bool ShowDeclName = true;
  2600. if (!isFunc &&
  2601. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2602. InvalidDecl = 0;
  2603. else if (!isFunc)
  2604. InvalidDecl = 1;
  2605. else if (AS != AS_public)
  2606. InvalidDecl = 2;
  2607. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2608. InvalidDecl = 3;
  2609. else switch (Name.getNameKind()) {
  2610. case DeclarationName::CXXConstructorName:
  2611. InvalidDecl = 4;
  2612. ShowDeclName = false;
  2613. break;
  2614. case DeclarationName::CXXDestructorName:
  2615. InvalidDecl = 5;
  2616. ShowDeclName = false;
  2617. break;
  2618. case DeclarationName::CXXOperatorName:
  2619. case DeclarationName::CXXConversionFunctionName:
  2620. InvalidDecl = 6;
  2621. break;
  2622. default:
  2623. InvalidDecl = 0;
  2624. break;
  2625. }
  2626. if (InvalidDecl) {
  2627. if (ShowDeclName)
  2628. Diag(Loc, diag::err_invalid_member_in_interface)
  2629. << (InvalidDecl-1) << Name;
  2630. else
  2631. Diag(Loc, diag::err_invalid_member_in_interface)
  2632. << (InvalidDecl-1) << "";
  2633. return nullptr;
  2634. }
  2635. }
  2636. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2637. // duration (auto, register) or with the extern storage-class-specifier.
  2638. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2639. // data members and cannot be applied to names declared const or static,
  2640. // and cannot be applied to reference members.
  2641. switch (DS.getStorageClassSpec()) {
  2642. case DeclSpec::SCS_unspecified:
  2643. case DeclSpec::SCS_typedef:
  2644. case DeclSpec::SCS_static:
  2645. break;
  2646. case DeclSpec::SCS_mutable:
  2647. if (isFunc) {
  2648. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2649. // FIXME: It would be nicer if the keyword was ignored only for this
  2650. // declarator. Otherwise we could get follow-up errors.
  2651. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2652. }
  2653. break;
  2654. default:
  2655. Diag(DS.getStorageClassSpecLoc(),
  2656. diag::err_storageclass_invalid_for_member);
  2657. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2658. break;
  2659. }
  2660. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2661. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2662. !isFunc);
  2663. if (DS.isConstexprSpecified() && isInstField) {
  2664. SemaDiagnosticBuilder B =
  2665. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2666. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2667. if (InitStyle == ICIS_NoInit) {
  2668. B << 0 << 0;
  2669. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2670. B << FixItHint::CreateRemoval(ConstexprLoc);
  2671. else {
  2672. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2673. D.getMutableDeclSpec().ClearConstexprSpec();
  2674. const char *PrevSpec;
  2675. unsigned DiagID;
  2676. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2677. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2678. (void)Failed;
  2679. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2680. }
  2681. } else {
  2682. B << 1;
  2683. const char *PrevSpec;
  2684. unsigned DiagID;
  2685. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2686. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2687. Context.getPrintingPolicy())) {
  2688. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2689. "This is the only DeclSpec that should fail to be applied");
  2690. B << 1;
  2691. } else {
  2692. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2693. isInstField = false;
  2694. }
  2695. }
  2696. }
  2697. NamedDecl *Member;
  2698. if (isInstField) {
  2699. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2700. // Data members must have identifiers for names.
  2701. if (!Name.isIdentifier()) {
  2702. Diag(Loc, diag::err_bad_variable_name)
  2703. << Name;
  2704. return nullptr;
  2705. }
  2706. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2707. // Member field could not be with "template" keyword.
  2708. // So TemplateParameterLists should be empty in this case.
  2709. if (TemplateParameterLists.size()) {
  2710. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2711. if (TemplateParams->size()) {
  2712. // There is no such thing as a member field template.
  2713. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2714. << II
  2715. << SourceRange(TemplateParams->getTemplateLoc(),
  2716. TemplateParams->getRAngleLoc());
  2717. } else {
  2718. // There is an extraneous 'template<>' for this member.
  2719. Diag(TemplateParams->getTemplateLoc(),
  2720. diag::err_template_member_noparams)
  2721. << II
  2722. << SourceRange(TemplateParams->getTemplateLoc(),
  2723. TemplateParams->getRAngleLoc());
  2724. }
  2725. return nullptr;
  2726. }
  2727. if (SS.isSet() && !SS.isInvalid()) {
  2728. // The user provided a superfluous scope specifier inside a class
  2729. // definition:
  2730. //
  2731. // class X {
  2732. // int X::member;
  2733. // };
  2734. if (DeclContext *DC = computeDeclContext(SS, false))
  2735. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2736. D.getName().getKind() ==
  2737. UnqualifiedIdKind::IK_TemplateId);
  2738. else
  2739. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2740. << Name << SS.getRange();
  2741. SS.clear();
  2742. }
  2743. if (MSPropertyAttr) {
  2744. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2745. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2746. if (!Member)
  2747. return nullptr;
  2748. isInstField = false;
  2749. } else {
  2750. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2751. BitWidth, InitStyle, AS);
  2752. if (!Member)
  2753. return nullptr;
  2754. }
  2755. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2756. } else {
  2757. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2758. if (!Member)
  2759. return nullptr;
  2760. // Non-instance-fields can't have a bitfield.
  2761. if (BitWidth) {
  2762. if (Member->isInvalidDecl()) {
  2763. // don't emit another diagnostic.
  2764. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2765. // C++ 9.6p3: A bit-field shall not be a static member.
  2766. // "static member 'A' cannot be a bit-field"
  2767. Diag(Loc, diag::err_static_not_bitfield)
  2768. << Name << BitWidth->getSourceRange();
  2769. } else if (isa<TypedefDecl>(Member)) {
  2770. // "typedef member 'x' cannot be a bit-field"
  2771. Diag(Loc, diag::err_typedef_not_bitfield)
  2772. << Name << BitWidth->getSourceRange();
  2773. } else {
  2774. // A function typedef ("typedef int f(); f a;").
  2775. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2776. Diag(Loc, diag::err_not_integral_type_bitfield)
  2777. << Name << cast<ValueDecl>(Member)->getType()
  2778. << BitWidth->getSourceRange();
  2779. }
  2780. BitWidth = nullptr;
  2781. Member->setInvalidDecl();
  2782. }
  2783. NamedDecl *NonTemplateMember = Member;
  2784. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2785. NonTemplateMember = FunTmpl->getTemplatedDecl();
  2786. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2787. NonTemplateMember = VarTmpl->getTemplatedDecl();
  2788. Member->setAccess(AS);
  2789. // If we have declared a member function template or static data member
  2790. // template, set the access of the templated declaration as well.
  2791. if (NonTemplateMember != Member)
  2792. NonTemplateMember->setAccess(AS);
  2793. // C++ [temp.deduct.guide]p3:
  2794. // A deduction guide [...] for a member class template [shall be
  2795. // declared] with the same access [as the template].
  2796. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  2797. auto *TD = DG->getDeducedTemplate();
  2798. if (AS != TD->getAccess()) {
  2799. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  2800. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  2801. << TD->getAccess();
  2802. const AccessSpecDecl *LastAccessSpec = nullptr;
  2803. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  2804. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  2805. LastAccessSpec = AccessSpec;
  2806. }
  2807. assert(LastAccessSpec && "differing access with no access specifier");
  2808. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  2809. << AS;
  2810. }
  2811. }
  2812. }
  2813. if (VS.isOverrideSpecified())
  2814. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2815. if (VS.isFinalSpecified())
  2816. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2817. VS.isFinalSpelledSealed()));
  2818. if (VS.getLastLocation().isValid()) {
  2819. // Update the end location of a method that has a virt-specifiers.
  2820. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2821. MD->setRangeEnd(VS.getLastLocation());
  2822. }
  2823. CheckOverrideControl(Member);
  2824. assert((Name || isInstField) && "No identifier for non-field ?");
  2825. if (isInstField) {
  2826. FieldDecl *FD = cast<FieldDecl>(Member);
  2827. FieldCollector->Add(FD);
  2828. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2829. // Remember all explicit private FieldDecls that have a name, no side
  2830. // effects and are not part of a dependent type declaration.
  2831. if (!FD->isImplicit() && FD->getDeclName() &&
  2832. FD->getAccess() == AS_private &&
  2833. !FD->hasAttr<UnusedAttr>() &&
  2834. !FD->getParent()->isDependentContext() &&
  2835. !InitializationHasSideEffects(*FD))
  2836. UnusedPrivateFields.insert(FD);
  2837. }
  2838. }
  2839. return Member;
  2840. }
  2841. namespace {
  2842. class UninitializedFieldVisitor
  2843. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2844. Sema &S;
  2845. // List of Decls to generate a warning on. Also remove Decls that become
  2846. // initialized.
  2847. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2848. // List of base classes of the record. Classes are removed after their
  2849. // initializers.
  2850. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2851. // Vector of decls to be removed from the Decl set prior to visiting the
  2852. // nodes. These Decls may have been initialized in the prior initializer.
  2853. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2854. // If non-null, add a note to the warning pointing back to the constructor.
  2855. const CXXConstructorDecl *Constructor;
  2856. // Variables to hold state when processing an initializer list. When
  2857. // InitList is true, special case initialization of FieldDecls matching
  2858. // InitListFieldDecl.
  2859. bool InitList;
  2860. FieldDecl *InitListFieldDecl;
  2861. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2862. public:
  2863. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2864. UninitializedFieldVisitor(Sema &S,
  2865. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2866. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2867. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2868. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2869. // Returns true if the use of ME is not an uninitialized use.
  2870. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2871. bool CheckReferenceOnly) {
  2872. llvm::SmallVector<FieldDecl*, 4> Fields;
  2873. bool ReferenceField = false;
  2874. while (ME) {
  2875. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2876. if (!FD)
  2877. return false;
  2878. Fields.push_back(FD);
  2879. if (FD->getType()->isReferenceType())
  2880. ReferenceField = true;
  2881. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2882. }
  2883. // Binding a reference to an unintialized field is not an
  2884. // uninitialized use.
  2885. if (CheckReferenceOnly && !ReferenceField)
  2886. return true;
  2887. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2888. // Discard the first field since it is the field decl that is being
  2889. // initialized.
  2890. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2891. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2892. }
  2893. for (auto UsedIter = UsedFieldIndex.begin(),
  2894. UsedEnd = UsedFieldIndex.end(),
  2895. OrigIter = InitFieldIndex.begin(),
  2896. OrigEnd = InitFieldIndex.end();
  2897. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2898. if (*UsedIter < *OrigIter)
  2899. return true;
  2900. if (*UsedIter > *OrigIter)
  2901. break;
  2902. }
  2903. return false;
  2904. }
  2905. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2906. bool AddressOf) {
  2907. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2908. return;
  2909. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2910. // or union.
  2911. MemberExpr *FieldME = ME;
  2912. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2913. Expr *Base = ME;
  2914. while (MemberExpr *SubME =
  2915. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2916. if (isa<VarDecl>(SubME->getMemberDecl()))
  2917. return;
  2918. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2919. if (!FD->isAnonymousStructOrUnion())
  2920. FieldME = SubME;
  2921. if (!FieldME->getType().isPODType(S.Context))
  2922. AllPODFields = false;
  2923. Base = SubME->getBase();
  2924. }
  2925. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2926. return;
  2927. if (AddressOf && AllPODFields)
  2928. return;
  2929. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2930. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2931. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2932. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2933. }
  2934. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2935. QualType T = BaseCast->getType();
  2936. if (T->isPointerType() &&
  2937. BaseClasses.count(T->getPointeeType())) {
  2938. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2939. << T->getPointeeType() << FoundVD;
  2940. }
  2941. }
  2942. }
  2943. if (!Decls.count(FoundVD))
  2944. return;
  2945. const bool IsReference = FoundVD->getType()->isReferenceType();
  2946. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  2947. // Special checking for initializer lists.
  2948. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  2949. return;
  2950. }
  2951. } else {
  2952. // Prevent double warnings on use of unbounded references.
  2953. if (CheckReferenceOnly && !IsReference)
  2954. return;
  2955. }
  2956. unsigned diag = IsReference
  2957. ? diag::warn_reference_field_is_uninit
  2958. : diag::warn_field_is_uninit;
  2959. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  2960. if (Constructor)
  2961. S.Diag(Constructor->getLocation(),
  2962. diag::note_uninit_in_this_constructor)
  2963. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  2964. }
  2965. void HandleValue(Expr *E, bool AddressOf) {
  2966. E = E->IgnoreParens();
  2967. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  2968. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  2969. AddressOf /*AddressOf*/);
  2970. return;
  2971. }
  2972. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2973. Visit(CO->getCond());
  2974. HandleValue(CO->getTrueExpr(), AddressOf);
  2975. HandleValue(CO->getFalseExpr(), AddressOf);
  2976. return;
  2977. }
  2978. if (BinaryConditionalOperator *BCO =
  2979. dyn_cast<BinaryConditionalOperator>(E)) {
  2980. Visit(BCO->getCond());
  2981. HandleValue(BCO->getFalseExpr(), AddressOf);
  2982. return;
  2983. }
  2984. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  2985. HandleValue(OVE->getSourceExpr(), AddressOf);
  2986. return;
  2987. }
  2988. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2989. switch (BO->getOpcode()) {
  2990. default:
  2991. break;
  2992. case(BO_PtrMemD):
  2993. case(BO_PtrMemI):
  2994. HandleValue(BO->getLHS(), AddressOf);
  2995. Visit(BO->getRHS());
  2996. return;
  2997. case(BO_Comma):
  2998. Visit(BO->getLHS());
  2999. HandleValue(BO->getRHS(), AddressOf);
  3000. return;
  3001. }
  3002. }
  3003. Visit(E);
  3004. }
  3005. void CheckInitListExpr(InitListExpr *ILE) {
  3006. InitFieldIndex.push_back(0);
  3007. for (auto Child : ILE->children()) {
  3008. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3009. CheckInitListExpr(SubList);
  3010. } else {
  3011. Visit(Child);
  3012. }
  3013. ++InitFieldIndex.back();
  3014. }
  3015. InitFieldIndex.pop_back();
  3016. }
  3017. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3018. FieldDecl *Field, const Type *BaseClass) {
  3019. // Remove Decls that may have been initialized in the previous
  3020. // initializer.
  3021. for (ValueDecl* VD : DeclsToRemove)
  3022. Decls.erase(VD);
  3023. DeclsToRemove.clear();
  3024. Constructor = FieldConstructor;
  3025. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3026. if (ILE && Field) {
  3027. InitList = true;
  3028. InitListFieldDecl = Field;
  3029. InitFieldIndex.clear();
  3030. CheckInitListExpr(ILE);
  3031. } else {
  3032. InitList = false;
  3033. Visit(E);
  3034. }
  3035. if (Field)
  3036. Decls.erase(Field);
  3037. if (BaseClass)
  3038. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3039. }
  3040. void VisitMemberExpr(MemberExpr *ME) {
  3041. // All uses of unbounded reference fields will warn.
  3042. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3043. }
  3044. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3045. if (E->getCastKind() == CK_LValueToRValue) {
  3046. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3047. return;
  3048. }
  3049. Inherited::VisitImplicitCastExpr(E);
  3050. }
  3051. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3052. if (E->getConstructor()->isCopyConstructor()) {
  3053. Expr *ArgExpr = E->getArg(0);
  3054. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3055. if (ILE->getNumInits() == 1)
  3056. ArgExpr = ILE->getInit(0);
  3057. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3058. if (ICE->getCastKind() == CK_NoOp)
  3059. ArgExpr = ICE->getSubExpr();
  3060. HandleValue(ArgExpr, false /*AddressOf*/);
  3061. return;
  3062. }
  3063. Inherited::VisitCXXConstructExpr(E);
  3064. }
  3065. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3066. Expr *Callee = E->getCallee();
  3067. if (isa<MemberExpr>(Callee)) {
  3068. HandleValue(Callee, false /*AddressOf*/);
  3069. for (auto Arg : E->arguments())
  3070. Visit(Arg);
  3071. return;
  3072. }
  3073. Inherited::VisitCXXMemberCallExpr(E);
  3074. }
  3075. void VisitCallExpr(CallExpr *E) {
  3076. // Treat std::move as a use.
  3077. if (E->isCallToStdMove()) {
  3078. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3079. return;
  3080. }
  3081. Inherited::VisitCallExpr(E);
  3082. }
  3083. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3084. Expr *Callee = E->getCallee();
  3085. if (isa<UnresolvedLookupExpr>(Callee))
  3086. return Inherited::VisitCXXOperatorCallExpr(E);
  3087. Visit(Callee);
  3088. for (auto Arg : E->arguments())
  3089. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3090. }
  3091. void VisitBinaryOperator(BinaryOperator *E) {
  3092. // If a field assignment is detected, remove the field from the
  3093. // uninitiailized field set.
  3094. if (E->getOpcode() == BO_Assign)
  3095. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3096. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3097. if (!FD->getType()->isReferenceType())
  3098. DeclsToRemove.push_back(FD);
  3099. if (E->isCompoundAssignmentOp()) {
  3100. HandleValue(E->getLHS(), false /*AddressOf*/);
  3101. Visit(E->getRHS());
  3102. return;
  3103. }
  3104. Inherited::VisitBinaryOperator(E);
  3105. }
  3106. void VisitUnaryOperator(UnaryOperator *E) {
  3107. if (E->isIncrementDecrementOp()) {
  3108. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3109. return;
  3110. }
  3111. if (E->getOpcode() == UO_AddrOf) {
  3112. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3113. HandleValue(ME->getBase(), true /*AddressOf*/);
  3114. return;
  3115. }
  3116. }
  3117. Inherited::VisitUnaryOperator(E);
  3118. }
  3119. };
  3120. // Diagnose value-uses of fields to initialize themselves, e.g.
  3121. // foo(foo)
  3122. // where foo is not also a parameter to the constructor.
  3123. // Also diagnose across field uninitialized use such as
  3124. // x(y), y(x)
  3125. // TODO: implement -Wuninitialized and fold this into that framework.
  3126. static void DiagnoseUninitializedFields(
  3127. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3128. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3129. Constructor->getLocation())) {
  3130. return;
  3131. }
  3132. if (Constructor->isInvalidDecl())
  3133. return;
  3134. const CXXRecordDecl *RD = Constructor->getParent();
  3135. if (RD->getDescribedClassTemplate())
  3136. return;
  3137. // Holds fields that are uninitialized.
  3138. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3139. // At the beginning, all fields are uninitialized.
  3140. for (auto *I : RD->decls()) {
  3141. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3142. UninitializedFields.insert(FD);
  3143. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3144. UninitializedFields.insert(IFD->getAnonField());
  3145. }
  3146. }
  3147. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3148. for (auto I : RD->bases())
  3149. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3150. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3151. return;
  3152. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3153. UninitializedFields,
  3154. UninitializedBaseClasses);
  3155. for (const auto *FieldInit : Constructor->inits()) {
  3156. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3157. break;
  3158. Expr *InitExpr = FieldInit->getInit();
  3159. if (!InitExpr)
  3160. continue;
  3161. if (CXXDefaultInitExpr *Default =
  3162. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3163. InitExpr = Default->getExpr();
  3164. if (!InitExpr)
  3165. continue;
  3166. // In class initializers will point to the constructor.
  3167. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3168. FieldInit->getAnyMember(),
  3169. FieldInit->getBaseClass());
  3170. } else {
  3171. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3172. FieldInit->getAnyMember(),
  3173. FieldInit->getBaseClass());
  3174. }
  3175. }
  3176. }
  3177. } // namespace
  3178. /// Enter a new C++ default initializer scope. After calling this, the
  3179. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3180. /// parsing or instantiating the initializer failed.
  3181. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3182. // Create a synthetic function scope to represent the call to the constructor
  3183. // that notionally surrounds a use of this initializer.
  3184. PushFunctionScope();
  3185. }
  3186. /// This is invoked after parsing an in-class initializer for a
  3187. /// non-static C++ class member, and after instantiating an in-class initializer
  3188. /// in a class template. Such actions are deferred until the class is complete.
  3189. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3190. SourceLocation InitLoc,
  3191. Expr *InitExpr) {
  3192. // Pop the notional constructor scope we created earlier.
  3193. PopFunctionScopeInfo(nullptr, D);
  3194. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3195. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3196. "must set init style when field is created");
  3197. if (!InitExpr) {
  3198. D->setInvalidDecl();
  3199. if (FD)
  3200. FD->removeInClassInitializer();
  3201. return;
  3202. }
  3203. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3204. FD->setInvalidDecl();
  3205. FD->removeInClassInitializer();
  3206. return;
  3207. }
  3208. ExprResult Init = InitExpr;
  3209. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3210. InitializedEntity Entity =
  3211. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3212. InitializationKind Kind =
  3213. FD->getInClassInitStyle() == ICIS_ListInit
  3214. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3215. InitExpr->getBeginLoc(),
  3216. InitExpr->getEndLoc())
  3217. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3218. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3219. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3220. if (Init.isInvalid()) {
  3221. FD->setInvalidDecl();
  3222. return;
  3223. }
  3224. }
  3225. // C++11 [class.base.init]p7:
  3226. // The initialization of each base and member constitutes a
  3227. // full-expression.
  3228. Init = ActOnFinishFullExpr(Init.get(), InitLoc);
  3229. if (Init.isInvalid()) {
  3230. FD->setInvalidDecl();
  3231. return;
  3232. }
  3233. InitExpr = Init.get();
  3234. FD->setInClassInitializer(InitExpr);
  3235. }
  3236. /// Find the direct and/or virtual base specifiers that
  3237. /// correspond to the given base type, for use in base initialization
  3238. /// within a constructor.
  3239. static bool FindBaseInitializer(Sema &SemaRef,
  3240. CXXRecordDecl *ClassDecl,
  3241. QualType BaseType,
  3242. const CXXBaseSpecifier *&DirectBaseSpec,
  3243. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3244. // First, check for a direct base class.
  3245. DirectBaseSpec = nullptr;
  3246. for (const auto &Base : ClassDecl->bases()) {
  3247. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3248. // We found a direct base of this type. That's what we're
  3249. // initializing.
  3250. DirectBaseSpec = &Base;
  3251. break;
  3252. }
  3253. }
  3254. // Check for a virtual base class.
  3255. // FIXME: We might be able to short-circuit this if we know in advance that
  3256. // there are no virtual bases.
  3257. VirtualBaseSpec = nullptr;
  3258. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3259. // We haven't found a base yet; search the class hierarchy for a
  3260. // virtual base class.
  3261. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3262. /*DetectVirtual=*/false);
  3263. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3264. SemaRef.Context.getTypeDeclType(ClassDecl),
  3265. BaseType, Paths)) {
  3266. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3267. Path != Paths.end(); ++Path) {
  3268. if (Path->back().Base->isVirtual()) {
  3269. VirtualBaseSpec = Path->back().Base;
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. }
  3275. return DirectBaseSpec || VirtualBaseSpec;
  3276. }
  3277. /// Handle a C++ member initializer using braced-init-list syntax.
  3278. MemInitResult
  3279. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3280. Scope *S,
  3281. CXXScopeSpec &SS,
  3282. IdentifierInfo *MemberOrBase,
  3283. ParsedType TemplateTypeTy,
  3284. const DeclSpec &DS,
  3285. SourceLocation IdLoc,
  3286. Expr *InitList,
  3287. SourceLocation EllipsisLoc) {
  3288. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3289. DS, IdLoc, InitList,
  3290. EllipsisLoc);
  3291. }
  3292. /// Handle a C++ member initializer using parentheses syntax.
  3293. MemInitResult
  3294. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3295. Scope *S,
  3296. CXXScopeSpec &SS,
  3297. IdentifierInfo *MemberOrBase,
  3298. ParsedType TemplateTypeTy,
  3299. const DeclSpec &DS,
  3300. SourceLocation IdLoc,
  3301. SourceLocation LParenLoc,
  3302. ArrayRef<Expr *> Args,
  3303. SourceLocation RParenLoc,
  3304. SourceLocation EllipsisLoc) {
  3305. Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
  3306. Args, RParenLoc);
  3307. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3308. DS, IdLoc, List, EllipsisLoc);
  3309. }
  3310. namespace {
  3311. // Callback to only accept typo corrections that can be a valid C++ member
  3312. // intializer: either a non-static field member or a base class.
  3313. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  3314. public:
  3315. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3316. : ClassDecl(ClassDecl) {}
  3317. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3318. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3319. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3320. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3321. return isa<TypeDecl>(ND);
  3322. }
  3323. return false;
  3324. }
  3325. private:
  3326. CXXRecordDecl *ClassDecl;
  3327. };
  3328. }
  3329. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3330. CXXScopeSpec &SS,
  3331. ParsedType TemplateTypeTy,
  3332. IdentifierInfo *MemberOrBase) {
  3333. if (SS.getScopeRep() || TemplateTypeTy)
  3334. return nullptr;
  3335. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3336. if (Result.empty())
  3337. return nullptr;
  3338. ValueDecl *Member;
  3339. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3340. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3341. return Member;
  3342. return nullptr;
  3343. }
  3344. /// Handle a C++ member initializer.
  3345. MemInitResult
  3346. Sema::BuildMemInitializer(Decl *ConstructorD,
  3347. Scope *S,
  3348. CXXScopeSpec &SS,
  3349. IdentifierInfo *MemberOrBase,
  3350. ParsedType TemplateTypeTy,
  3351. const DeclSpec &DS,
  3352. SourceLocation IdLoc,
  3353. Expr *Init,
  3354. SourceLocation EllipsisLoc) {
  3355. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3356. if (!Res.isUsable())
  3357. return true;
  3358. Init = Res.get();
  3359. if (!ConstructorD)
  3360. return true;
  3361. AdjustDeclIfTemplate(ConstructorD);
  3362. CXXConstructorDecl *Constructor
  3363. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3364. if (!Constructor) {
  3365. // The user wrote a constructor initializer on a function that is
  3366. // not a C++ constructor. Ignore the error for now, because we may
  3367. // have more member initializers coming; we'll diagnose it just
  3368. // once in ActOnMemInitializers.
  3369. return true;
  3370. }
  3371. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3372. // C++ [class.base.init]p2:
  3373. // Names in a mem-initializer-id are looked up in the scope of the
  3374. // constructor's class and, if not found in that scope, are looked
  3375. // up in the scope containing the constructor's definition.
  3376. // [Note: if the constructor's class contains a member with the
  3377. // same name as a direct or virtual base class of the class, a
  3378. // mem-initializer-id naming the member or base class and composed
  3379. // of a single identifier refers to the class member. A
  3380. // mem-initializer-id for the hidden base class may be specified
  3381. // using a qualified name. ]
  3382. // Look for a member, first.
  3383. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3384. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3385. if (EllipsisLoc.isValid())
  3386. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3387. << MemberOrBase
  3388. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3389. return BuildMemberInitializer(Member, Init, IdLoc);
  3390. }
  3391. // It didn't name a member, so see if it names a class.
  3392. QualType BaseType;
  3393. TypeSourceInfo *TInfo = nullptr;
  3394. if (TemplateTypeTy) {
  3395. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3396. } else if (DS.getTypeSpecType() == TST_decltype) {
  3397. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3398. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3399. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3400. return true;
  3401. } else {
  3402. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3403. LookupParsedName(R, S, &SS);
  3404. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3405. if (!TyD) {
  3406. if (R.isAmbiguous()) return true;
  3407. // We don't want access-control diagnostics here.
  3408. R.suppressDiagnostics();
  3409. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3410. bool NotUnknownSpecialization = false;
  3411. DeclContext *DC = computeDeclContext(SS, false);
  3412. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3413. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3414. if (!NotUnknownSpecialization) {
  3415. // When the scope specifier can refer to a member of an unknown
  3416. // specialization, we take it as a type name.
  3417. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3418. SS.getWithLocInContext(Context),
  3419. *MemberOrBase, IdLoc);
  3420. if (BaseType.isNull())
  3421. return true;
  3422. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3423. DependentNameTypeLoc TL =
  3424. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3425. if (!TL.isNull()) {
  3426. TL.setNameLoc(IdLoc);
  3427. TL.setElaboratedKeywordLoc(SourceLocation());
  3428. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3429. }
  3430. R.clear();
  3431. R.setLookupName(MemberOrBase);
  3432. }
  3433. }
  3434. // If no results were found, try to correct typos.
  3435. TypoCorrection Corr;
  3436. if (R.empty() && BaseType.isNull() &&
  3437. (Corr = CorrectTypo(
  3438. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3439. llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
  3440. CTK_ErrorRecovery, ClassDecl))) {
  3441. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3442. // We have found a non-static data member with a similar
  3443. // name to what was typed; complain and initialize that
  3444. // member.
  3445. diagnoseTypo(Corr,
  3446. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3447. << MemberOrBase << true);
  3448. return BuildMemberInitializer(Member, Init, IdLoc);
  3449. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3450. const CXXBaseSpecifier *DirectBaseSpec;
  3451. const CXXBaseSpecifier *VirtualBaseSpec;
  3452. if (FindBaseInitializer(*this, ClassDecl,
  3453. Context.getTypeDeclType(Type),
  3454. DirectBaseSpec, VirtualBaseSpec)) {
  3455. // We have found a direct or virtual base class with a
  3456. // similar name to what was typed; complain and initialize
  3457. // that base class.
  3458. diagnoseTypo(Corr,
  3459. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3460. << MemberOrBase << false,
  3461. PDiag() /*Suppress note, we provide our own.*/);
  3462. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3463. : VirtualBaseSpec;
  3464. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3465. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3466. TyD = Type;
  3467. }
  3468. }
  3469. }
  3470. if (!TyD && BaseType.isNull()) {
  3471. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3472. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3473. return true;
  3474. }
  3475. }
  3476. if (BaseType.isNull()) {
  3477. BaseType = Context.getTypeDeclType(TyD);
  3478. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3479. if (SS.isSet()) {
  3480. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3481. BaseType);
  3482. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3483. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3484. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3485. TL.setElaboratedKeywordLoc(SourceLocation());
  3486. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3487. }
  3488. }
  3489. }
  3490. if (!TInfo)
  3491. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3492. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3493. }
  3494. MemInitResult
  3495. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3496. SourceLocation IdLoc) {
  3497. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3498. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3499. assert((DirectMember || IndirectMember) &&
  3500. "Member must be a FieldDecl or IndirectFieldDecl");
  3501. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3502. return true;
  3503. if (Member->isInvalidDecl())
  3504. return true;
  3505. MultiExprArg Args;
  3506. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3507. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3508. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3509. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3510. } else {
  3511. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3512. Args = Init;
  3513. }
  3514. SourceRange InitRange = Init->getSourceRange();
  3515. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3516. // Can't check initialization for a member of dependent type or when
  3517. // any of the arguments are type-dependent expressions.
  3518. DiscardCleanupsInEvaluationContext();
  3519. } else {
  3520. bool InitList = false;
  3521. if (isa<InitListExpr>(Init)) {
  3522. InitList = true;
  3523. Args = Init;
  3524. }
  3525. // Initialize the member.
  3526. InitializedEntity MemberEntity =
  3527. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3528. : InitializedEntity::InitializeMember(IndirectMember,
  3529. nullptr);
  3530. InitializationKind Kind =
  3531. InitList ? InitializationKind::CreateDirectList(
  3532. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3533. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3534. InitRange.getEnd());
  3535. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3536. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3537. nullptr);
  3538. if (MemberInit.isInvalid())
  3539. return true;
  3540. // C++11 [class.base.init]p7:
  3541. // The initialization of each base and member constitutes a
  3542. // full-expression.
  3543. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
  3544. if (MemberInit.isInvalid())
  3545. return true;
  3546. Init = MemberInit.get();
  3547. }
  3548. if (DirectMember) {
  3549. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3550. InitRange.getBegin(), Init,
  3551. InitRange.getEnd());
  3552. } else {
  3553. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3554. InitRange.getBegin(), Init,
  3555. InitRange.getEnd());
  3556. }
  3557. }
  3558. MemInitResult
  3559. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3560. CXXRecordDecl *ClassDecl) {
  3561. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3562. if (!LangOpts.CPlusPlus11)
  3563. return Diag(NameLoc, diag::err_delegating_ctor)
  3564. << TInfo->getTypeLoc().getLocalSourceRange();
  3565. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3566. bool InitList = true;
  3567. MultiExprArg Args = Init;
  3568. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3569. InitList = false;
  3570. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3571. }
  3572. SourceRange InitRange = Init->getSourceRange();
  3573. // Initialize the object.
  3574. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3575. QualType(ClassDecl->getTypeForDecl(), 0));
  3576. InitializationKind Kind =
  3577. InitList ? InitializationKind::CreateDirectList(
  3578. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3579. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3580. InitRange.getEnd());
  3581. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3582. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3583. Args, nullptr);
  3584. if (DelegationInit.isInvalid())
  3585. return true;
  3586. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3587. "Delegating constructor with no target?");
  3588. // C++11 [class.base.init]p7:
  3589. // The initialization of each base and member constitutes a
  3590. // full-expression.
  3591. DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
  3592. InitRange.getBegin());
  3593. if (DelegationInit.isInvalid())
  3594. return true;
  3595. // If we are in a dependent context, template instantiation will
  3596. // perform this type-checking again. Just save the arguments that we
  3597. // received in a ParenListExpr.
  3598. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3599. // of the information that we have about the base
  3600. // initializer. However, deconstructing the ASTs is a dicey process,
  3601. // and this approach is far more likely to get the corner cases right.
  3602. if (CurContext->isDependentContext())
  3603. DelegationInit = Init;
  3604. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3605. DelegationInit.getAs<Expr>(),
  3606. InitRange.getEnd());
  3607. }
  3608. MemInitResult
  3609. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3610. Expr *Init, CXXRecordDecl *ClassDecl,
  3611. SourceLocation EllipsisLoc) {
  3612. SourceLocation BaseLoc
  3613. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3614. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3615. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3616. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3617. // C++ [class.base.init]p2:
  3618. // [...] Unless the mem-initializer-id names a nonstatic data
  3619. // member of the constructor's class or a direct or virtual base
  3620. // of that class, the mem-initializer is ill-formed. A
  3621. // mem-initializer-list can initialize a base class using any
  3622. // name that denotes that base class type.
  3623. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3624. SourceRange InitRange = Init->getSourceRange();
  3625. if (EllipsisLoc.isValid()) {
  3626. // This is a pack expansion.
  3627. if (!BaseType->containsUnexpandedParameterPack()) {
  3628. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3629. << SourceRange(BaseLoc, InitRange.getEnd());
  3630. EllipsisLoc = SourceLocation();
  3631. }
  3632. } else {
  3633. // Check for any unexpanded parameter packs.
  3634. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3635. return true;
  3636. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3637. return true;
  3638. }
  3639. // Check for direct and virtual base classes.
  3640. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3641. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3642. if (!Dependent) {
  3643. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3644. BaseType))
  3645. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3646. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3647. VirtualBaseSpec);
  3648. // C++ [base.class.init]p2:
  3649. // Unless the mem-initializer-id names a nonstatic data member of the
  3650. // constructor's class or a direct or virtual base of that class, the
  3651. // mem-initializer is ill-formed.
  3652. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3653. // If the class has any dependent bases, then it's possible that
  3654. // one of those types will resolve to the same type as
  3655. // BaseType. Therefore, just treat this as a dependent base
  3656. // class initialization. FIXME: Should we try to check the
  3657. // initialization anyway? It seems odd.
  3658. if (ClassDecl->hasAnyDependentBases())
  3659. Dependent = true;
  3660. else
  3661. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3662. << BaseType << Context.getTypeDeclType(ClassDecl)
  3663. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3664. }
  3665. }
  3666. if (Dependent) {
  3667. DiscardCleanupsInEvaluationContext();
  3668. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3669. /*IsVirtual=*/false,
  3670. InitRange.getBegin(), Init,
  3671. InitRange.getEnd(), EllipsisLoc);
  3672. }
  3673. // C++ [base.class.init]p2:
  3674. // If a mem-initializer-id is ambiguous because it designates both
  3675. // a direct non-virtual base class and an inherited virtual base
  3676. // class, the mem-initializer is ill-formed.
  3677. if (DirectBaseSpec && VirtualBaseSpec)
  3678. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3679. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3680. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3681. if (!BaseSpec)
  3682. BaseSpec = VirtualBaseSpec;
  3683. // Initialize the base.
  3684. bool InitList = true;
  3685. MultiExprArg Args = Init;
  3686. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3687. InitList = false;
  3688. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3689. }
  3690. InitializedEntity BaseEntity =
  3691. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3692. InitializationKind Kind =
  3693. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3694. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3695. InitRange.getEnd());
  3696. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3697. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3698. if (BaseInit.isInvalid())
  3699. return true;
  3700. // C++11 [class.base.init]p7:
  3701. // The initialization of each base and member constitutes a
  3702. // full-expression.
  3703. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
  3704. if (BaseInit.isInvalid())
  3705. return true;
  3706. // If we are in a dependent context, template instantiation will
  3707. // perform this type-checking again. Just save the arguments that we
  3708. // received in a ParenListExpr.
  3709. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3710. // of the information that we have about the base
  3711. // initializer. However, deconstructing the ASTs is a dicey process,
  3712. // and this approach is far more likely to get the corner cases right.
  3713. if (CurContext->isDependentContext())
  3714. BaseInit = Init;
  3715. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3716. BaseSpec->isVirtual(),
  3717. InitRange.getBegin(),
  3718. BaseInit.getAs<Expr>(),
  3719. InitRange.getEnd(), EllipsisLoc);
  3720. }
  3721. // Create a static_cast\<T&&>(expr).
  3722. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3723. if (T.isNull()) T = E->getType();
  3724. QualType TargetType = SemaRef.BuildReferenceType(
  3725. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3726. SourceLocation ExprLoc = E->getBeginLoc();
  3727. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3728. TargetType, ExprLoc);
  3729. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3730. SourceRange(ExprLoc, ExprLoc),
  3731. E->getSourceRange()).get();
  3732. }
  3733. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3734. /// initialize its base or member.
  3735. enum ImplicitInitializerKind {
  3736. IIK_Default,
  3737. IIK_Copy,
  3738. IIK_Move,
  3739. IIK_Inherit
  3740. };
  3741. static bool
  3742. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3743. ImplicitInitializerKind ImplicitInitKind,
  3744. CXXBaseSpecifier *BaseSpec,
  3745. bool IsInheritedVirtualBase,
  3746. CXXCtorInitializer *&CXXBaseInit) {
  3747. InitializedEntity InitEntity
  3748. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3749. IsInheritedVirtualBase);
  3750. ExprResult BaseInit;
  3751. switch (ImplicitInitKind) {
  3752. case IIK_Inherit:
  3753. case IIK_Default: {
  3754. InitializationKind InitKind
  3755. = InitializationKind::CreateDefault(Constructor->getLocation());
  3756. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3757. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3758. break;
  3759. }
  3760. case IIK_Move:
  3761. case IIK_Copy: {
  3762. bool Moving = ImplicitInitKind == IIK_Move;
  3763. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3764. QualType ParamType = Param->getType().getNonReferenceType();
  3765. Expr *CopyCtorArg =
  3766. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3767. SourceLocation(), Param, false,
  3768. Constructor->getLocation(), ParamType,
  3769. VK_LValue, nullptr);
  3770. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3771. // Cast to the base class to avoid ambiguities.
  3772. QualType ArgTy =
  3773. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3774. ParamType.getQualifiers());
  3775. if (Moving) {
  3776. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3777. }
  3778. CXXCastPath BasePath;
  3779. BasePath.push_back(BaseSpec);
  3780. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3781. CK_UncheckedDerivedToBase,
  3782. Moving ? VK_XValue : VK_LValue,
  3783. &BasePath).get();
  3784. InitializationKind InitKind
  3785. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3786. SourceLocation(), SourceLocation());
  3787. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3788. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3789. break;
  3790. }
  3791. }
  3792. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3793. if (BaseInit.isInvalid())
  3794. return true;
  3795. CXXBaseInit =
  3796. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3797. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3798. SourceLocation()),
  3799. BaseSpec->isVirtual(),
  3800. SourceLocation(),
  3801. BaseInit.getAs<Expr>(),
  3802. SourceLocation(),
  3803. SourceLocation());
  3804. return false;
  3805. }
  3806. static bool RefersToRValueRef(Expr *MemRef) {
  3807. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3808. return Referenced->getType()->isRValueReferenceType();
  3809. }
  3810. static bool
  3811. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3812. ImplicitInitializerKind ImplicitInitKind,
  3813. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3814. CXXCtorInitializer *&CXXMemberInit) {
  3815. if (Field->isInvalidDecl())
  3816. return true;
  3817. SourceLocation Loc = Constructor->getLocation();
  3818. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3819. bool Moving = ImplicitInitKind == IIK_Move;
  3820. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3821. QualType ParamType = Param->getType().getNonReferenceType();
  3822. // Suppress copying zero-width bitfields.
  3823. if (Field->isZeroLengthBitField(SemaRef.Context))
  3824. return false;
  3825. Expr *MemberExprBase =
  3826. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3827. SourceLocation(), Param, false,
  3828. Loc, ParamType, VK_LValue, nullptr);
  3829. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3830. if (Moving) {
  3831. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3832. }
  3833. // Build a reference to this field within the parameter.
  3834. CXXScopeSpec SS;
  3835. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3836. Sema::LookupMemberName);
  3837. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3838. : cast<ValueDecl>(Field), AS_public);
  3839. MemberLookup.resolveKind();
  3840. ExprResult CtorArg
  3841. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3842. ParamType, Loc,
  3843. /*IsArrow=*/false,
  3844. SS,
  3845. /*TemplateKWLoc=*/SourceLocation(),
  3846. /*FirstQualifierInScope=*/nullptr,
  3847. MemberLookup,
  3848. /*TemplateArgs=*/nullptr,
  3849. /*S*/nullptr);
  3850. if (CtorArg.isInvalid())
  3851. return true;
  3852. // C++11 [class.copy]p15:
  3853. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3854. // with static_cast<T&&>(x.m);
  3855. if (RefersToRValueRef(CtorArg.get())) {
  3856. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3857. }
  3858. InitializedEntity Entity =
  3859. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3860. /*Implicit*/ true)
  3861. : InitializedEntity::InitializeMember(Field, nullptr,
  3862. /*Implicit*/ true);
  3863. // Direct-initialize to use the copy constructor.
  3864. InitializationKind InitKind =
  3865. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3866. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3867. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  3868. ExprResult MemberInit =
  3869. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  3870. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3871. if (MemberInit.isInvalid())
  3872. return true;
  3873. if (Indirect)
  3874. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3875. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3876. else
  3877. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3878. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3879. return false;
  3880. }
  3881. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3882. "Unhandled implicit init kind!");
  3883. QualType FieldBaseElementType =
  3884. SemaRef.Context.getBaseElementType(Field->getType());
  3885. if (FieldBaseElementType->isRecordType()) {
  3886. InitializedEntity InitEntity =
  3887. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3888. /*Implicit*/ true)
  3889. : InitializedEntity::InitializeMember(Field, nullptr,
  3890. /*Implicit*/ true);
  3891. InitializationKind InitKind =
  3892. InitializationKind::CreateDefault(Loc);
  3893. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3894. ExprResult MemberInit =
  3895. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3896. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3897. if (MemberInit.isInvalid())
  3898. return true;
  3899. if (Indirect)
  3900. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3901. Indirect, Loc,
  3902. Loc,
  3903. MemberInit.get(),
  3904. Loc);
  3905. else
  3906. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3907. Field, Loc, Loc,
  3908. MemberInit.get(),
  3909. Loc);
  3910. return false;
  3911. }
  3912. if (!Field->getParent()->isUnion()) {
  3913. if (FieldBaseElementType->isReferenceType()) {
  3914. SemaRef.Diag(Constructor->getLocation(),
  3915. diag::err_uninitialized_member_in_ctor)
  3916. << (int)Constructor->isImplicit()
  3917. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3918. << 0 << Field->getDeclName();
  3919. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3920. return true;
  3921. }
  3922. if (FieldBaseElementType.isConstQualified()) {
  3923. SemaRef.Diag(Constructor->getLocation(),
  3924. diag::err_uninitialized_member_in_ctor)
  3925. << (int)Constructor->isImplicit()
  3926. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3927. << 1 << Field->getDeclName();
  3928. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3929. return true;
  3930. }
  3931. }
  3932. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  3933. // ARC and Weak:
  3934. // Default-initialize Objective-C pointers to NULL.
  3935. CXXMemberInit
  3936. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3937. Loc, Loc,
  3938. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3939. Loc);
  3940. return false;
  3941. }
  3942. // Nothing to initialize.
  3943. CXXMemberInit = nullptr;
  3944. return false;
  3945. }
  3946. namespace {
  3947. struct BaseAndFieldInfo {
  3948. Sema &S;
  3949. CXXConstructorDecl *Ctor;
  3950. bool AnyErrorsInInits;
  3951. ImplicitInitializerKind IIK;
  3952. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  3953. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  3954. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  3955. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  3956. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  3957. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  3958. if (Ctor->getInheritedConstructor())
  3959. IIK = IIK_Inherit;
  3960. else if (Generated && Ctor->isCopyConstructor())
  3961. IIK = IIK_Copy;
  3962. else if (Generated && Ctor->isMoveConstructor())
  3963. IIK = IIK_Move;
  3964. else
  3965. IIK = IIK_Default;
  3966. }
  3967. bool isImplicitCopyOrMove() const {
  3968. switch (IIK) {
  3969. case IIK_Copy:
  3970. case IIK_Move:
  3971. return true;
  3972. case IIK_Default:
  3973. case IIK_Inherit:
  3974. return false;
  3975. }
  3976. llvm_unreachable("Invalid ImplicitInitializerKind!");
  3977. }
  3978. bool addFieldInitializer(CXXCtorInitializer *Init) {
  3979. AllToInit.push_back(Init);
  3980. // Check whether this initializer makes the field "used".
  3981. if (Init->getInit()->HasSideEffects(S.Context))
  3982. S.UnusedPrivateFields.remove(Init->getAnyMember());
  3983. return false;
  3984. }
  3985. bool isInactiveUnionMember(FieldDecl *Field) {
  3986. RecordDecl *Record = Field->getParent();
  3987. if (!Record->isUnion())
  3988. return false;
  3989. if (FieldDecl *Active =
  3990. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  3991. return Active != Field->getCanonicalDecl();
  3992. // In an implicit copy or move constructor, ignore any in-class initializer.
  3993. if (isImplicitCopyOrMove())
  3994. return true;
  3995. // If there's no explicit initialization, the field is active only if it
  3996. // has an in-class initializer...
  3997. if (Field->hasInClassInitializer())
  3998. return false;
  3999. // ... or it's an anonymous struct or union whose class has an in-class
  4000. // initializer.
  4001. if (!Field->isAnonymousStructOrUnion())
  4002. return true;
  4003. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4004. return !FieldRD->hasInClassInitializer();
  4005. }
  4006. /// Determine whether the given field is, or is within, a union member
  4007. /// that is inactive (because there was an initializer given for a different
  4008. /// member of the union, or because the union was not initialized at all).
  4009. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4010. IndirectFieldDecl *Indirect) {
  4011. if (!Indirect)
  4012. return isInactiveUnionMember(Field);
  4013. for (auto *C : Indirect->chain()) {
  4014. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4015. if (Field && isInactiveUnionMember(Field))
  4016. return true;
  4017. }
  4018. return false;
  4019. }
  4020. };
  4021. }
  4022. /// Determine whether the given type is an incomplete or zero-lenfgth
  4023. /// array type.
  4024. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4025. if (T->isIncompleteArrayType())
  4026. return true;
  4027. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4028. if (!ArrayT->getSize())
  4029. return true;
  4030. T = ArrayT->getElementType();
  4031. }
  4032. return false;
  4033. }
  4034. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4035. FieldDecl *Field,
  4036. IndirectFieldDecl *Indirect = nullptr) {
  4037. if (Field->isInvalidDecl())
  4038. return false;
  4039. // Overwhelmingly common case: we have a direct initializer for this field.
  4040. if (CXXCtorInitializer *Init =
  4041. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4042. return Info.addFieldInitializer(Init);
  4043. // C++11 [class.base.init]p8:
  4044. // if the entity is a non-static data member that has a
  4045. // brace-or-equal-initializer and either
  4046. // -- the constructor's class is a union and no other variant member of that
  4047. // union is designated by a mem-initializer-id or
  4048. // -- the constructor's class is not a union, and, if the entity is a member
  4049. // of an anonymous union, no other member of that union is designated by
  4050. // a mem-initializer-id,
  4051. // the entity is initialized as specified in [dcl.init].
  4052. //
  4053. // We also apply the same rules to handle anonymous structs within anonymous
  4054. // unions.
  4055. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4056. return false;
  4057. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4058. ExprResult DIE =
  4059. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4060. if (DIE.isInvalid())
  4061. return true;
  4062. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4063. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4064. CXXCtorInitializer *Init;
  4065. if (Indirect)
  4066. Init = new (SemaRef.Context)
  4067. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4068. SourceLocation(), DIE.get(), SourceLocation());
  4069. else
  4070. Init = new (SemaRef.Context)
  4071. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4072. SourceLocation(), DIE.get(), SourceLocation());
  4073. return Info.addFieldInitializer(Init);
  4074. }
  4075. // Don't initialize incomplete or zero-length arrays.
  4076. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4077. return false;
  4078. // Don't try to build an implicit initializer if there were semantic
  4079. // errors in any of the initializers (and therefore we might be
  4080. // missing some that the user actually wrote).
  4081. if (Info.AnyErrorsInInits)
  4082. return false;
  4083. CXXCtorInitializer *Init = nullptr;
  4084. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4085. Indirect, Init))
  4086. return true;
  4087. if (!Init)
  4088. return false;
  4089. return Info.addFieldInitializer(Init);
  4090. }
  4091. bool
  4092. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4093. CXXCtorInitializer *Initializer) {
  4094. assert(Initializer->isDelegatingInitializer());
  4095. Constructor->setNumCtorInitializers(1);
  4096. CXXCtorInitializer **initializer =
  4097. new (Context) CXXCtorInitializer*[1];
  4098. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4099. Constructor->setCtorInitializers(initializer);
  4100. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4101. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4102. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4103. }
  4104. DelegatingCtorDecls.push_back(Constructor);
  4105. DiagnoseUninitializedFields(*this, Constructor);
  4106. return false;
  4107. }
  4108. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4109. ArrayRef<CXXCtorInitializer *> Initializers) {
  4110. if (Constructor->isDependentContext()) {
  4111. // Just store the initializers as written, they will be checked during
  4112. // instantiation.
  4113. if (!Initializers.empty()) {
  4114. Constructor->setNumCtorInitializers(Initializers.size());
  4115. CXXCtorInitializer **baseOrMemberInitializers =
  4116. new (Context) CXXCtorInitializer*[Initializers.size()];
  4117. memcpy(baseOrMemberInitializers, Initializers.data(),
  4118. Initializers.size() * sizeof(CXXCtorInitializer*));
  4119. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4120. }
  4121. // Let template instantiation know whether we had errors.
  4122. if (AnyErrors)
  4123. Constructor->setInvalidDecl();
  4124. return false;
  4125. }
  4126. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4127. // We need to build the initializer AST according to order of construction
  4128. // and not what user specified in the Initializers list.
  4129. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4130. if (!ClassDecl)
  4131. return true;
  4132. bool HadError = false;
  4133. for (unsigned i = 0; i < Initializers.size(); i++) {
  4134. CXXCtorInitializer *Member = Initializers[i];
  4135. if (Member->isBaseInitializer())
  4136. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4137. else {
  4138. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4139. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4140. for (auto *C : F->chain()) {
  4141. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4142. if (FD && FD->getParent()->isUnion())
  4143. Info.ActiveUnionMember.insert(std::make_pair(
  4144. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4145. }
  4146. } else if (FieldDecl *FD = Member->getMember()) {
  4147. if (FD->getParent()->isUnion())
  4148. Info.ActiveUnionMember.insert(std::make_pair(
  4149. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4150. }
  4151. }
  4152. }
  4153. // Keep track of the direct virtual bases.
  4154. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4155. for (auto &I : ClassDecl->bases()) {
  4156. if (I.isVirtual())
  4157. DirectVBases.insert(&I);
  4158. }
  4159. // Push virtual bases before others.
  4160. for (auto &VBase : ClassDecl->vbases()) {
  4161. if (CXXCtorInitializer *Value
  4162. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4163. // [class.base.init]p7, per DR257:
  4164. // A mem-initializer where the mem-initializer-id names a virtual base
  4165. // class is ignored during execution of a constructor of any class that
  4166. // is not the most derived class.
  4167. if (ClassDecl->isAbstract()) {
  4168. // FIXME: Provide a fixit to remove the base specifier. This requires
  4169. // tracking the location of the associated comma for a base specifier.
  4170. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4171. << VBase.getType() << ClassDecl;
  4172. DiagnoseAbstractType(ClassDecl);
  4173. }
  4174. Info.AllToInit.push_back(Value);
  4175. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4176. // [class.base.init]p8, per DR257:
  4177. // If a given [...] base class is not named by a mem-initializer-id
  4178. // [...] and the entity is not a virtual base class of an abstract
  4179. // class, then [...] the entity is default-initialized.
  4180. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4181. CXXCtorInitializer *CXXBaseInit;
  4182. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4183. &VBase, IsInheritedVirtualBase,
  4184. CXXBaseInit)) {
  4185. HadError = true;
  4186. continue;
  4187. }
  4188. Info.AllToInit.push_back(CXXBaseInit);
  4189. }
  4190. }
  4191. // Non-virtual bases.
  4192. for (auto &Base : ClassDecl->bases()) {
  4193. // Virtuals are in the virtual base list and already constructed.
  4194. if (Base.isVirtual())
  4195. continue;
  4196. if (CXXCtorInitializer *Value
  4197. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4198. Info.AllToInit.push_back(Value);
  4199. } else if (!AnyErrors) {
  4200. CXXCtorInitializer *CXXBaseInit;
  4201. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4202. &Base, /*IsInheritedVirtualBase=*/false,
  4203. CXXBaseInit)) {
  4204. HadError = true;
  4205. continue;
  4206. }
  4207. Info.AllToInit.push_back(CXXBaseInit);
  4208. }
  4209. }
  4210. // Fields.
  4211. for (auto *Mem : ClassDecl->decls()) {
  4212. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4213. // C++ [class.bit]p2:
  4214. // A declaration for a bit-field that omits the identifier declares an
  4215. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4216. // initialized.
  4217. if (F->isUnnamedBitfield())
  4218. continue;
  4219. // If we're not generating the implicit copy/move constructor, then we'll
  4220. // handle anonymous struct/union fields based on their individual
  4221. // indirect fields.
  4222. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4223. continue;
  4224. if (CollectFieldInitializer(*this, Info, F))
  4225. HadError = true;
  4226. continue;
  4227. }
  4228. // Beyond this point, we only consider default initialization.
  4229. if (Info.isImplicitCopyOrMove())
  4230. continue;
  4231. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4232. if (F->getType()->isIncompleteArrayType()) {
  4233. assert(ClassDecl->hasFlexibleArrayMember() &&
  4234. "Incomplete array type is not valid");
  4235. continue;
  4236. }
  4237. // Initialize each field of an anonymous struct individually.
  4238. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4239. HadError = true;
  4240. continue;
  4241. }
  4242. }
  4243. unsigned NumInitializers = Info.AllToInit.size();
  4244. if (NumInitializers > 0) {
  4245. Constructor->setNumCtorInitializers(NumInitializers);
  4246. CXXCtorInitializer **baseOrMemberInitializers =
  4247. new (Context) CXXCtorInitializer*[NumInitializers];
  4248. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4249. NumInitializers * sizeof(CXXCtorInitializer*));
  4250. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4251. // Constructors implicitly reference the base and member
  4252. // destructors.
  4253. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4254. Constructor->getParent());
  4255. }
  4256. return HadError;
  4257. }
  4258. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4259. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4260. const RecordDecl *RD = RT->getDecl();
  4261. if (RD->isAnonymousStructOrUnion()) {
  4262. for (auto *Field : RD->fields())
  4263. PopulateKeysForFields(Field, IdealInits);
  4264. return;
  4265. }
  4266. }
  4267. IdealInits.push_back(Field->getCanonicalDecl());
  4268. }
  4269. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4270. return Context.getCanonicalType(BaseType).getTypePtr();
  4271. }
  4272. static const void *GetKeyForMember(ASTContext &Context,
  4273. CXXCtorInitializer *Member) {
  4274. if (!Member->isAnyMemberInitializer())
  4275. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4276. return Member->getAnyMember()->getCanonicalDecl();
  4277. }
  4278. static void DiagnoseBaseOrMemInitializerOrder(
  4279. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4280. ArrayRef<CXXCtorInitializer *> Inits) {
  4281. if (Constructor->getDeclContext()->isDependentContext())
  4282. return;
  4283. // Don't check initializers order unless the warning is enabled at the
  4284. // location of at least one initializer.
  4285. bool ShouldCheckOrder = false;
  4286. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4287. CXXCtorInitializer *Init = Inits[InitIndex];
  4288. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4289. Init->getSourceLocation())) {
  4290. ShouldCheckOrder = true;
  4291. break;
  4292. }
  4293. }
  4294. if (!ShouldCheckOrder)
  4295. return;
  4296. // Build the list of bases and members in the order that they'll
  4297. // actually be initialized. The explicit initializers should be in
  4298. // this same order but may be missing things.
  4299. SmallVector<const void*, 32> IdealInitKeys;
  4300. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4301. // 1. Virtual bases.
  4302. for (const auto &VBase : ClassDecl->vbases())
  4303. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4304. // 2. Non-virtual bases.
  4305. for (const auto &Base : ClassDecl->bases()) {
  4306. if (Base.isVirtual())
  4307. continue;
  4308. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4309. }
  4310. // 3. Direct fields.
  4311. for (auto *Field : ClassDecl->fields()) {
  4312. if (Field->isUnnamedBitfield())
  4313. continue;
  4314. PopulateKeysForFields(Field, IdealInitKeys);
  4315. }
  4316. unsigned NumIdealInits = IdealInitKeys.size();
  4317. unsigned IdealIndex = 0;
  4318. CXXCtorInitializer *PrevInit = nullptr;
  4319. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4320. CXXCtorInitializer *Init = Inits[InitIndex];
  4321. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4322. // Scan forward to try to find this initializer in the idealized
  4323. // initializers list.
  4324. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4325. if (InitKey == IdealInitKeys[IdealIndex])
  4326. break;
  4327. // If we didn't find this initializer, it must be because we
  4328. // scanned past it on a previous iteration. That can only
  4329. // happen if we're out of order; emit a warning.
  4330. if (IdealIndex == NumIdealInits && PrevInit) {
  4331. Sema::SemaDiagnosticBuilder D =
  4332. SemaRef.Diag(PrevInit->getSourceLocation(),
  4333. diag::warn_initializer_out_of_order);
  4334. if (PrevInit->isAnyMemberInitializer())
  4335. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4336. else
  4337. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4338. if (Init->isAnyMemberInitializer())
  4339. D << 0 << Init->getAnyMember()->getDeclName();
  4340. else
  4341. D << 1 << Init->getTypeSourceInfo()->getType();
  4342. // Move back to the initializer's location in the ideal list.
  4343. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4344. if (InitKey == IdealInitKeys[IdealIndex])
  4345. break;
  4346. assert(IdealIndex < NumIdealInits &&
  4347. "initializer not found in initializer list");
  4348. }
  4349. PrevInit = Init;
  4350. }
  4351. }
  4352. namespace {
  4353. bool CheckRedundantInit(Sema &S,
  4354. CXXCtorInitializer *Init,
  4355. CXXCtorInitializer *&PrevInit) {
  4356. if (!PrevInit) {
  4357. PrevInit = Init;
  4358. return false;
  4359. }
  4360. if (FieldDecl *Field = Init->getAnyMember())
  4361. S.Diag(Init->getSourceLocation(),
  4362. diag::err_multiple_mem_initialization)
  4363. << Field->getDeclName()
  4364. << Init->getSourceRange();
  4365. else {
  4366. const Type *BaseClass = Init->getBaseClass();
  4367. assert(BaseClass && "neither field nor base");
  4368. S.Diag(Init->getSourceLocation(),
  4369. diag::err_multiple_base_initialization)
  4370. << QualType(BaseClass, 0)
  4371. << Init->getSourceRange();
  4372. }
  4373. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4374. << 0 << PrevInit->getSourceRange();
  4375. return true;
  4376. }
  4377. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4378. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4379. bool CheckRedundantUnionInit(Sema &S,
  4380. CXXCtorInitializer *Init,
  4381. RedundantUnionMap &Unions) {
  4382. FieldDecl *Field = Init->getAnyMember();
  4383. RecordDecl *Parent = Field->getParent();
  4384. NamedDecl *Child = Field;
  4385. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4386. if (Parent->isUnion()) {
  4387. UnionEntry &En = Unions[Parent];
  4388. if (En.first && En.first != Child) {
  4389. S.Diag(Init->getSourceLocation(),
  4390. diag::err_multiple_mem_union_initialization)
  4391. << Field->getDeclName()
  4392. << Init->getSourceRange();
  4393. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4394. << 0 << En.second->getSourceRange();
  4395. return true;
  4396. }
  4397. if (!En.first) {
  4398. En.first = Child;
  4399. En.second = Init;
  4400. }
  4401. if (!Parent->isAnonymousStructOrUnion())
  4402. return false;
  4403. }
  4404. Child = Parent;
  4405. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4406. }
  4407. return false;
  4408. }
  4409. }
  4410. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4411. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4412. SourceLocation ColonLoc,
  4413. ArrayRef<CXXCtorInitializer*> MemInits,
  4414. bool AnyErrors) {
  4415. if (!ConstructorDecl)
  4416. return;
  4417. AdjustDeclIfTemplate(ConstructorDecl);
  4418. CXXConstructorDecl *Constructor
  4419. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4420. if (!Constructor) {
  4421. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4422. return;
  4423. }
  4424. // Mapping for the duplicate initializers check.
  4425. // For member initializers, this is keyed with a FieldDecl*.
  4426. // For base initializers, this is keyed with a Type*.
  4427. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4428. // Mapping for the inconsistent anonymous-union initializers check.
  4429. RedundantUnionMap MemberUnions;
  4430. bool HadError = false;
  4431. for (unsigned i = 0; i < MemInits.size(); i++) {
  4432. CXXCtorInitializer *Init = MemInits[i];
  4433. // Set the source order index.
  4434. Init->setSourceOrder(i);
  4435. if (Init->isAnyMemberInitializer()) {
  4436. const void *Key = GetKeyForMember(Context, Init);
  4437. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4438. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4439. HadError = true;
  4440. } else if (Init->isBaseInitializer()) {
  4441. const void *Key = GetKeyForMember(Context, Init);
  4442. if (CheckRedundantInit(*this, Init, Members[Key]))
  4443. HadError = true;
  4444. } else {
  4445. assert(Init->isDelegatingInitializer());
  4446. // This must be the only initializer
  4447. if (MemInits.size() != 1) {
  4448. Diag(Init->getSourceLocation(),
  4449. diag::err_delegating_initializer_alone)
  4450. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4451. // We will treat this as being the only initializer.
  4452. }
  4453. SetDelegatingInitializer(Constructor, MemInits[i]);
  4454. // Return immediately as the initializer is set.
  4455. return;
  4456. }
  4457. }
  4458. if (HadError)
  4459. return;
  4460. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4461. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4462. DiagnoseUninitializedFields(*this, Constructor);
  4463. }
  4464. void
  4465. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4466. CXXRecordDecl *ClassDecl) {
  4467. // Ignore dependent contexts. Also ignore unions, since their members never
  4468. // have destructors implicitly called.
  4469. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4470. return;
  4471. // FIXME: all the access-control diagnostics are positioned on the
  4472. // field/base declaration. That's probably good; that said, the
  4473. // user might reasonably want to know why the destructor is being
  4474. // emitted, and we currently don't say.
  4475. // Non-static data members.
  4476. for (auto *Field : ClassDecl->fields()) {
  4477. if (Field->isInvalidDecl())
  4478. continue;
  4479. // Don't destroy incomplete or zero-length arrays.
  4480. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4481. continue;
  4482. QualType FieldType = Context.getBaseElementType(Field->getType());
  4483. const RecordType* RT = FieldType->getAs<RecordType>();
  4484. if (!RT)
  4485. continue;
  4486. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4487. if (FieldClassDecl->isInvalidDecl())
  4488. continue;
  4489. if (FieldClassDecl->hasIrrelevantDestructor())
  4490. continue;
  4491. // The destructor for an implicit anonymous union member is never invoked.
  4492. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4493. continue;
  4494. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4495. assert(Dtor && "No dtor found for FieldClassDecl!");
  4496. CheckDestructorAccess(Field->getLocation(), Dtor,
  4497. PDiag(diag::err_access_dtor_field)
  4498. << Field->getDeclName()
  4499. << FieldType);
  4500. MarkFunctionReferenced(Location, Dtor);
  4501. DiagnoseUseOfDecl(Dtor, Location);
  4502. }
  4503. // We only potentially invoke the destructors of potentially constructed
  4504. // subobjects.
  4505. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4506. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4507. // Bases.
  4508. for (const auto &Base : ClassDecl->bases()) {
  4509. // Bases are always records in a well-formed non-dependent class.
  4510. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4511. // Remember direct virtual bases.
  4512. if (Base.isVirtual()) {
  4513. if (!VisitVirtualBases)
  4514. continue;
  4515. DirectVirtualBases.insert(RT);
  4516. }
  4517. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4518. // If our base class is invalid, we probably can't get its dtor anyway.
  4519. if (BaseClassDecl->isInvalidDecl())
  4520. continue;
  4521. if (BaseClassDecl->hasIrrelevantDestructor())
  4522. continue;
  4523. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4524. assert(Dtor && "No dtor found for BaseClassDecl!");
  4525. // FIXME: caret should be on the start of the class name
  4526. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4527. PDiag(diag::err_access_dtor_base)
  4528. << Base.getType() << Base.getSourceRange(),
  4529. Context.getTypeDeclType(ClassDecl));
  4530. MarkFunctionReferenced(Location, Dtor);
  4531. DiagnoseUseOfDecl(Dtor, Location);
  4532. }
  4533. if (!VisitVirtualBases)
  4534. return;
  4535. // Virtual bases.
  4536. for (const auto &VBase : ClassDecl->vbases()) {
  4537. // Bases are always records in a well-formed non-dependent class.
  4538. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4539. // Ignore direct virtual bases.
  4540. if (DirectVirtualBases.count(RT))
  4541. continue;
  4542. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4543. // If our base class is invalid, we probably can't get its dtor anyway.
  4544. if (BaseClassDecl->isInvalidDecl())
  4545. continue;
  4546. if (BaseClassDecl->hasIrrelevantDestructor())
  4547. continue;
  4548. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4549. assert(Dtor && "No dtor found for BaseClassDecl!");
  4550. if (CheckDestructorAccess(
  4551. ClassDecl->getLocation(), Dtor,
  4552. PDiag(diag::err_access_dtor_vbase)
  4553. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4554. Context.getTypeDeclType(ClassDecl)) ==
  4555. AR_accessible) {
  4556. CheckDerivedToBaseConversion(
  4557. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4558. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4559. SourceRange(), DeclarationName(), nullptr);
  4560. }
  4561. MarkFunctionReferenced(Location, Dtor);
  4562. DiagnoseUseOfDecl(Dtor, Location);
  4563. }
  4564. }
  4565. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4566. if (!CDtorDecl)
  4567. return;
  4568. if (CXXConstructorDecl *Constructor
  4569. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4570. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4571. DiagnoseUninitializedFields(*this, Constructor);
  4572. }
  4573. }
  4574. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4575. if (!getLangOpts().CPlusPlus)
  4576. return false;
  4577. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4578. if (!RD)
  4579. return false;
  4580. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4581. // class template specialization here, but doing so breaks a lot of code.
  4582. // We can't answer whether something is abstract until it has a
  4583. // definition. If it's currently being defined, we'll walk back
  4584. // over all the declarations when we have a full definition.
  4585. const CXXRecordDecl *Def = RD->getDefinition();
  4586. if (!Def || Def->isBeingDefined())
  4587. return false;
  4588. return RD->isAbstract();
  4589. }
  4590. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4591. TypeDiagnoser &Diagnoser) {
  4592. if (!isAbstractType(Loc, T))
  4593. return false;
  4594. T = Context.getBaseElementType(T);
  4595. Diagnoser.diagnose(*this, Loc, T);
  4596. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4597. return true;
  4598. }
  4599. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4600. // Check if we've already emitted the list of pure virtual functions
  4601. // for this class.
  4602. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4603. return;
  4604. // If the diagnostic is suppressed, don't emit the notes. We're only
  4605. // going to emit them once, so try to attach them to a diagnostic we're
  4606. // actually going to show.
  4607. if (Diags.isLastDiagnosticIgnored())
  4608. return;
  4609. CXXFinalOverriderMap FinalOverriders;
  4610. RD->getFinalOverriders(FinalOverriders);
  4611. // Keep a set of seen pure methods so we won't diagnose the same method
  4612. // more than once.
  4613. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4614. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4615. MEnd = FinalOverriders.end();
  4616. M != MEnd;
  4617. ++M) {
  4618. for (OverridingMethods::iterator SO = M->second.begin(),
  4619. SOEnd = M->second.end();
  4620. SO != SOEnd; ++SO) {
  4621. // C++ [class.abstract]p4:
  4622. // A class is abstract if it contains or inherits at least one
  4623. // pure virtual function for which the final overrider is pure
  4624. // virtual.
  4625. //
  4626. if (SO->second.size() != 1)
  4627. continue;
  4628. if (!SO->second.front().Method->isPure())
  4629. continue;
  4630. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4631. continue;
  4632. Diag(SO->second.front().Method->getLocation(),
  4633. diag::note_pure_virtual_function)
  4634. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4635. }
  4636. }
  4637. if (!PureVirtualClassDiagSet)
  4638. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4639. PureVirtualClassDiagSet->insert(RD);
  4640. }
  4641. namespace {
  4642. struct AbstractUsageInfo {
  4643. Sema &S;
  4644. CXXRecordDecl *Record;
  4645. CanQualType AbstractType;
  4646. bool Invalid;
  4647. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4648. : S(S), Record(Record),
  4649. AbstractType(S.Context.getCanonicalType(
  4650. S.Context.getTypeDeclType(Record))),
  4651. Invalid(false) {}
  4652. void DiagnoseAbstractType() {
  4653. if (Invalid) return;
  4654. S.DiagnoseAbstractType(Record);
  4655. Invalid = true;
  4656. }
  4657. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4658. };
  4659. struct CheckAbstractUsage {
  4660. AbstractUsageInfo &Info;
  4661. const NamedDecl *Ctx;
  4662. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4663. : Info(Info), Ctx(Ctx) {}
  4664. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4665. switch (TL.getTypeLocClass()) {
  4666. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4667. #define TYPELOC(CLASS, PARENT) \
  4668. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4669. #include "clang/AST/TypeLocNodes.def"
  4670. }
  4671. }
  4672. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4673. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4674. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4675. if (!TL.getParam(I))
  4676. continue;
  4677. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4678. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4679. }
  4680. }
  4681. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4682. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4683. }
  4684. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4685. // Visit the type parameters from a permissive context.
  4686. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4687. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4688. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4689. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4690. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4691. // TODO: other template argument types?
  4692. }
  4693. }
  4694. // Visit pointee types from a permissive context.
  4695. #define CheckPolymorphic(Type) \
  4696. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4697. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4698. }
  4699. CheckPolymorphic(PointerTypeLoc)
  4700. CheckPolymorphic(ReferenceTypeLoc)
  4701. CheckPolymorphic(MemberPointerTypeLoc)
  4702. CheckPolymorphic(BlockPointerTypeLoc)
  4703. CheckPolymorphic(AtomicTypeLoc)
  4704. /// Handle all the types we haven't given a more specific
  4705. /// implementation for above.
  4706. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4707. // Every other kind of type that we haven't called out already
  4708. // that has an inner type is either (1) sugar or (2) contains that
  4709. // inner type in some way as a subobject.
  4710. if (TypeLoc Next = TL.getNextTypeLoc())
  4711. return Visit(Next, Sel);
  4712. // If there's no inner type and we're in a permissive context,
  4713. // don't diagnose.
  4714. if (Sel == Sema::AbstractNone) return;
  4715. // Check whether the type matches the abstract type.
  4716. QualType T = TL.getType();
  4717. if (T->isArrayType()) {
  4718. Sel = Sema::AbstractArrayType;
  4719. T = Info.S.Context.getBaseElementType(T);
  4720. }
  4721. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4722. if (CT != Info.AbstractType) return;
  4723. // It matched; do some magic.
  4724. if (Sel == Sema::AbstractArrayType) {
  4725. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4726. << T << TL.getSourceRange();
  4727. } else {
  4728. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4729. << Sel << T << TL.getSourceRange();
  4730. }
  4731. Info.DiagnoseAbstractType();
  4732. }
  4733. };
  4734. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4735. Sema::AbstractDiagSelID Sel) {
  4736. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4737. }
  4738. }
  4739. /// Check for invalid uses of an abstract type in a method declaration.
  4740. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4741. CXXMethodDecl *MD) {
  4742. // No need to do the check on definitions, which require that
  4743. // the return/param types be complete.
  4744. if (MD->doesThisDeclarationHaveABody())
  4745. return;
  4746. // For safety's sake, just ignore it if we don't have type source
  4747. // information. This should never happen for non-implicit methods,
  4748. // but...
  4749. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4750. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4751. }
  4752. /// Check for invalid uses of an abstract type within a class definition.
  4753. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4754. CXXRecordDecl *RD) {
  4755. for (auto *D : RD->decls()) {
  4756. if (D->isImplicit()) continue;
  4757. // Methods and method templates.
  4758. if (isa<CXXMethodDecl>(D)) {
  4759. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4760. } else if (isa<FunctionTemplateDecl>(D)) {
  4761. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4762. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4763. // Fields and static variables.
  4764. } else if (isa<FieldDecl>(D)) {
  4765. FieldDecl *FD = cast<FieldDecl>(D);
  4766. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4767. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4768. } else if (isa<VarDecl>(D)) {
  4769. VarDecl *VD = cast<VarDecl>(D);
  4770. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4771. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4772. // Nested classes and class templates.
  4773. } else if (isa<CXXRecordDecl>(D)) {
  4774. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4775. } else if (isa<ClassTemplateDecl>(D)) {
  4776. CheckAbstractClassUsage(Info,
  4777. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4778. }
  4779. }
  4780. }
  4781. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  4782. Attr *ClassAttr = getDLLAttr(Class);
  4783. if (!ClassAttr)
  4784. return;
  4785. assert(ClassAttr->getKind() == attr::DLLExport);
  4786. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4787. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4788. // Don't go any further if this is just an explicit instantiation
  4789. // declaration.
  4790. return;
  4791. for (Decl *Member : Class->decls()) {
  4792. // Defined static variables that are members of an exported base
  4793. // class must be marked export too.
  4794. auto *VD = dyn_cast<VarDecl>(Member);
  4795. if (VD && Member->getAttr<DLLExportAttr>() &&
  4796. VD->getStorageClass() == SC_Static &&
  4797. TSK == TSK_ImplicitInstantiation)
  4798. S.MarkVariableReferenced(VD->getLocation(), VD);
  4799. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  4800. if (!MD)
  4801. continue;
  4802. if (Member->getAttr<DLLExportAttr>()) {
  4803. if (MD->isUserProvided()) {
  4804. // Instantiate non-default class member functions ...
  4805. // .. except for certain kinds of template specializations.
  4806. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4807. continue;
  4808. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4809. // The function will be passed to the consumer when its definition is
  4810. // encountered.
  4811. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4812. MD->isCopyAssignmentOperator() ||
  4813. MD->isMoveAssignmentOperator()) {
  4814. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4815. // defaulted methods, and the copy and move assignment operators. The
  4816. // latter are exported even if they are trivial, because the address of
  4817. // an operator can be taken and should compare equal across libraries.
  4818. DiagnosticErrorTrap Trap(S.Diags);
  4819. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4820. if (Trap.hasErrorOccurred()) {
  4821. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4822. << Class << !S.getLangOpts().CPlusPlus11;
  4823. break;
  4824. }
  4825. // There is no later point when we will see the definition of this
  4826. // function, so pass it to the consumer now.
  4827. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4828. }
  4829. }
  4830. }
  4831. }
  4832. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  4833. CXXRecordDecl *Class) {
  4834. // Only the MS ABI has default constructor closures, so we don't need to do
  4835. // this semantic checking anywhere else.
  4836. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  4837. return;
  4838. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  4839. for (Decl *Member : Class->decls()) {
  4840. // Look for exported default constructors.
  4841. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  4842. if (!CD || !CD->isDefaultConstructor())
  4843. continue;
  4844. auto *Attr = CD->getAttr<DLLExportAttr>();
  4845. if (!Attr)
  4846. continue;
  4847. // If the class is non-dependent, mark the default arguments as ODR-used so
  4848. // that we can properly codegen the constructor closure.
  4849. if (!Class->isDependentContext()) {
  4850. for (ParmVarDecl *PD : CD->parameters()) {
  4851. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  4852. S.DiscardCleanupsInEvaluationContext();
  4853. }
  4854. }
  4855. if (LastExportedDefaultCtor) {
  4856. S.Diag(LastExportedDefaultCtor->getLocation(),
  4857. diag::err_attribute_dll_ambiguous_default_ctor)
  4858. << Class;
  4859. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  4860. << CD->getDeclName();
  4861. return;
  4862. }
  4863. LastExportedDefaultCtor = CD;
  4864. }
  4865. }
  4866. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  4867. // Mark any compiler-generated routines with the implicit code_seg attribute.
  4868. for (auto *Method : Class->methods()) {
  4869. if (Method->isUserProvided())
  4870. continue;
  4871. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  4872. Method->addAttr(A);
  4873. }
  4874. }
  4875. /// Check class-level dllimport/dllexport attribute.
  4876. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4877. Attr *ClassAttr = getDLLAttr(Class);
  4878. // MSVC inherits DLL attributes to partial class template specializations.
  4879. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4880. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4881. if (Attr *TemplateAttr =
  4882. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4883. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4884. A->setInherited(true);
  4885. ClassAttr = A;
  4886. }
  4887. }
  4888. }
  4889. if (!ClassAttr)
  4890. return;
  4891. if (!Class->isExternallyVisible()) {
  4892. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4893. << Class << ClassAttr;
  4894. return;
  4895. }
  4896. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4897. !ClassAttr->isInherited()) {
  4898. // Diagnose dll attributes on members of class with dll attribute.
  4899. for (Decl *Member : Class->decls()) {
  4900. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4901. continue;
  4902. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4903. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4904. continue;
  4905. Diag(MemberAttr->getLocation(),
  4906. diag::err_attribute_dll_member_of_dll_class)
  4907. << MemberAttr << ClassAttr;
  4908. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4909. Member->setInvalidDecl();
  4910. }
  4911. }
  4912. if (Class->getDescribedClassTemplate())
  4913. // Don't inherit dll attribute until the template is instantiated.
  4914. return;
  4915. // The class is either imported or exported.
  4916. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4917. // Check if this was a dllimport attribute propagated from a derived class to
  4918. // a base class template specialization. We don't apply these attributes to
  4919. // static data members.
  4920. const bool PropagatedImport =
  4921. !ClassExported &&
  4922. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  4923. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4924. // Ignore explicit dllexport on explicit class template instantiation declarations.
  4925. if (ClassExported && !ClassAttr->isInherited() &&
  4926. TSK == TSK_ExplicitInstantiationDeclaration) {
  4927. Class->dropAttr<DLLExportAttr>();
  4928. return;
  4929. }
  4930. // Force declaration of implicit members so they can inherit the attribute.
  4931. ForceDeclarationOfImplicitMembers(Class);
  4932. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4933. // seem to be true in practice?
  4934. for (Decl *Member : Class->decls()) {
  4935. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4936. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  4937. // Only methods and static fields inherit the attributes.
  4938. if (!VD && !MD)
  4939. continue;
  4940. if (MD) {
  4941. // Don't process deleted methods.
  4942. if (MD->isDeleted())
  4943. continue;
  4944. if (MD->isInlined()) {
  4945. // MinGW does not import or export inline methods.
  4946. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4947. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
  4948. continue;
  4949. // MSVC versions before 2015 don't export the move assignment operators
  4950. // and move constructor, so don't attempt to import/export them if
  4951. // we have a definition.
  4952. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  4953. if ((MD->isMoveAssignmentOperator() ||
  4954. (Ctor && Ctor->isMoveConstructor())) &&
  4955. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  4956. continue;
  4957. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  4958. // operator is exported anyway.
  4959. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  4960. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  4961. continue;
  4962. }
  4963. }
  4964. // Don't apply dllimport attributes to static data members of class template
  4965. // instantiations when the attribute is propagated from a derived class.
  4966. if (VD && PropagatedImport)
  4967. continue;
  4968. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  4969. continue;
  4970. if (!getDLLAttr(Member)) {
  4971. auto *NewAttr =
  4972. cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4973. NewAttr->setInherited(true);
  4974. Member->addAttr(NewAttr);
  4975. if (MD) {
  4976. // Propagate DLLAttr to friend re-declarations of MD that have already
  4977. // been constructed.
  4978. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  4979. FD = FD->getPreviousDecl()) {
  4980. if (FD->getFriendObjectKind() == Decl::FOK_None)
  4981. continue;
  4982. assert(!getDLLAttr(FD) &&
  4983. "friend re-decl should not already have a DLLAttr");
  4984. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4985. NewAttr->setInherited(true);
  4986. FD->addAttr(NewAttr);
  4987. }
  4988. }
  4989. }
  4990. }
  4991. if (ClassExported)
  4992. DelayedDllExportClasses.push_back(Class);
  4993. }
  4994. /// Perform propagation of DLL attributes from a derived class to a
  4995. /// templated base class for MS compatibility.
  4996. void Sema::propagateDLLAttrToBaseClassTemplate(
  4997. CXXRecordDecl *Class, Attr *ClassAttr,
  4998. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  4999. if (getDLLAttr(
  5000. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5001. // If the base class template has a DLL attribute, don't try to change it.
  5002. return;
  5003. }
  5004. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5005. if (!getDLLAttr(BaseTemplateSpec) &&
  5006. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5007. TSK == TSK_ImplicitInstantiation)) {
  5008. // The template hasn't been instantiated yet (or it has, but only as an
  5009. // explicit instantiation declaration or implicit instantiation, which means
  5010. // we haven't codegenned any members yet), so propagate the attribute.
  5011. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5012. NewAttr->setInherited(true);
  5013. BaseTemplateSpec->addAttr(NewAttr);
  5014. // If this was an import, mark that we propagated it from a derived class to
  5015. // a base class template specialization.
  5016. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5017. ImportAttr->setPropagatedToBaseTemplate();
  5018. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5019. // needs to be run again to work see the new attribute. Otherwise this will
  5020. // get run whenever the template is instantiated.
  5021. if (TSK != TSK_Undeclared)
  5022. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5023. return;
  5024. }
  5025. if (getDLLAttr(BaseTemplateSpec)) {
  5026. // The template has already been specialized or instantiated with an
  5027. // attribute, explicitly or through propagation. We should not try to change
  5028. // it.
  5029. return;
  5030. }
  5031. // The template was previously instantiated or explicitly specialized without
  5032. // a dll attribute, It's too late for us to add an attribute, so warn that
  5033. // this is unsupported.
  5034. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5035. << BaseTemplateSpec->isExplicitSpecialization();
  5036. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5037. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5038. Diag(BaseTemplateSpec->getLocation(),
  5039. diag::note_template_class_explicit_specialization_was_here)
  5040. << BaseTemplateSpec;
  5041. } else {
  5042. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5043. diag::note_template_class_instantiation_was_here)
  5044. << BaseTemplateSpec;
  5045. }
  5046. }
  5047. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5048. SourceLocation DefaultLoc) {
  5049. switch (S.getSpecialMember(MD)) {
  5050. case Sema::CXXDefaultConstructor:
  5051. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5052. cast<CXXConstructorDecl>(MD));
  5053. break;
  5054. case Sema::CXXCopyConstructor:
  5055. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5056. break;
  5057. case Sema::CXXCopyAssignment:
  5058. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5059. break;
  5060. case Sema::CXXDestructor:
  5061. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5062. break;
  5063. case Sema::CXXMoveConstructor:
  5064. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5065. break;
  5066. case Sema::CXXMoveAssignment:
  5067. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5068. break;
  5069. case Sema::CXXInvalid:
  5070. llvm_unreachable("Invalid special member.");
  5071. }
  5072. }
  5073. /// Determine whether a type is permitted to be passed or returned in
  5074. /// registers, per C++ [class.temporary]p3.
  5075. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5076. TargetInfo::CallingConvKind CCK) {
  5077. if (D->isDependentType() || D->isInvalidDecl())
  5078. return false;
  5079. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5080. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5081. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5082. return !D->hasNonTrivialDestructorForCall() &&
  5083. !D->hasNonTrivialCopyConstructorForCall();
  5084. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5085. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5086. bool DtorIsTrivialForCall = false;
  5087. // If a class has at least one non-deleted, trivial copy constructor, it
  5088. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5089. //
  5090. // Note: This permits classes with non-trivial copy or move ctors to be
  5091. // passed in registers, so long as they *also* have a trivial copy ctor,
  5092. // which is non-conforming.
  5093. if (D->needsImplicitCopyConstructor()) {
  5094. if (!D->defaultedCopyConstructorIsDeleted()) {
  5095. if (D->hasTrivialCopyConstructor())
  5096. CopyCtorIsTrivial = true;
  5097. if (D->hasTrivialCopyConstructorForCall())
  5098. CopyCtorIsTrivialForCall = true;
  5099. }
  5100. } else {
  5101. for (const CXXConstructorDecl *CD : D->ctors()) {
  5102. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5103. if (CD->isTrivial())
  5104. CopyCtorIsTrivial = true;
  5105. if (CD->isTrivialForCall())
  5106. CopyCtorIsTrivialForCall = true;
  5107. }
  5108. }
  5109. }
  5110. if (D->needsImplicitDestructor()) {
  5111. if (!D->defaultedDestructorIsDeleted() &&
  5112. D->hasTrivialDestructorForCall())
  5113. DtorIsTrivialForCall = true;
  5114. } else if (const auto *DD = D->getDestructor()) {
  5115. if (!DD->isDeleted() && DD->isTrivialForCall())
  5116. DtorIsTrivialForCall = true;
  5117. }
  5118. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5119. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5120. return true;
  5121. // If a class has a destructor, we'd really like to pass it indirectly
  5122. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5123. // impossible for small types, which it will pass in a single register or
  5124. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5125. // We can't call out all large objects as being indirect because there are
  5126. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5127. // how we pass large POD types.
  5128. // Note: This permits small classes with nontrivial destructors to be
  5129. // passed in registers, which is non-conforming.
  5130. if (CopyCtorIsTrivial &&
  5131. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
  5132. return true;
  5133. return false;
  5134. }
  5135. // Per C++ [class.temporary]p3, the relevant condition is:
  5136. // each copy constructor, move constructor, and destructor of X is
  5137. // either trivial or deleted, and X has at least one non-deleted copy
  5138. // or move constructor
  5139. bool HasNonDeletedCopyOrMove = false;
  5140. if (D->needsImplicitCopyConstructor() &&
  5141. !D->defaultedCopyConstructorIsDeleted()) {
  5142. if (!D->hasTrivialCopyConstructorForCall())
  5143. return false;
  5144. HasNonDeletedCopyOrMove = true;
  5145. }
  5146. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5147. !D->defaultedMoveConstructorIsDeleted()) {
  5148. if (!D->hasTrivialMoveConstructorForCall())
  5149. return false;
  5150. HasNonDeletedCopyOrMove = true;
  5151. }
  5152. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5153. !D->hasTrivialDestructorForCall())
  5154. return false;
  5155. for (const CXXMethodDecl *MD : D->methods()) {
  5156. if (MD->isDeleted())
  5157. continue;
  5158. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5159. if (CD && CD->isCopyOrMoveConstructor())
  5160. HasNonDeletedCopyOrMove = true;
  5161. else if (!isa<CXXDestructorDecl>(MD))
  5162. continue;
  5163. if (!MD->isTrivialForCall())
  5164. return false;
  5165. }
  5166. return HasNonDeletedCopyOrMove;
  5167. }
  5168. /// Perform semantic checks on a class definition that has been
  5169. /// completing, introducing implicitly-declared members, checking for
  5170. /// abstract types, etc.
  5171. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5172. if (!Record)
  5173. return;
  5174. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5175. AbstractUsageInfo Info(*this, Record);
  5176. CheckAbstractClassUsage(Info, Record);
  5177. }
  5178. // If this is not an aggregate type and has no user-declared constructor,
  5179. // complain about any non-static data members of reference or const scalar
  5180. // type, since they will never get initializers.
  5181. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5182. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5183. !Record->isLambda()) {
  5184. bool Complained = false;
  5185. for (const auto *F : Record->fields()) {
  5186. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5187. continue;
  5188. if (F->getType()->isReferenceType() ||
  5189. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5190. if (!Complained) {
  5191. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5192. << Record->getTagKind() << Record;
  5193. Complained = true;
  5194. }
  5195. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5196. << F->getType()->isReferenceType()
  5197. << F->getDeclName();
  5198. }
  5199. }
  5200. }
  5201. if (Record->getIdentifier()) {
  5202. // C++ [class.mem]p13:
  5203. // If T is the name of a class, then each of the following shall have a
  5204. // name different from T:
  5205. // - every member of every anonymous union that is a member of class T.
  5206. //
  5207. // C++ [class.mem]p14:
  5208. // In addition, if class T has a user-declared constructor (12.1), every
  5209. // non-static data member of class T shall have a name different from T.
  5210. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5211. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5212. ++I) {
  5213. NamedDecl *D = (*I)->getUnderlyingDecl();
  5214. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5215. Record->hasUserDeclaredConstructor()) ||
  5216. isa<IndirectFieldDecl>(D)) {
  5217. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5218. << D->getDeclName();
  5219. break;
  5220. }
  5221. }
  5222. }
  5223. // Warn if the class has virtual methods but non-virtual public destructor.
  5224. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5225. CXXDestructorDecl *dtor = Record->getDestructor();
  5226. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5227. !Record->hasAttr<FinalAttr>())
  5228. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5229. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5230. }
  5231. if (Record->isAbstract()) {
  5232. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5233. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5234. << FA->isSpelledAsSealed();
  5235. DiagnoseAbstractType(Record);
  5236. }
  5237. }
  5238. // See if trivial_abi has to be dropped.
  5239. if (Record->hasAttr<TrivialABIAttr>())
  5240. checkIllFormedTrivialABIStruct(*Record);
  5241. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5242. // "trivial_abi".
  5243. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5244. if (HasTrivialABI)
  5245. Record->setHasTrivialSpecialMemberForCall();
  5246. bool HasMethodWithOverrideControl = false,
  5247. HasOverridingMethodWithoutOverrideControl = false;
  5248. if (!Record->isDependentType()) {
  5249. for (auto *M : Record->methods()) {
  5250. // See if a method overloads virtual methods in a base
  5251. // class without overriding any.
  5252. if (!M->isStatic())
  5253. DiagnoseHiddenVirtualMethods(M);
  5254. if (M->hasAttr<OverrideAttr>())
  5255. HasMethodWithOverrideControl = true;
  5256. else if (M->size_overridden_methods() > 0)
  5257. HasOverridingMethodWithoutOverrideControl = true;
  5258. // Check whether the explicitly-defaulted special members are valid.
  5259. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5260. CheckExplicitlyDefaultedSpecialMember(M);
  5261. // For an explicitly defaulted or deleted special member, we defer
  5262. // determining triviality until the class is complete. That time is now!
  5263. CXXSpecialMember CSM = getSpecialMember(M);
  5264. if (!M->isImplicit() && !M->isUserProvided()) {
  5265. if (CSM != CXXInvalid) {
  5266. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5267. // Inform the class that we've finished declaring this member.
  5268. Record->finishedDefaultedOrDeletedMember(M);
  5269. M->setTrivialForCall(
  5270. HasTrivialABI ||
  5271. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5272. Record->setTrivialForCallFlags(M);
  5273. }
  5274. }
  5275. // Set triviality for the purpose of calls if this is a user-provided
  5276. // copy/move constructor or destructor.
  5277. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5278. CSM == CXXDestructor) && M->isUserProvided()) {
  5279. M->setTrivialForCall(HasTrivialABI);
  5280. Record->setTrivialForCallFlags(M);
  5281. }
  5282. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5283. M->hasAttr<DLLExportAttr>()) {
  5284. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5285. M->isTrivial() &&
  5286. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5287. CSM == CXXDestructor))
  5288. M->dropAttr<DLLExportAttr>();
  5289. if (M->hasAttr<DLLExportAttr>()) {
  5290. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5291. ActOnFinishInlineFunctionDef(M);
  5292. }
  5293. }
  5294. }
  5295. }
  5296. if (HasMethodWithOverrideControl &&
  5297. HasOverridingMethodWithoutOverrideControl) {
  5298. // At least one method has the 'override' control declared.
  5299. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5300. for (auto *M : Record->methods())
  5301. DiagnoseAbsenceOfOverrideControl(M);
  5302. }
  5303. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5304. // whether this class uses any C++ features that are implemented
  5305. // completely differently in MSVC, and if so, emit a diagnostic.
  5306. // That diagnostic defaults to an error, but we allow projects to
  5307. // map it down to a warning (or ignore it). It's a fairly common
  5308. // practice among users of the ms_struct pragma to mass-annotate
  5309. // headers, sweeping up a bunch of types that the project doesn't
  5310. // really rely on MSVC-compatible layout for. We must therefore
  5311. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5312. if (Record->isMsStruct(Context) &&
  5313. (Record->isPolymorphic() || Record->getNumBases())) {
  5314. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5315. }
  5316. checkClassLevelDLLAttribute(Record);
  5317. checkClassLevelCodeSegAttribute(Record);
  5318. bool ClangABICompat4 =
  5319. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5320. TargetInfo::CallingConvKind CCK =
  5321. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5322. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5323. // Do not change ArgPassingRestrictions if it has already been set to
  5324. // APK_CanNeverPassInRegs.
  5325. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5326. Record->setArgPassingRestrictions(CanPass
  5327. ? RecordDecl::APK_CanPassInRegs
  5328. : RecordDecl::APK_CannotPassInRegs);
  5329. // If canPassInRegisters returns true despite the record having a non-trivial
  5330. // destructor, the record is destructed in the callee. This happens only when
  5331. // the record or one of its subobjects has a field annotated with trivial_abi
  5332. // or a field qualified with ObjC __strong/__weak.
  5333. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5334. Record->setParamDestroyedInCallee(true);
  5335. else if (Record->hasNonTrivialDestructor())
  5336. Record->setParamDestroyedInCallee(CanPass);
  5337. if (getLangOpts().ForceEmitVTables) {
  5338. // If we want to emit all the vtables, we need to mark it as used. This
  5339. // is especially required for cases like vtable assumption loads.
  5340. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5341. }
  5342. }
  5343. /// Look up the special member function that would be called by a special
  5344. /// member function for a subobject of class type.
  5345. ///
  5346. /// \param Class The class type of the subobject.
  5347. /// \param CSM The kind of special member function.
  5348. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5349. /// \param ConstRHS True if this is a copy operation with a const object
  5350. /// on its RHS, that is, if the argument to the outer special member
  5351. /// function is 'const' and this is not a field marked 'mutable'.
  5352. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5353. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5354. unsigned FieldQuals, bool ConstRHS) {
  5355. unsigned LHSQuals = 0;
  5356. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5357. LHSQuals = FieldQuals;
  5358. unsigned RHSQuals = FieldQuals;
  5359. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5360. RHSQuals = 0;
  5361. else if (ConstRHS)
  5362. RHSQuals |= Qualifiers::Const;
  5363. return S.LookupSpecialMember(Class, CSM,
  5364. RHSQuals & Qualifiers::Const,
  5365. RHSQuals & Qualifiers::Volatile,
  5366. false,
  5367. LHSQuals & Qualifiers::Const,
  5368. LHSQuals & Qualifiers::Volatile);
  5369. }
  5370. class Sema::InheritedConstructorInfo {
  5371. Sema &S;
  5372. SourceLocation UseLoc;
  5373. /// A mapping from the base classes through which the constructor was
  5374. /// inherited to the using shadow declaration in that base class (or a null
  5375. /// pointer if the constructor was declared in that base class).
  5376. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5377. InheritedFromBases;
  5378. public:
  5379. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5380. ConstructorUsingShadowDecl *Shadow)
  5381. : S(S), UseLoc(UseLoc) {
  5382. bool DiagnosedMultipleConstructedBases = false;
  5383. CXXRecordDecl *ConstructedBase = nullptr;
  5384. UsingDecl *ConstructedBaseUsing = nullptr;
  5385. // Find the set of such base class subobjects and check that there's a
  5386. // unique constructed subobject.
  5387. for (auto *D : Shadow->redecls()) {
  5388. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5389. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5390. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5391. InheritedFromBases.insert(
  5392. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5393. DShadow->getNominatedBaseClassShadowDecl()));
  5394. if (DShadow->constructsVirtualBase())
  5395. InheritedFromBases.insert(
  5396. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5397. DShadow->getConstructedBaseClassShadowDecl()));
  5398. else
  5399. assert(DNominatedBase == DConstructedBase);
  5400. // [class.inhctor.init]p2:
  5401. // If the constructor was inherited from multiple base class subobjects
  5402. // of type B, the program is ill-formed.
  5403. if (!ConstructedBase) {
  5404. ConstructedBase = DConstructedBase;
  5405. ConstructedBaseUsing = D->getUsingDecl();
  5406. } else if (ConstructedBase != DConstructedBase &&
  5407. !Shadow->isInvalidDecl()) {
  5408. if (!DiagnosedMultipleConstructedBases) {
  5409. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5410. << Shadow->getTargetDecl();
  5411. S.Diag(ConstructedBaseUsing->getLocation(),
  5412. diag::note_ambiguous_inherited_constructor_using)
  5413. << ConstructedBase;
  5414. DiagnosedMultipleConstructedBases = true;
  5415. }
  5416. S.Diag(D->getUsingDecl()->getLocation(),
  5417. diag::note_ambiguous_inherited_constructor_using)
  5418. << DConstructedBase;
  5419. }
  5420. }
  5421. if (DiagnosedMultipleConstructedBases)
  5422. Shadow->setInvalidDecl();
  5423. }
  5424. /// Find the constructor to use for inherited construction of a base class,
  5425. /// and whether that base class constructor inherits the constructor from a
  5426. /// virtual base class (in which case it won't actually invoke it).
  5427. std::pair<CXXConstructorDecl *, bool>
  5428. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5429. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5430. if (It == InheritedFromBases.end())
  5431. return std::make_pair(nullptr, false);
  5432. // This is an intermediary class.
  5433. if (It->second)
  5434. return std::make_pair(
  5435. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5436. It->second->constructsVirtualBase());
  5437. // This is the base class from which the constructor was inherited.
  5438. return std::make_pair(Ctor, false);
  5439. }
  5440. };
  5441. /// Is the special member function which would be selected to perform the
  5442. /// specified operation on the specified class type a constexpr constructor?
  5443. static bool
  5444. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5445. Sema::CXXSpecialMember CSM, unsigned Quals,
  5446. bool ConstRHS,
  5447. CXXConstructorDecl *InheritedCtor = nullptr,
  5448. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5449. // If we're inheriting a constructor, see if we need to call it for this base
  5450. // class.
  5451. if (InheritedCtor) {
  5452. assert(CSM == Sema::CXXDefaultConstructor);
  5453. auto BaseCtor =
  5454. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5455. if (BaseCtor)
  5456. return BaseCtor->isConstexpr();
  5457. }
  5458. if (CSM == Sema::CXXDefaultConstructor)
  5459. return ClassDecl->hasConstexprDefaultConstructor();
  5460. Sema::SpecialMemberOverloadResult SMOR =
  5461. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5462. if (!SMOR.getMethod())
  5463. // A constructor we wouldn't select can't be "involved in initializing"
  5464. // anything.
  5465. return true;
  5466. return SMOR.getMethod()->isConstexpr();
  5467. }
  5468. /// Determine whether the specified special member function would be constexpr
  5469. /// if it were implicitly defined.
  5470. static bool defaultedSpecialMemberIsConstexpr(
  5471. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5472. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5473. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5474. if (!S.getLangOpts().CPlusPlus11)
  5475. return false;
  5476. // C++11 [dcl.constexpr]p4:
  5477. // In the definition of a constexpr constructor [...]
  5478. bool Ctor = true;
  5479. switch (CSM) {
  5480. case Sema::CXXDefaultConstructor:
  5481. if (Inherited)
  5482. break;
  5483. // Since default constructor lookup is essentially trivial (and cannot
  5484. // involve, for instance, template instantiation), we compute whether a
  5485. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5486. //
  5487. // This is important for performance; we need to know whether the default
  5488. // constructor is constexpr to determine whether the type is a literal type.
  5489. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5490. case Sema::CXXCopyConstructor:
  5491. case Sema::CXXMoveConstructor:
  5492. // For copy or move constructors, we need to perform overload resolution.
  5493. break;
  5494. case Sema::CXXCopyAssignment:
  5495. case Sema::CXXMoveAssignment:
  5496. if (!S.getLangOpts().CPlusPlus14)
  5497. return false;
  5498. // In C++1y, we need to perform overload resolution.
  5499. Ctor = false;
  5500. break;
  5501. case Sema::CXXDestructor:
  5502. case Sema::CXXInvalid:
  5503. return false;
  5504. }
  5505. // -- if the class is a non-empty union, or for each non-empty anonymous
  5506. // union member of a non-union class, exactly one non-static data member
  5507. // shall be initialized; [DR1359]
  5508. //
  5509. // If we squint, this is guaranteed, since exactly one non-static data member
  5510. // will be initialized (if the constructor isn't deleted), we just don't know
  5511. // which one.
  5512. if (Ctor && ClassDecl->isUnion())
  5513. return CSM == Sema::CXXDefaultConstructor
  5514. ? ClassDecl->hasInClassInitializer() ||
  5515. !ClassDecl->hasVariantMembers()
  5516. : true;
  5517. // -- the class shall not have any virtual base classes;
  5518. if (Ctor && ClassDecl->getNumVBases())
  5519. return false;
  5520. // C++1y [class.copy]p26:
  5521. // -- [the class] is a literal type, and
  5522. if (!Ctor && !ClassDecl->isLiteral())
  5523. return false;
  5524. // -- every constructor involved in initializing [...] base class
  5525. // sub-objects shall be a constexpr constructor;
  5526. // -- the assignment operator selected to copy/move each direct base
  5527. // class is a constexpr function, and
  5528. for (const auto &B : ClassDecl->bases()) {
  5529. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5530. if (!BaseType) continue;
  5531. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5532. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5533. InheritedCtor, Inherited))
  5534. return false;
  5535. }
  5536. // -- every constructor involved in initializing non-static data members
  5537. // [...] shall be a constexpr constructor;
  5538. // -- every non-static data member and base class sub-object shall be
  5539. // initialized
  5540. // -- for each non-static data member of X that is of class type (or array
  5541. // thereof), the assignment operator selected to copy/move that member is
  5542. // a constexpr function
  5543. for (const auto *F : ClassDecl->fields()) {
  5544. if (F->isInvalidDecl())
  5545. continue;
  5546. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5547. continue;
  5548. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5549. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5550. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5551. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5552. BaseType.getCVRQualifiers(),
  5553. ConstArg && !F->isMutable()))
  5554. return false;
  5555. } else if (CSM == Sema::CXXDefaultConstructor) {
  5556. return false;
  5557. }
  5558. }
  5559. // All OK, it's constexpr!
  5560. return true;
  5561. }
  5562. static Sema::ImplicitExceptionSpecification
  5563. ComputeDefaultedSpecialMemberExceptionSpec(
  5564. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5565. Sema::InheritedConstructorInfo *ICI);
  5566. static Sema::ImplicitExceptionSpecification
  5567. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5568. auto CSM = S.getSpecialMember(MD);
  5569. if (CSM != Sema::CXXInvalid)
  5570. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5571. auto *CD = cast<CXXConstructorDecl>(MD);
  5572. assert(CD->getInheritedConstructor() &&
  5573. "only special members have implicit exception specs");
  5574. Sema::InheritedConstructorInfo ICI(
  5575. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5576. return ComputeDefaultedSpecialMemberExceptionSpec(
  5577. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5578. }
  5579. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5580. CXXMethodDecl *MD) {
  5581. FunctionProtoType::ExtProtoInfo EPI;
  5582. // Build an exception specification pointing back at this member.
  5583. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5584. EPI.ExceptionSpec.SourceDecl = MD;
  5585. // Set the calling convention to the default for C++ instance methods.
  5586. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5587. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5588. /*IsCXXMethod=*/true));
  5589. return EPI;
  5590. }
  5591. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5592. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5593. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5594. return;
  5595. // Evaluate the exception specification.
  5596. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5597. auto ESI = IES.getExceptionSpec();
  5598. // Update the type of the special member to use it.
  5599. UpdateExceptionSpec(MD, ESI);
  5600. // A user-provided destructor can be defined outside the class. When that
  5601. // happens, be sure to update the exception specification on both
  5602. // declarations.
  5603. const FunctionProtoType *CanonicalFPT =
  5604. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5605. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5606. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5607. }
  5608. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5609. CXXRecordDecl *RD = MD->getParent();
  5610. CXXSpecialMember CSM = getSpecialMember(MD);
  5611. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5612. "not an explicitly-defaulted special member");
  5613. // Whether this was the first-declared instance of the constructor.
  5614. // This affects whether we implicitly add an exception spec and constexpr.
  5615. bool First = MD == MD->getCanonicalDecl();
  5616. bool HadError = false;
  5617. // C++11 [dcl.fct.def.default]p1:
  5618. // A function that is explicitly defaulted shall
  5619. // -- be a special member function (checked elsewhere),
  5620. // -- have the same type (except for ref-qualifiers, and except that a
  5621. // copy operation can take a non-const reference) as an implicit
  5622. // declaration, and
  5623. // -- not have default arguments.
  5624. unsigned ExpectedParams = 1;
  5625. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5626. ExpectedParams = 0;
  5627. if (MD->getNumParams() != ExpectedParams) {
  5628. // This also checks for default arguments: a copy or move constructor with a
  5629. // default argument is classified as a default constructor, and assignment
  5630. // operations and destructors can't have default arguments.
  5631. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5632. << CSM << MD->getSourceRange();
  5633. HadError = true;
  5634. } else if (MD->isVariadic()) {
  5635. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5636. << CSM << MD->getSourceRange();
  5637. HadError = true;
  5638. }
  5639. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5640. bool CanHaveConstParam = false;
  5641. if (CSM == CXXCopyConstructor)
  5642. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5643. else if (CSM == CXXCopyAssignment)
  5644. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5645. QualType ReturnType = Context.VoidTy;
  5646. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5647. // Check for return type matching.
  5648. ReturnType = Type->getReturnType();
  5649. QualType ExpectedReturnType =
  5650. Context.getLValueReferenceType(Context.getTypeDeclType(RD));
  5651. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5652. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5653. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5654. HadError = true;
  5655. }
  5656. // A defaulted special member cannot have cv-qualifiers.
  5657. if (Type->getTypeQuals()) {
  5658. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5659. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5660. HadError = true;
  5661. }
  5662. }
  5663. // Check for parameter type matching.
  5664. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5665. bool HasConstParam = false;
  5666. if (ExpectedParams && ArgType->isReferenceType()) {
  5667. // Argument must be reference to possibly-const T.
  5668. QualType ReferentType = ArgType->getPointeeType();
  5669. HasConstParam = ReferentType.isConstQualified();
  5670. if (ReferentType.isVolatileQualified()) {
  5671. Diag(MD->getLocation(),
  5672. diag::err_defaulted_special_member_volatile_param) << CSM;
  5673. HadError = true;
  5674. }
  5675. if (HasConstParam && !CanHaveConstParam) {
  5676. if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5677. Diag(MD->getLocation(),
  5678. diag::err_defaulted_special_member_copy_const_param)
  5679. << (CSM == CXXCopyAssignment);
  5680. // FIXME: Explain why this special member can't be const.
  5681. } else {
  5682. Diag(MD->getLocation(),
  5683. diag::err_defaulted_special_member_move_const_param)
  5684. << (CSM == CXXMoveAssignment);
  5685. }
  5686. HadError = true;
  5687. }
  5688. } else if (ExpectedParams) {
  5689. // A copy assignment operator can take its argument by value, but a
  5690. // defaulted one cannot.
  5691. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5692. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5693. HadError = true;
  5694. }
  5695. // C++11 [dcl.fct.def.default]p2:
  5696. // An explicitly-defaulted function may be declared constexpr only if it
  5697. // would have been implicitly declared as constexpr,
  5698. // Do not apply this rule to members of class templates, since core issue 1358
  5699. // makes such functions always instantiate to constexpr functions. For
  5700. // functions which cannot be constexpr (for non-constructors in C++11 and for
  5701. // destructors in C++1y), this is checked elsewhere.
  5702. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  5703. HasConstParam);
  5704. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  5705. : isa<CXXConstructorDecl>(MD)) &&
  5706. MD->isConstexpr() && !Constexpr &&
  5707. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  5708. Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
  5709. // FIXME: Explain why the special member can't be constexpr.
  5710. HadError = true;
  5711. }
  5712. // and may have an explicit exception-specification only if it is compatible
  5713. // with the exception-specification on the implicit declaration.
  5714. if (Type->hasExceptionSpec()) {
  5715. // Delay the check if this is the first declaration of the special member,
  5716. // since we may not have parsed some necessary in-class initializers yet.
  5717. if (First) {
  5718. // If the exception specification needs to be instantiated, do so now,
  5719. // before we clobber it with an EST_Unevaluated specification below.
  5720. if (Type->getExceptionSpecType() == EST_Uninstantiated) {
  5721. InstantiateExceptionSpec(MD->getBeginLoc(), MD);
  5722. Type = MD->getType()->getAs<FunctionProtoType>();
  5723. }
  5724. DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
  5725. } else
  5726. CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
  5727. }
  5728. // If a function is explicitly defaulted on its first declaration,
  5729. if (First) {
  5730. // -- it is implicitly considered to be constexpr if the implicit
  5731. // definition would be,
  5732. MD->setConstexpr(Constexpr);
  5733. // -- it is implicitly considered to have the same exception-specification
  5734. // as if it had been implicitly declared,
  5735. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  5736. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5737. EPI.ExceptionSpec.SourceDecl = MD;
  5738. MD->setType(Context.getFunctionType(ReturnType,
  5739. llvm::makeArrayRef(&ArgType,
  5740. ExpectedParams),
  5741. EPI));
  5742. }
  5743. if (ShouldDeleteSpecialMember(MD, CSM)) {
  5744. if (First) {
  5745. SetDeclDeleted(MD, MD->getLocation());
  5746. } else {
  5747. // C++11 [dcl.fct.def.default]p4:
  5748. // [For a] user-provided explicitly-defaulted function [...] if such a
  5749. // function is implicitly defined as deleted, the program is ill-formed.
  5750. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  5751. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5752. HadError = true;
  5753. }
  5754. }
  5755. if (HadError)
  5756. MD->setInvalidDecl();
  5757. }
  5758. /// Check whether the exception specification provided for an
  5759. /// explicitly-defaulted special member matches the exception specification
  5760. /// that would have been generated for an implicit special member, per
  5761. /// C++11 [dcl.fct.def.default]p2.
  5762. void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
  5763. CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
  5764. // If the exception specification was explicitly specified but hadn't been
  5765. // parsed when the method was defaulted, grab it now.
  5766. if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
  5767. SpecifiedType =
  5768. MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  5769. // Compute the implicit exception specification.
  5770. CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5771. /*IsCXXMethod=*/true);
  5772. FunctionProtoType::ExtProtoInfo EPI(CC);
  5773. auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
  5774. EPI.ExceptionSpec = IES.getExceptionSpec();
  5775. const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
  5776. Context.getFunctionType(Context.VoidTy, None, EPI));
  5777. // Ensure that it matches.
  5778. CheckEquivalentExceptionSpec(
  5779. PDiag(diag::err_incorrect_defaulted_exception_spec)
  5780. << getSpecialMember(MD), PDiag(),
  5781. ImplicitType, SourceLocation(),
  5782. SpecifiedType, MD->getLocation());
  5783. }
  5784. void Sema::CheckDelayedMemberExceptionSpecs() {
  5785. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  5786. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  5787. decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
  5788. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  5789. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  5790. std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
  5791. // Perform any deferred checking of exception specifications for virtual
  5792. // destructors.
  5793. for (auto &Check : Overriding)
  5794. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  5795. // Perform any deferred checking of exception specifications for befriended
  5796. // special members.
  5797. for (auto &Check : Equivalent)
  5798. CheckEquivalentExceptionSpec(Check.second, Check.first);
  5799. // Check that any explicitly-defaulted methods have exception specifications
  5800. // compatible with their implicit exception specifications.
  5801. for (auto &Spec : Defaulted)
  5802. CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
  5803. }
  5804. namespace {
  5805. /// CRTP base class for visiting operations performed by a special member
  5806. /// function (or inherited constructor).
  5807. template<typename Derived>
  5808. struct SpecialMemberVisitor {
  5809. Sema &S;
  5810. CXXMethodDecl *MD;
  5811. Sema::CXXSpecialMember CSM;
  5812. Sema::InheritedConstructorInfo *ICI;
  5813. // Properties of the special member, computed for convenience.
  5814. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  5815. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5816. Sema::InheritedConstructorInfo *ICI)
  5817. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  5818. switch (CSM) {
  5819. case Sema::CXXDefaultConstructor:
  5820. case Sema::CXXCopyConstructor:
  5821. case Sema::CXXMoveConstructor:
  5822. IsConstructor = true;
  5823. break;
  5824. case Sema::CXXCopyAssignment:
  5825. case Sema::CXXMoveAssignment:
  5826. IsAssignment = true;
  5827. break;
  5828. case Sema::CXXDestructor:
  5829. break;
  5830. case Sema::CXXInvalid:
  5831. llvm_unreachable("invalid special member kind");
  5832. }
  5833. if (MD->getNumParams()) {
  5834. if (const ReferenceType *RT =
  5835. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  5836. ConstArg = RT->getPointeeType().isConstQualified();
  5837. }
  5838. }
  5839. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5840. /// Is this a "move" special member?
  5841. bool isMove() const {
  5842. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  5843. }
  5844. /// Look up the corresponding special member in the given class.
  5845. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  5846. unsigned Quals, bool IsMutable) {
  5847. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  5848. ConstArg && !IsMutable);
  5849. }
  5850. /// Look up the constructor for the specified base class to see if it's
  5851. /// overridden due to this being an inherited constructor.
  5852. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  5853. if (!ICI)
  5854. return {};
  5855. assert(CSM == Sema::CXXDefaultConstructor);
  5856. auto *BaseCtor =
  5857. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  5858. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  5859. return MD;
  5860. return {};
  5861. }
  5862. /// A base or member subobject.
  5863. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  5864. /// Get the location to use for a subobject in diagnostics.
  5865. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  5866. // FIXME: For an indirect virtual base, the direct base leading to
  5867. // the indirect virtual base would be a more useful choice.
  5868. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  5869. return B->getBaseTypeLoc();
  5870. else
  5871. return Subobj.get<FieldDecl*>()->getLocation();
  5872. }
  5873. enum BasesToVisit {
  5874. /// Visit all non-virtual (direct) bases.
  5875. VisitNonVirtualBases,
  5876. /// Visit all direct bases, virtual or not.
  5877. VisitDirectBases,
  5878. /// Visit all non-virtual bases, and all virtual bases if the class
  5879. /// is not abstract.
  5880. VisitPotentiallyConstructedBases,
  5881. /// Visit all direct or virtual bases.
  5882. VisitAllBases
  5883. };
  5884. // Visit the bases and members of the class.
  5885. bool visit(BasesToVisit Bases) {
  5886. CXXRecordDecl *RD = MD->getParent();
  5887. if (Bases == VisitPotentiallyConstructedBases)
  5888. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  5889. for (auto &B : RD->bases())
  5890. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  5891. getDerived().visitBase(&B))
  5892. return true;
  5893. if (Bases == VisitAllBases)
  5894. for (auto &B : RD->vbases())
  5895. if (getDerived().visitBase(&B))
  5896. return true;
  5897. for (auto *F : RD->fields())
  5898. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  5899. getDerived().visitField(F))
  5900. return true;
  5901. return false;
  5902. }
  5903. };
  5904. }
  5905. namespace {
  5906. struct SpecialMemberDeletionInfo
  5907. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  5908. bool Diagnose;
  5909. SourceLocation Loc;
  5910. bool AllFieldsAreConst;
  5911. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  5912. Sema::CXXSpecialMember CSM,
  5913. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  5914. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  5915. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  5916. bool inUnion() const { return MD->getParent()->isUnion(); }
  5917. Sema::CXXSpecialMember getEffectiveCSM() {
  5918. return ICI ? Sema::CXXInvalid : CSM;
  5919. }
  5920. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  5921. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  5922. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  5923. bool shouldDeleteForField(FieldDecl *FD);
  5924. bool shouldDeleteForAllConstMembers();
  5925. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  5926. unsigned Quals);
  5927. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  5928. Sema::SpecialMemberOverloadResult SMOR,
  5929. bool IsDtorCallInCtor);
  5930. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  5931. };
  5932. }
  5933. /// Is the given special member inaccessible when used on the given
  5934. /// sub-object.
  5935. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  5936. CXXMethodDecl *target) {
  5937. /// If we're operating on a base class, the object type is the
  5938. /// type of this special member.
  5939. QualType objectTy;
  5940. AccessSpecifier access = target->getAccess();
  5941. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  5942. objectTy = S.Context.getTypeDeclType(MD->getParent());
  5943. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  5944. // If we're operating on a field, the object type is the type of the field.
  5945. } else {
  5946. objectTy = S.Context.getTypeDeclType(target->getParent());
  5947. }
  5948. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  5949. }
  5950. /// Check whether we should delete a special member due to the implicit
  5951. /// definition containing a call to a special member of a subobject.
  5952. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  5953. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  5954. bool IsDtorCallInCtor) {
  5955. CXXMethodDecl *Decl = SMOR.getMethod();
  5956. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  5957. int DiagKind = -1;
  5958. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  5959. DiagKind = !Decl ? 0 : 1;
  5960. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  5961. DiagKind = 2;
  5962. else if (!isAccessible(Subobj, Decl))
  5963. DiagKind = 3;
  5964. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  5965. !Decl->isTrivial()) {
  5966. // A member of a union must have a trivial corresponding special member.
  5967. // As a weird special case, a destructor call from a union's constructor
  5968. // must be accessible and non-deleted, but need not be trivial. Such a
  5969. // destructor is never actually called, but is semantically checked as
  5970. // if it were.
  5971. DiagKind = 4;
  5972. }
  5973. if (DiagKind == -1)
  5974. return false;
  5975. if (Diagnose) {
  5976. if (Field) {
  5977. S.Diag(Field->getLocation(),
  5978. diag::note_deleted_special_member_class_subobject)
  5979. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  5980. << Field << DiagKind << IsDtorCallInCtor;
  5981. } else {
  5982. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  5983. S.Diag(Base->getBeginLoc(),
  5984. diag::note_deleted_special_member_class_subobject)
  5985. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  5986. << Base->getType() << DiagKind << IsDtorCallInCtor;
  5987. }
  5988. if (DiagKind == 1)
  5989. S.NoteDeletedFunction(Decl);
  5990. // FIXME: Explain inaccessibility if DiagKind == 3.
  5991. }
  5992. return true;
  5993. }
  5994. /// Check whether we should delete a special member function due to having a
  5995. /// direct or virtual base class or non-static data member of class type M.
  5996. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  5997. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  5998. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  5999. bool IsMutable = Field && Field->isMutable();
  6000. // C++11 [class.ctor]p5:
  6001. // -- any direct or virtual base class, or non-static data member with no
  6002. // brace-or-equal-initializer, has class type M (or array thereof) and
  6003. // either M has no default constructor or overload resolution as applied
  6004. // to M's default constructor results in an ambiguity or in a function
  6005. // that is deleted or inaccessible
  6006. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6007. // -- a direct or virtual base class B that cannot be copied/moved because
  6008. // overload resolution, as applied to B's corresponding special member,
  6009. // results in an ambiguity or a function that is deleted or inaccessible
  6010. // from the defaulted special member
  6011. // C++11 [class.dtor]p5:
  6012. // -- any direct or virtual base class [...] has a type with a destructor
  6013. // that is deleted or inaccessible
  6014. if (!(CSM == Sema::CXXDefaultConstructor &&
  6015. Field && Field->hasInClassInitializer()) &&
  6016. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6017. false))
  6018. return true;
  6019. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6020. // -- any direct or virtual base class or non-static data member has a
  6021. // type with a destructor that is deleted or inaccessible
  6022. if (IsConstructor) {
  6023. Sema::SpecialMemberOverloadResult SMOR =
  6024. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6025. false, false, false, false, false);
  6026. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6027. return true;
  6028. }
  6029. return false;
  6030. }
  6031. /// Check whether we should delete a special member function due to the class
  6032. /// having a particular direct or virtual base class.
  6033. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6034. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6035. // If program is correct, BaseClass cannot be null, but if it is, the error
  6036. // must be reported elsewhere.
  6037. if (!BaseClass)
  6038. return false;
  6039. // If we have an inheriting constructor, check whether we're calling an
  6040. // inherited constructor instead of a default constructor.
  6041. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6042. if (auto *BaseCtor = SMOR.getMethod()) {
  6043. // Note that we do not check access along this path; other than that,
  6044. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6045. // FIXME: Check that the base has a usable destructor! Sink this into
  6046. // shouldDeleteForClassSubobject.
  6047. if (BaseCtor->isDeleted() && Diagnose) {
  6048. S.Diag(Base->getBeginLoc(),
  6049. diag::note_deleted_special_member_class_subobject)
  6050. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6051. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
  6052. S.NoteDeletedFunction(BaseCtor);
  6053. }
  6054. return BaseCtor->isDeleted();
  6055. }
  6056. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6057. }
  6058. /// Check whether we should delete a special member function due to the class
  6059. /// having a particular non-static data member.
  6060. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6061. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6062. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6063. if (CSM == Sema::CXXDefaultConstructor) {
  6064. // For a default constructor, all references must be initialized in-class
  6065. // and, if a union, it must have a non-const member.
  6066. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6067. if (Diagnose)
  6068. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6069. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6070. return true;
  6071. }
  6072. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6073. // const-qualified type (or array thereof) with no
  6074. // brace-or-equal-initializer does not have a user-provided default
  6075. // constructor.
  6076. if (!inUnion() && FieldType.isConstQualified() &&
  6077. !FD->hasInClassInitializer() &&
  6078. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6079. if (Diagnose)
  6080. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6081. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6082. return true;
  6083. }
  6084. if (inUnion() && !FieldType.isConstQualified())
  6085. AllFieldsAreConst = false;
  6086. } else if (CSM == Sema::CXXCopyConstructor) {
  6087. // For a copy constructor, data members must not be of rvalue reference
  6088. // type.
  6089. if (FieldType->isRValueReferenceType()) {
  6090. if (Diagnose)
  6091. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6092. << MD->getParent() << FD << FieldType;
  6093. return true;
  6094. }
  6095. } else if (IsAssignment) {
  6096. // For an assignment operator, data members must not be of reference type.
  6097. if (FieldType->isReferenceType()) {
  6098. if (Diagnose)
  6099. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6100. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6101. return true;
  6102. }
  6103. if (!FieldRecord && FieldType.isConstQualified()) {
  6104. // C++11 [class.copy]p23:
  6105. // -- a non-static data member of const non-class type (or array thereof)
  6106. if (Diagnose)
  6107. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6108. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6109. return true;
  6110. }
  6111. }
  6112. if (FieldRecord) {
  6113. // Some additional restrictions exist on the variant members.
  6114. if (!inUnion() && FieldRecord->isUnion() &&
  6115. FieldRecord->isAnonymousStructOrUnion()) {
  6116. bool AllVariantFieldsAreConst = true;
  6117. // FIXME: Handle anonymous unions declared within anonymous unions.
  6118. for (auto *UI : FieldRecord->fields()) {
  6119. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6120. if (!UnionFieldType.isConstQualified())
  6121. AllVariantFieldsAreConst = false;
  6122. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6123. if (UnionFieldRecord &&
  6124. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6125. UnionFieldType.getCVRQualifiers()))
  6126. return true;
  6127. }
  6128. // At least one member in each anonymous union must be non-const
  6129. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6130. !FieldRecord->field_empty()) {
  6131. if (Diagnose)
  6132. S.Diag(FieldRecord->getLocation(),
  6133. diag::note_deleted_default_ctor_all_const)
  6134. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6135. return true;
  6136. }
  6137. // Don't check the implicit member of the anonymous union type.
  6138. // This is technically non-conformant, but sanity demands it.
  6139. return false;
  6140. }
  6141. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6142. FieldType.getCVRQualifiers()))
  6143. return true;
  6144. }
  6145. return false;
  6146. }
  6147. /// C++11 [class.ctor] p5:
  6148. /// A defaulted default constructor for a class X is defined as deleted if
  6149. /// X is a union and all of its variant members are of const-qualified type.
  6150. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6151. // This is a silly definition, because it gives an empty union a deleted
  6152. // default constructor. Don't do that.
  6153. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6154. bool AnyFields = false;
  6155. for (auto *F : MD->getParent()->fields())
  6156. if ((AnyFields = !F->isUnnamedBitfield()))
  6157. break;
  6158. if (!AnyFields)
  6159. return false;
  6160. if (Diagnose)
  6161. S.Diag(MD->getParent()->getLocation(),
  6162. diag::note_deleted_default_ctor_all_const)
  6163. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6164. return true;
  6165. }
  6166. return false;
  6167. }
  6168. /// Determine whether a defaulted special member function should be defined as
  6169. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6170. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6171. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6172. InheritedConstructorInfo *ICI,
  6173. bool Diagnose) {
  6174. if (MD->isInvalidDecl())
  6175. return false;
  6176. CXXRecordDecl *RD = MD->getParent();
  6177. assert(!RD->isDependentType() && "do deletion after instantiation");
  6178. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6179. return false;
  6180. // C++11 [expr.lambda.prim]p19:
  6181. // The closure type associated with a lambda-expression has a
  6182. // deleted (8.4.3) default constructor and a deleted copy
  6183. // assignment operator.
  6184. if (RD->isLambda() &&
  6185. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6186. if (Diagnose)
  6187. Diag(RD->getLocation(), diag::note_lambda_decl);
  6188. return true;
  6189. }
  6190. // For an anonymous struct or union, the copy and assignment special members
  6191. // will never be used, so skip the check. For an anonymous union declared at
  6192. // namespace scope, the constructor and destructor are used.
  6193. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6194. RD->isAnonymousStructOrUnion())
  6195. return false;
  6196. // C++11 [class.copy]p7, p18:
  6197. // If the class definition declares a move constructor or move assignment
  6198. // operator, an implicitly declared copy constructor or copy assignment
  6199. // operator is defined as deleted.
  6200. if (MD->isImplicit() &&
  6201. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6202. CXXMethodDecl *UserDeclaredMove = nullptr;
  6203. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6204. // deletion of the corresponding copy operation, not both copy operations.
  6205. // MSVC 2015 has adopted the standards conforming behavior.
  6206. bool DeletesOnlyMatchingCopy =
  6207. getLangOpts().MSVCCompat &&
  6208. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6209. if (RD->hasUserDeclaredMoveConstructor() &&
  6210. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6211. if (!Diagnose) return true;
  6212. // Find any user-declared move constructor.
  6213. for (auto *I : RD->ctors()) {
  6214. if (I->isMoveConstructor()) {
  6215. UserDeclaredMove = I;
  6216. break;
  6217. }
  6218. }
  6219. assert(UserDeclaredMove);
  6220. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6221. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6222. if (!Diagnose) return true;
  6223. // Find any user-declared move assignment operator.
  6224. for (auto *I : RD->methods()) {
  6225. if (I->isMoveAssignmentOperator()) {
  6226. UserDeclaredMove = I;
  6227. break;
  6228. }
  6229. }
  6230. assert(UserDeclaredMove);
  6231. }
  6232. if (UserDeclaredMove) {
  6233. Diag(UserDeclaredMove->getLocation(),
  6234. diag::note_deleted_copy_user_declared_move)
  6235. << (CSM == CXXCopyAssignment) << RD
  6236. << UserDeclaredMove->isMoveAssignmentOperator();
  6237. return true;
  6238. }
  6239. }
  6240. // Do access control from the special member function
  6241. ContextRAII MethodContext(*this, MD);
  6242. // C++11 [class.dtor]p5:
  6243. // -- for a virtual destructor, lookup of the non-array deallocation function
  6244. // results in an ambiguity or in a function that is deleted or inaccessible
  6245. if (CSM == CXXDestructor && MD->isVirtual()) {
  6246. FunctionDecl *OperatorDelete = nullptr;
  6247. DeclarationName Name =
  6248. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6249. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6250. OperatorDelete, /*Diagnose*/false)) {
  6251. if (Diagnose)
  6252. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6253. return true;
  6254. }
  6255. }
  6256. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6257. // Per DR1611, do not consider virtual bases of constructors of abstract
  6258. // classes, since we are not going to construct them.
  6259. // Per DR1658, do not consider virtual bases of destructors of abstract
  6260. // classes either.
  6261. // Per DR2180, for assignment operators we only assign (and thus only
  6262. // consider) direct bases.
  6263. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6264. : SMI.VisitPotentiallyConstructedBases))
  6265. return true;
  6266. if (SMI.shouldDeleteForAllConstMembers())
  6267. return true;
  6268. if (getLangOpts().CUDA) {
  6269. // We should delete the special member in CUDA mode if target inference
  6270. // failed.
  6271. return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
  6272. Diagnose);
  6273. }
  6274. return false;
  6275. }
  6276. /// Perform lookup for a special member of the specified kind, and determine
  6277. /// whether it is trivial. If the triviality can be determined without the
  6278. /// lookup, skip it. This is intended for use when determining whether a
  6279. /// special member of a containing object is trivial, and thus does not ever
  6280. /// perform overload resolution for default constructors.
  6281. ///
  6282. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6283. /// member that was most likely to be intended to be trivial, if any.
  6284. ///
  6285. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6286. /// determine whether the special member is trivial.
  6287. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6288. Sema::CXXSpecialMember CSM, unsigned Quals,
  6289. bool ConstRHS,
  6290. Sema::TrivialABIHandling TAH,
  6291. CXXMethodDecl **Selected) {
  6292. if (Selected)
  6293. *Selected = nullptr;
  6294. switch (CSM) {
  6295. case Sema::CXXInvalid:
  6296. llvm_unreachable("not a special member");
  6297. case Sema::CXXDefaultConstructor:
  6298. // C++11 [class.ctor]p5:
  6299. // A default constructor is trivial if:
  6300. // - all the [direct subobjects] have trivial default constructors
  6301. //
  6302. // Note, no overload resolution is performed in this case.
  6303. if (RD->hasTrivialDefaultConstructor())
  6304. return true;
  6305. if (Selected) {
  6306. // If there's a default constructor which could have been trivial, dig it
  6307. // out. Otherwise, if there's any user-provided default constructor, point
  6308. // to that as an example of why there's not a trivial one.
  6309. CXXConstructorDecl *DefCtor = nullptr;
  6310. if (RD->needsImplicitDefaultConstructor())
  6311. S.DeclareImplicitDefaultConstructor(RD);
  6312. for (auto *CI : RD->ctors()) {
  6313. if (!CI->isDefaultConstructor())
  6314. continue;
  6315. DefCtor = CI;
  6316. if (!DefCtor->isUserProvided())
  6317. break;
  6318. }
  6319. *Selected = DefCtor;
  6320. }
  6321. return false;
  6322. case Sema::CXXDestructor:
  6323. // C++11 [class.dtor]p5:
  6324. // A destructor is trivial if:
  6325. // - all the direct [subobjects] have trivial destructors
  6326. if (RD->hasTrivialDestructor() ||
  6327. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6328. RD->hasTrivialDestructorForCall()))
  6329. return true;
  6330. if (Selected) {
  6331. if (RD->needsImplicitDestructor())
  6332. S.DeclareImplicitDestructor(RD);
  6333. *Selected = RD->getDestructor();
  6334. }
  6335. return false;
  6336. case Sema::CXXCopyConstructor:
  6337. // C++11 [class.copy]p12:
  6338. // A copy constructor is trivial if:
  6339. // - the constructor selected to copy each direct [subobject] is trivial
  6340. if (RD->hasTrivialCopyConstructor() ||
  6341. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6342. RD->hasTrivialCopyConstructorForCall())) {
  6343. if (Quals == Qualifiers::Const)
  6344. // We must either select the trivial copy constructor or reach an
  6345. // ambiguity; no need to actually perform overload resolution.
  6346. return true;
  6347. } else if (!Selected) {
  6348. return false;
  6349. }
  6350. // In C++98, we are not supposed to perform overload resolution here, but we
  6351. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6352. // cases like B as having a non-trivial copy constructor:
  6353. // struct A { template<typename T> A(T&); };
  6354. // struct B { mutable A a; };
  6355. goto NeedOverloadResolution;
  6356. case Sema::CXXCopyAssignment:
  6357. // C++11 [class.copy]p25:
  6358. // A copy assignment operator is trivial if:
  6359. // - the assignment operator selected to copy each direct [subobject] is
  6360. // trivial
  6361. if (RD->hasTrivialCopyAssignment()) {
  6362. if (Quals == Qualifiers::Const)
  6363. return true;
  6364. } else if (!Selected) {
  6365. return false;
  6366. }
  6367. // In C++98, we are not supposed to perform overload resolution here, but we
  6368. // treat that as a language defect.
  6369. goto NeedOverloadResolution;
  6370. case Sema::CXXMoveConstructor:
  6371. case Sema::CXXMoveAssignment:
  6372. NeedOverloadResolution:
  6373. Sema::SpecialMemberOverloadResult SMOR =
  6374. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6375. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6376. // We treat it as not making the member non-trivial, just like the standard
  6377. // mandates for the default constructor. This should rarely matter, because
  6378. // the member will also be deleted.
  6379. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6380. return true;
  6381. if (!SMOR.getMethod()) {
  6382. assert(SMOR.getKind() ==
  6383. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6384. return false;
  6385. }
  6386. // We deliberately don't check if we found a deleted special member. We're
  6387. // not supposed to!
  6388. if (Selected)
  6389. *Selected = SMOR.getMethod();
  6390. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6391. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6392. return SMOR.getMethod()->isTrivialForCall();
  6393. return SMOR.getMethod()->isTrivial();
  6394. }
  6395. llvm_unreachable("unknown special method kind");
  6396. }
  6397. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6398. for (auto *CI : RD->ctors())
  6399. if (!CI->isImplicit())
  6400. return CI;
  6401. // Look for constructor templates.
  6402. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6403. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6404. if (CXXConstructorDecl *CD =
  6405. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6406. return CD;
  6407. }
  6408. return nullptr;
  6409. }
  6410. /// The kind of subobject we are checking for triviality. The values of this
  6411. /// enumeration are used in diagnostics.
  6412. enum TrivialSubobjectKind {
  6413. /// The subobject is a base class.
  6414. TSK_BaseClass,
  6415. /// The subobject is a non-static data member.
  6416. TSK_Field,
  6417. /// The object is actually the complete object.
  6418. TSK_CompleteObject
  6419. };
  6420. /// Check whether the special member selected for a given type would be trivial.
  6421. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6422. QualType SubType, bool ConstRHS,
  6423. Sema::CXXSpecialMember CSM,
  6424. TrivialSubobjectKind Kind,
  6425. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6426. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6427. if (!SubRD)
  6428. return true;
  6429. CXXMethodDecl *Selected;
  6430. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6431. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6432. return true;
  6433. if (Diagnose) {
  6434. if (ConstRHS)
  6435. SubType.addConst();
  6436. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6437. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6438. << Kind << SubType.getUnqualifiedType();
  6439. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6440. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6441. } else if (!Selected)
  6442. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6443. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6444. else if (Selected->isUserProvided()) {
  6445. if (Kind == TSK_CompleteObject)
  6446. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6447. << Kind << SubType.getUnqualifiedType() << CSM;
  6448. else {
  6449. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6450. << Kind << SubType.getUnqualifiedType() << CSM;
  6451. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6452. }
  6453. } else {
  6454. if (Kind != TSK_CompleteObject)
  6455. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6456. << Kind << SubType.getUnqualifiedType() << CSM;
  6457. // Explain why the defaulted or deleted special member isn't trivial.
  6458. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6459. Diagnose);
  6460. }
  6461. }
  6462. return false;
  6463. }
  6464. /// Check whether the members of a class type allow a special member to be
  6465. /// trivial.
  6466. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6467. Sema::CXXSpecialMember CSM,
  6468. bool ConstArg,
  6469. Sema::TrivialABIHandling TAH,
  6470. bool Diagnose) {
  6471. for (const auto *FI : RD->fields()) {
  6472. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6473. continue;
  6474. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6475. // Pretend anonymous struct or union members are members of this class.
  6476. if (FI->isAnonymousStructOrUnion()) {
  6477. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6478. CSM, ConstArg, TAH, Diagnose))
  6479. return false;
  6480. continue;
  6481. }
  6482. // C++11 [class.ctor]p5:
  6483. // A default constructor is trivial if [...]
  6484. // -- no non-static data member of its class has a
  6485. // brace-or-equal-initializer
  6486. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6487. if (Diagnose)
  6488. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6489. return false;
  6490. }
  6491. // Objective C ARC 4.3.5:
  6492. // [...] nontrivally ownership-qualified types are [...] not trivially
  6493. // default constructible, copy constructible, move constructible, copy
  6494. // assignable, move assignable, or destructible [...]
  6495. if (FieldType.hasNonTrivialObjCLifetime()) {
  6496. if (Diagnose)
  6497. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6498. << RD << FieldType.getObjCLifetime();
  6499. return false;
  6500. }
  6501. bool ConstRHS = ConstArg && !FI->isMutable();
  6502. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6503. CSM, TSK_Field, TAH, Diagnose))
  6504. return false;
  6505. }
  6506. return true;
  6507. }
  6508. /// Diagnose why the specified class does not have a trivial special member of
  6509. /// the given kind.
  6510. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6511. QualType Ty = Context.getRecordType(RD);
  6512. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6513. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6514. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6515. /*Diagnose*/true);
  6516. }
  6517. /// Determine whether a defaulted or deleted special member function is trivial,
  6518. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6519. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6520. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6521. TrivialABIHandling TAH, bool Diagnose) {
  6522. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6523. CXXRecordDecl *RD = MD->getParent();
  6524. bool ConstArg = false;
  6525. // C++11 [class.copy]p12, p25: [DR1593]
  6526. // A [special member] is trivial if [...] its parameter-type-list is
  6527. // equivalent to the parameter-type-list of an implicit declaration [...]
  6528. switch (CSM) {
  6529. case CXXDefaultConstructor:
  6530. case CXXDestructor:
  6531. // Trivial default constructors and destructors cannot have parameters.
  6532. break;
  6533. case CXXCopyConstructor:
  6534. case CXXCopyAssignment: {
  6535. // Trivial copy operations always have const, non-volatile parameter types.
  6536. ConstArg = true;
  6537. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6538. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6539. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6540. if (Diagnose)
  6541. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6542. << Param0->getSourceRange() << Param0->getType()
  6543. << Context.getLValueReferenceType(
  6544. Context.getRecordType(RD).withConst());
  6545. return false;
  6546. }
  6547. break;
  6548. }
  6549. case CXXMoveConstructor:
  6550. case CXXMoveAssignment: {
  6551. // Trivial move operations always have non-cv-qualified parameters.
  6552. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6553. const RValueReferenceType *RT =
  6554. Param0->getType()->getAs<RValueReferenceType>();
  6555. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6556. if (Diagnose)
  6557. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6558. << Param0->getSourceRange() << Param0->getType()
  6559. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6560. return false;
  6561. }
  6562. break;
  6563. }
  6564. case CXXInvalid:
  6565. llvm_unreachable("not a special member");
  6566. }
  6567. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6568. if (Diagnose)
  6569. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6570. diag::note_nontrivial_default_arg)
  6571. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6572. return false;
  6573. }
  6574. if (MD->isVariadic()) {
  6575. if (Diagnose)
  6576. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6577. return false;
  6578. }
  6579. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6580. // A copy/move [constructor or assignment operator] is trivial if
  6581. // -- the [member] selected to copy/move each direct base class subobject
  6582. // is trivial
  6583. //
  6584. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6585. // A [default constructor or destructor] is trivial if
  6586. // -- all the direct base classes have trivial [default constructors or
  6587. // destructors]
  6588. for (const auto &BI : RD->bases())
  6589. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6590. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6591. return false;
  6592. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6593. // A copy/move [constructor or assignment operator] for a class X is
  6594. // trivial if
  6595. // -- for each non-static data member of X that is of class type (or array
  6596. // thereof), the constructor selected to copy/move that member is
  6597. // trivial
  6598. //
  6599. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6600. // A [default constructor or destructor] is trivial if
  6601. // -- for all of the non-static data members of its class that are of class
  6602. // type (or array thereof), each such class has a trivial [default
  6603. // constructor or destructor]
  6604. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6605. return false;
  6606. // C++11 [class.dtor]p5:
  6607. // A destructor is trivial if [...]
  6608. // -- the destructor is not virtual
  6609. if (CSM == CXXDestructor && MD->isVirtual()) {
  6610. if (Diagnose)
  6611. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6612. return false;
  6613. }
  6614. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6615. // A [special member] for class X is trivial if [...]
  6616. // -- class X has no virtual functions and no virtual base classes
  6617. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6618. if (!Diagnose)
  6619. return false;
  6620. if (RD->getNumVBases()) {
  6621. // Check for virtual bases. We already know that the corresponding
  6622. // member in all bases is trivial, so vbases must all be direct.
  6623. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6624. assert(BS.isVirtual());
  6625. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6626. return false;
  6627. }
  6628. // Must have a virtual method.
  6629. for (const auto *MI : RD->methods()) {
  6630. if (MI->isVirtual()) {
  6631. SourceLocation MLoc = MI->getBeginLoc();
  6632. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6633. return false;
  6634. }
  6635. }
  6636. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6637. }
  6638. // Looks like it's trivial!
  6639. return true;
  6640. }
  6641. namespace {
  6642. struct FindHiddenVirtualMethod {
  6643. Sema *S;
  6644. CXXMethodDecl *Method;
  6645. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6646. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6647. private:
  6648. /// Check whether any most overriden method from MD in Methods
  6649. static bool CheckMostOverridenMethods(
  6650. const CXXMethodDecl *MD,
  6651. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6652. if (MD->size_overridden_methods() == 0)
  6653. return Methods.count(MD->getCanonicalDecl());
  6654. for (const CXXMethodDecl *O : MD->overridden_methods())
  6655. if (CheckMostOverridenMethods(O, Methods))
  6656. return true;
  6657. return false;
  6658. }
  6659. public:
  6660. /// Member lookup function that determines whether a given C++
  6661. /// method overloads virtual methods in a base class without overriding any,
  6662. /// to be used with CXXRecordDecl::lookupInBases().
  6663. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6664. RecordDecl *BaseRecord =
  6665. Specifier->getType()->getAs<RecordType>()->getDecl();
  6666. DeclarationName Name = Method->getDeclName();
  6667. assert(Name.getNameKind() == DeclarationName::Identifier);
  6668. bool foundSameNameMethod = false;
  6669. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6670. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6671. Path.Decls = Path.Decls.slice(1)) {
  6672. NamedDecl *D = Path.Decls.front();
  6673. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6674. MD = MD->getCanonicalDecl();
  6675. foundSameNameMethod = true;
  6676. // Interested only in hidden virtual methods.
  6677. if (!MD->isVirtual())
  6678. continue;
  6679. // If the method we are checking overrides a method from its base
  6680. // don't warn about the other overloaded methods. Clang deviates from
  6681. // GCC by only diagnosing overloads of inherited virtual functions that
  6682. // do not override any other virtual functions in the base. GCC's
  6683. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  6684. // function from a base class. These cases may be better served by a
  6685. // warning (not specific to virtual functions) on call sites when the
  6686. // call would select a different function from the base class, were it
  6687. // visible.
  6688. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  6689. if (!S->IsOverload(Method, MD, false))
  6690. return true;
  6691. // Collect the overload only if its hidden.
  6692. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  6693. overloadedMethods.push_back(MD);
  6694. }
  6695. }
  6696. if (foundSameNameMethod)
  6697. OverloadedMethods.append(overloadedMethods.begin(),
  6698. overloadedMethods.end());
  6699. return foundSameNameMethod;
  6700. }
  6701. };
  6702. } // end anonymous namespace
  6703. /// Add the most overriden methods from MD to Methods
  6704. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  6705. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  6706. if (MD->size_overridden_methods() == 0)
  6707. Methods.insert(MD->getCanonicalDecl());
  6708. else
  6709. for (const CXXMethodDecl *O : MD->overridden_methods())
  6710. AddMostOverridenMethods(O, Methods);
  6711. }
  6712. /// Check if a method overloads virtual methods in a base class without
  6713. /// overriding any.
  6714. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  6715. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6716. if (!MD->getDeclName().isIdentifier())
  6717. return;
  6718. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  6719. /*bool RecordPaths=*/false,
  6720. /*bool DetectVirtual=*/false);
  6721. FindHiddenVirtualMethod FHVM;
  6722. FHVM.Method = MD;
  6723. FHVM.S = this;
  6724. // Keep the base methods that were overriden or introduced in the subclass
  6725. // by 'using' in a set. A base method not in this set is hidden.
  6726. CXXRecordDecl *DC = MD->getParent();
  6727. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  6728. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6729. NamedDecl *ND = *I;
  6730. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  6731. ND = shad->getTargetDecl();
  6732. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6733. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  6734. }
  6735. if (DC->lookupInBases(FHVM, Paths))
  6736. OverloadedMethods = FHVM.OverloadedMethods;
  6737. }
  6738. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  6739. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6740. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  6741. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  6742. PartialDiagnostic PD = PDiag(
  6743. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  6744. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  6745. Diag(overloadedMD->getLocation(), PD);
  6746. }
  6747. }
  6748. /// Diagnose methods which overload virtual methods in a base class
  6749. /// without overriding any.
  6750. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  6751. if (MD->isInvalidDecl())
  6752. return;
  6753. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  6754. return;
  6755. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6756. FindHiddenVirtualMethods(MD, OverloadedMethods);
  6757. if (!OverloadedMethods.empty()) {
  6758. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  6759. << MD << (OverloadedMethods.size() > 1);
  6760. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  6761. }
  6762. }
  6763. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  6764. auto PrintDiagAndRemoveAttr = [&]() {
  6765. // No diagnostics if this is a template instantiation.
  6766. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  6767. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  6768. diag::ext_cannot_use_trivial_abi) << &RD;
  6769. RD.dropAttr<TrivialABIAttr>();
  6770. };
  6771. // Ill-formed if the struct has virtual functions.
  6772. if (RD.isPolymorphic()) {
  6773. PrintDiagAndRemoveAttr();
  6774. return;
  6775. }
  6776. for (const auto &B : RD.bases()) {
  6777. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  6778. // virtual base.
  6779. if ((!B.getType()->isDependentType() &&
  6780. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  6781. B.isVirtual()) {
  6782. PrintDiagAndRemoveAttr();
  6783. return;
  6784. }
  6785. }
  6786. for (const auto *FD : RD.fields()) {
  6787. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  6788. // non-trivial for the purpose of calls.
  6789. QualType FT = FD->getType();
  6790. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  6791. PrintDiagAndRemoveAttr();
  6792. return;
  6793. }
  6794. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  6795. if (!RT->isDependentType() &&
  6796. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  6797. PrintDiagAndRemoveAttr();
  6798. return;
  6799. }
  6800. }
  6801. }
  6802. void Sema::ActOnFinishCXXMemberSpecification(
  6803. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  6804. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  6805. if (!TagDecl)
  6806. return;
  6807. AdjustDeclIfTemplate(TagDecl);
  6808. for (const ParsedAttr &AL : AttrList) {
  6809. if (AL.getKind() != ParsedAttr::AT_Visibility)
  6810. continue;
  6811. AL.setInvalid();
  6812. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
  6813. << AL.getName();
  6814. }
  6815. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  6816. // strict aliasing violation!
  6817. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  6818. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  6819. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  6820. }
  6821. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  6822. /// special functions, such as the default constructor, copy
  6823. /// constructor, or destructor, to the given C++ class (C++
  6824. /// [special]p1). This routine can only be executed just before the
  6825. /// definition of the class is complete.
  6826. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  6827. if (ClassDecl->needsImplicitDefaultConstructor()) {
  6828. ++ASTContext::NumImplicitDefaultConstructors;
  6829. if (ClassDecl->hasInheritedConstructor())
  6830. DeclareImplicitDefaultConstructor(ClassDecl);
  6831. }
  6832. if (ClassDecl->needsImplicitCopyConstructor()) {
  6833. ++ASTContext::NumImplicitCopyConstructors;
  6834. // If the properties or semantics of the copy constructor couldn't be
  6835. // determined while the class was being declared, force a declaration
  6836. // of it now.
  6837. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  6838. ClassDecl->hasInheritedConstructor())
  6839. DeclareImplicitCopyConstructor(ClassDecl);
  6840. // For the MS ABI we need to know whether the copy ctor is deleted. A
  6841. // prerequisite for deleting the implicit copy ctor is that the class has a
  6842. // move ctor or move assignment that is either user-declared or whose
  6843. // semantics are inherited from a subobject. FIXME: We should provide a more
  6844. // direct way for CodeGen to ask whether the constructor was deleted.
  6845. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  6846. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  6847. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6848. ClassDecl->hasUserDeclaredMoveAssignment() ||
  6849. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  6850. DeclareImplicitCopyConstructor(ClassDecl);
  6851. }
  6852. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  6853. ++ASTContext::NumImplicitMoveConstructors;
  6854. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6855. ClassDecl->hasInheritedConstructor())
  6856. DeclareImplicitMoveConstructor(ClassDecl);
  6857. }
  6858. if (ClassDecl->needsImplicitCopyAssignment()) {
  6859. ++ASTContext::NumImplicitCopyAssignmentOperators;
  6860. // If we have a dynamic class, then the copy assignment operator may be
  6861. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  6862. // it shows up in the right place in the vtable and that we diagnose
  6863. // problems with the implicit exception specification.
  6864. if (ClassDecl->isDynamicClass() ||
  6865. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  6866. ClassDecl->hasInheritedAssignment())
  6867. DeclareImplicitCopyAssignment(ClassDecl);
  6868. }
  6869. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  6870. ++ASTContext::NumImplicitMoveAssignmentOperators;
  6871. // Likewise for the move assignment operator.
  6872. if (ClassDecl->isDynamicClass() ||
  6873. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  6874. ClassDecl->hasInheritedAssignment())
  6875. DeclareImplicitMoveAssignment(ClassDecl);
  6876. }
  6877. if (ClassDecl->needsImplicitDestructor()) {
  6878. ++ASTContext::NumImplicitDestructors;
  6879. // If we have a dynamic class, then the destructor may be virtual, so we
  6880. // have to declare the destructor immediately. This ensures that, e.g., it
  6881. // shows up in the right place in the vtable and that we diagnose problems
  6882. // with the implicit exception specification.
  6883. if (ClassDecl->isDynamicClass() ||
  6884. ClassDecl->needsOverloadResolutionForDestructor())
  6885. DeclareImplicitDestructor(ClassDecl);
  6886. }
  6887. }
  6888. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  6889. if (!D)
  6890. return 0;
  6891. // The order of template parameters is not important here. All names
  6892. // get added to the same scope.
  6893. SmallVector<TemplateParameterList *, 4> ParameterLists;
  6894. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6895. D = TD->getTemplatedDecl();
  6896. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  6897. ParameterLists.push_back(PSD->getTemplateParameters());
  6898. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  6899. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  6900. ParameterLists.push_back(DD->getTemplateParameterList(i));
  6901. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  6902. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  6903. ParameterLists.push_back(FTD->getTemplateParameters());
  6904. }
  6905. }
  6906. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  6907. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  6908. ParameterLists.push_back(TD->getTemplateParameterList(i));
  6909. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  6910. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  6911. ParameterLists.push_back(CTD->getTemplateParameters());
  6912. }
  6913. }
  6914. unsigned Count = 0;
  6915. for (TemplateParameterList *Params : ParameterLists) {
  6916. if (Params->size() > 0)
  6917. // Ignore explicit specializations; they don't contribute to the template
  6918. // depth.
  6919. ++Count;
  6920. for (NamedDecl *Param : *Params) {
  6921. if (Param->getDeclName()) {
  6922. S->AddDecl(Param);
  6923. IdResolver.AddDecl(Param);
  6924. }
  6925. }
  6926. }
  6927. return Count;
  6928. }
  6929. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6930. if (!RecordD) return;
  6931. AdjustDeclIfTemplate(RecordD);
  6932. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  6933. PushDeclContext(S, Record);
  6934. }
  6935. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6936. if (!RecordD) return;
  6937. PopDeclContext();
  6938. }
  6939. /// This is used to implement the constant expression evaluation part of the
  6940. /// attribute enable_if extension. There is nothing in standard C++ which would
  6941. /// require reentering parameters.
  6942. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  6943. if (!Param)
  6944. return;
  6945. S->AddDecl(Param);
  6946. if (Param->getDeclName())
  6947. IdResolver.AddDecl(Param);
  6948. }
  6949. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  6950. /// parsing a top-level (non-nested) C++ class, and we are now
  6951. /// parsing those parts of the given Method declaration that could
  6952. /// not be parsed earlier (C++ [class.mem]p2), such as default
  6953. /// arguments. This action should enter the scope of the given
  6954. /// Method declaration as if we had just parsed the qualified method
  6955. /// name. However, it should not bring the parameters into scope;
  6956. /// that will be performed by ActOnDelayedCXXMethodParameter.
  6957. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  6958. }
  6959. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  6960. /// C++ method declaration. We're (re-)introducing the given
  6961. /// function parameter into scope for use in parsing later parts of
  6962. /// the method declaration. For example, we could see an
  6963. /// ActOnParamDefaultArgument event for this parameter.
  6964. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  6965. if (!ParamD)
  6966. return;
  6967. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  6968. // If this parameter has an unparsed default argument, clear it out
  6969. // to make way for the parsed default argument.
  6970. if (Param->hasUnparsedDefaultArg())
  6971. Param->setDefaultArg(nullptr);
  6972. S->AddDecl(Param);
  6973. if (Param->getDeclName())
  6974. IdResolver.AddDecl(Param);
  6975. }
  6976. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  6977. /// processing the delayed method declaration for Method. The method
  6978. /// declaration is now considered finished. There may be a separate
  6979. /// ActOnStartOfFunctionDef action later (not necessarily
  6980. /// immediately!) for this method, if it was also defined inside the
  6981. /// class body.
  6982. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  6983. if (!MethodD)
  6984. return;
  6985. AdjustDeclIfTemplate(MethodD);
  6986. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  6987. // Now that we have our default arguments, check the constructor
  6988. // again. It could produce additional diagnostics or affect whether
  6989. // the class has implicitly-declared destructors, among other
  6990. // things.
  6991. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  6992. CheckConstructor(Constructor);
  6993. // Check the default arguments, which we may have added.
  6994. if (!Method->isInvalidDecl())
  6995. CheckCXXDefaultArguments(Method);
  6996. }
  6997. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  6998. /// the well-formedness of the constructor declarator @p D with type @p
  6999. /// R. If there are any errors in the declarator, this routine will
  7000. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7001. /// will be updated to reflect a well-formed type for the constructor and
  7002. /// returned.
  7003. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7004. StorageClass &SC) {
  7005. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7006. // C++ [class.ctor]p3:
  7007. // A constructor shall not be virtual (10.3) or static (9.4). A
  7008. // constructor can be invoked for a const, volatile or const
  7009. // volatile object. A constructor shall not be declared const,
  7010. // volatile, or const volatile (9.3.2).
  7011. if (isVirtual) {
  7012. if (!D.isInvalidType())
  7013. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7014. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7015. << SourceRange(D.getIdentifierLoc());
  7016. D.setInvalidType();
  7017. }
  7018. if (SC == SC_Static) {
  7019. if (!D.isInvalidType())
  7020. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7021. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7022. << SourceRange(D.getIdentifierLoc());
  7023. D.setInvalidType();
  7024. SC = SC_None;
  7025. }
  7026. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7027. diagnoseIgnoredQualifiers(
  7028. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7029. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7030. D.getDeclSpec().getRestrictSpecLoc(),
  7031. D.getDeclSpec().getAtomicSpecLoc());
  7032. D.setInvalidType();
  7033. }
  7034. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7035. if (FTI.TypeQuals != 0) {
  7036. if (FTI.TypeQuals & Qualifiers::Const)
  7037. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7038. << "const" << SourceRange(D.getIdentifierLoc());
  7039. if (FTI.TypeQuals & Qualifiers::Volatile)
  7040. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7041. << "volatile" << SourceRange(D.getIdentifierLoc());
  7042. if (FTI.TypeQuals & Qualifiers::Restrict)
  7043. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7044. << "restrict" << SourceRange(D.getIdentifierLoc());
  7045. D.setInvalidType();
  7046. }
  7047. // C++0x [class.ctor]p4:
  7048. // A constructor shall not be declared with a ref-qualifier.
  7049. if (FTI.hasRefQualifier()) {
  7050. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7051. << FTI.RefQualifierIsLValueRef
  7052. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7053. D.setInvalidType();
  7054. }
  7055. // Rebuild the function type "R" without any type qualifiers (in
  7056. // case any of the errors above fired) and with "void" as the
  7057. // return type, since constructors don't have return types.
  7058. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7059. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7060. return R;
  7061. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7062. EPI.TypeQuals = 0;
  7063. EPI.RefQualifier = RQ_None;
  7064. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7065. }
  7066. /// CheckConstructor - Checks a fully-formed constructor for
  7067. /// well-formedness, issuing any diagnostics required. Returns true if
  7068. /// the constructor declarator is invalid.
  7069. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7070. CXXRecordDecl *ClassDecl
  7071. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7072. if (!ClassDecl)
  7073. return Constructor->setInvalidDecl();
  7074. // C++ [class.copy]p3:
  7075. // A declaration of a constructor for a class X is ill-formed if
  7076. // its first parameter is of type (optionally cv-qualified) X and
  7077. // either there are no other parameters or else all other
  7078. // parameters have default arguments.
  7079. if (!Constructor->isInvalidDecl() &&
  7080. ((Constructor->getNumParams() == 1) ||
  7081. (Constructor->getNumParams() > 1 &&
  7082. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7083. Constructor->getTemplateSpecializationKind()
  7084. != TSK_ImplicitInstantiation) {
  7085. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7086. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7087. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7088. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7089. const char *ConstRef
  7090. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7091. : " const &";
  7092. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7093. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7094. // FIXME: Rather that making the constructor invalid, we should endeavor
  7095. // to fix the type.
  7096. Constructor->setInvalidDecl();
  7097. }
  7098. }
  7099. }
  7100. /// CheckDestructor - Checks a fully-formed destructor definition for
  7101. /// well-formedness, issuing any diagnostics required. Returns true
  7102. /// on error.
  7103. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7104. CXXRecordDecl *RD = Destructor->getParent();
  7105. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7106. SourceLocation Loc;
  7107. if (!Destructor->isImplicit())
  7108. Loc = Destructor->getLocation();
  7109. else
  7110. Loc = RD->getLocation();
  7111. // If we have a virtual destructor, look up the deallocation function
  7112. if (FunctionDecl *OperatorDelete =
  7113. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7114. Expr *ThisArg = nullptr;
  7115. // If the notional 'delete this' expression requires a non-trivial
  7116. // conversion from 'this' to the type of a destroying operator delete's
  7117. // first parameter, perform that conversion now.
  7118. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7119. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7120. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7121. // C++ [class.dtor]p13:
  7122. // ... as if for the expression 'delete this' appearing in a
  7123. // non-virtual destructor of the destructor's class.
  7124. ContextRAII SwitchContext(*this, Destructor);
  7125. ExprResult This =
  7126. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7127. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7128. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7129. if (This.isInvalid()) {
  7130. // FIXME: Register this as a context note so that it comes out
  7131. // in the right order.
  7132. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7133. return true;
  7134. }
  7135. ThisArg = This.get();
  7136. }
  7137. }
  7138. MarkFunctionReferenced(Loc, OperatorDelete);
  7139. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7140. }
  7141. }
  7142. return false;
  7143. }
  7144. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7145. /// the well-formednes of the destructor declarator @p D with type @p
  7146. /// R. If there are any errors in the declarator, this routine will
  7147. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7148. /// will be updated to reflect a well-formed type for the destructor and
  7149. /// returned.
  7150. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7151. StorageClass& SC) {
  7152. // C++ [class.dtor]p1:
  7153. // [...] A typedef-name that names a class is a class-name
  7154. // (7.1.3); however, a typedef-name that names a class shall not
  7155. // be used as the identifier in the declarator for a destructor
  7156. // declaration.
  7157. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7158. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7159. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7160. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7161. else if (const TemplateSpecializationType *TST =
  7162. DeclaratorType->getAs<TemplateSpecializationType>())
  7163. if (TST->isTypeAlias())
  7164. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7165. << DeclaratorType << 1;
  7166. // C++ [class.dtor]p2:
  7167. // A destructor is used to destroy objects of its class type. A
  7168. // destructor takes no parameters, and no return type can be
  7169. // specified for it (not even void). The address of a destructor
  7170. // shall not be taken. A destructor shall not be static. A
  7171. // destructor can be invoked for a const, volatile or const
  7172. // volatile object. A destructor shall not be declared const,
  7173. // volatile or const volatile (9.3.2).
  7174. if (SC == SC_Static) {
  7175. if (!D.isInvalidType())
  7176. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7177. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7178. << SourceRange(D.getIdentifierLoc())
  7179. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7180. SC = SC_None;
  7181. }
  7182. if (!D.isInvalidType()) {
  7183. // Destructors don't have return types, but the parser will
  7184. // happily parse something like:
  7185. //
  7186. // class X {
  7187. // float ~X();
  7188. // };
  7189. //
  7190. // The return type will be eliminated later.
  7191. if (D.getDeclSpec().hasTypeSpecifier())
  7192. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7193. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7194. << SourceRange(D.getIdentifierLoc());
  7195. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7196. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7197. SourceLocation(),
  7198. D.getDeclSpec().getConstSpecLoc(),
  7199. D.getDeclSpec().getVolatileSpecLoc(),
  7200. D.getDeclSpec().getRestrictSpecLoc(),
  7201. D.getDeclSpec().getAtomicSpecLoc());
  7202. D.setInvalidType();
  7203. }
  7204. }
  7205. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7206. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  7207. if (FTI.TypeQuals & Qualifiers::Const)
  7208. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7209. << "const" << SourceRange(D.getIdentifierLoc());
  7210. if (FTI.TypeQuals & Qualifiers::Volatile)
  7211. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7212. << "volatile" << SourceRange(D.getIdentifierLoc());
  7213. if (FTI.TypeQuals & Qualifiers::Restrict)
  7214. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7215. << "restrict" << SourceRange(D.getIdentifierLoc());
  7216. D.setInvalidType();
  7217. }
  7218. // C++0x [class.dtor]p2:
  7219. // A destructor shall not be declared with a ref-qualifier.
  7220. if (FTI.hasRefQualifier()) {
  7221. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7222. << FTI.RefQualifierIsLValueRef
  7223. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7224. D.setInvalidType();
  7225. }
  7226. // Make sure we don't have any parameters.
  7227. if (FTIHasNonVoidParameters(FTI)) {
  7228. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7229. // Delete the parameters.
  7230. FTI.freeParams();
  7231. D.setInvalidType();
  7232. }
  7233. // Make sure the destructor isn't variadic.
  7234. if (FTI.isVariadic) {
  7235. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7236. D.setInvalidType();
  7237. }
  7238. // Rebuild the function type "R" without any type qualifiers or
  7239. // parameters (in case any of the errors above fired) and with
  7240. // "void" as the return type, since destructors don't have return
  7241. // types.
  7242. if (!D.isInvalidType())
  7243. return R;
  7244. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7245. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7246. EPI.Variadic = false;
  7247. EPI.TypeQuals = 0;
  7248. EPI.RefQualifier = RQ_None;
  7249. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7250. }
  7251. static void extendLeft(SourceRange &R, SourceRange Before) {
  7252. if (Before.isInvalid())
  7253. return;
  7254. R.setBegin(Before.getBegin());
  7255. if (R.getEnd().isInvalid())
  7256. R.setEnd(Before.getEnd());
  7257. }
  7258. static void extendRight(SourceRange &R, SourceRange After) {
  7259. if (After.isInvalid())
  7260. return;
  7261. if (R.getBegin().isInvalid())
  7262. R.setBegin(After.getBegin());
  7263. R.setEnd(After.getEnd());
  7264. }
  7265. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7266. /// well-formednes of the conversion function declarator @p D with
  7267. /// type @p R. If there are any errors in the declarator, this routine
  7268. /// will emit diagnostics and return true. Otherwise, it will return
  7269. /// false. Either way, the type @p R will be updated to reflect a
  7270. /// well-formed type for the conversion operator.
  7271. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7272. StorageClass& SC) {
  7273. // C++ [class.conv.fct]p1:
  7274. // Neither parameter types nor return type can be specified. The
  7275. // type of a conversion function (8.3.5) is "function taking no
  7276. // parameter returning conversion-type-id."
  7277. if (SC == SC_Static) {
  7278. if (!D.isInvalidType())
  7279. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7280. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7281. << D.getName().getSourceRange();
  7282. D.setInvalidType();
  7283. SC = SC_None;
  7284. }
  7285. TypeSourceInfo *ConvTSI = nullptr;
  7286. QualType ConvType =
  7287. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7288. const DeclSpec &DS = D.getDeclSpec();
  7289. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7290. // Conversion functions don't have return types, but the parser will
  7291. // happily parse something like:
  7292. //
  7293. // class X {
  7294. // float operator bool();
  7295. // };
  7296. //
  7297. // The return type will be changed later anyway.
  7298. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7299. << SourceRange(DS.getTypeSpecTypeLoc())
  7300. << SourceRange(D.getIdentifierLoc());
  7301. D.setInvalidType();
  7302. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7303. // It's also plausible that the user writes type qualifiers in the wrong
  7304. // place, such as:
  7305. // struct S { const operator int(); };
  7306. // FIXME: we could provide a fixit to move the qualifiers onto the
  7307. // conversion type.
  7308. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7309. << SourceRange(D.getIdentifierLoc()) << 0;
  7310. D.setInvalidType();
  7311. }
  7312. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7313. // Make sure we don't have any parameters.
  7314. if (Proto->getNumParams() > 0) {
  7315. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7316. // Delete the parameters.
  7317. D.getFunctionTypeInfo().freeParams();
  7318. D.setInvalidType();
  7319. } else if (Proto->isVariadic()) {
  7320. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7321. D.setInvalidType();
  7322. }
  7323. // Diagnose "&operator bool()" and other such nonsense. This
  7324. // is actually a gcc extension which we don't support.
  7325. if (Proto->getReturnType() != ConvType) {
  7326. bool NeedsTypedef = false;
  7327. SourceRange Before, After;
  7328. // Walk the chunks and extract information on them for our diagnostic.
  7329. bool PastFunctionChunk = false;
  7330. for (auto &Chunk : D.type_objects()) {
  7331. switch (Chunk.Kind) {
  7332. case DeclaratorChunk::Function:
  7333. if (!PastFunctionChunk) {
  7334. if (Chunk.Fun.HasTrailingReturnType) {
  7335. TypeSourceInfo *TRT = nullptr;
  7336. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7337. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7338. }
  7339. PastFunctionChunk = true;
  7340. break;
  7341. }
  7342. LLVM_FALLTHROUGH;
  7343. case DeclaratorChunk::Array:
  7344. NeedsTypedef = true;
  7345. extendRight(After, Chunk.getSourceRange());
  7346. break;
  7347. case DeclaratorChunk::Pointer:
  7348. case DeclaratorChunk::BlockPointer:
  7349. case DeclaratorChunk::Reference:
  7350. case DeclaratorChunk::MemberPointer:
  7351. case DeclaratorChunk::Pipe:
  7352. extendLeft(Before, Chunk.getSourceRange());
  7353. break;
  7354. case DeclaratorChunk::Paren:
  7355. extendLeft(Before, Chunk.Loc);
  7356. extendRight(After, Chunk.EndLoc);
  7357. break;
  7358. }
  7359. }
  7360. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7361. After.isValid() ? After.getBegin() :
  7362. D.getIdentifierLoc();
  7363. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7364. DB << Before << After;
  7365. if (!NeedsTypedef) {
  7366. DB << /*don't need a typedef*/0;
  7367. // If we can provide a correct fix-it hint, do so.
  7368. if (After.isInvalid() && ConvTSI) {
  7369. SourceLocation InsertLoc =
  7370. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7371. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7372. << FixItHint::CreateInsertionFromRange(
  7373. InsertLoc, CharSourceRange::getTokenRange(Before))
  7374. << FixItHint::CreateRemoval(Before);
  7375. }
  7376. } else if (!Proto->getReturnType()->isDependentType()) {
  7377. DB << /*typedef*/1 << Proto->getReturnType();
  7378. } else if (getLangOpts().CPlusPlus11) {
  7379. DB << /*alias template*/2 << Proto->getReturnType();
  7380. } else {
  7381. DB << /*might not be fixable*/3;
  7382. }
  7383. // Recover by incorporating the other type chunks into the result type.
  7384. // Note, this does *not* change the name of the function. This is compatible
  7385. // with the GCC extension:
  7386. // struct S { &operator int(); } s;
  7387. // int &r = s.operator int(); // ok in GCC
  7388. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7389. ConvType = Proto->getReturnType();
  7390. }
  7391. // C++ [class.conv.fct]p4:
  7392. // The conversion-type-id shall not represent a function type nor
  7393. // an array type.
  7394. if (ConvType->isArrayType()) {
  7395. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7396. ConvType = Context.getPointerType(ConvType);
  7397. D.setInvalidType();
  7398. } else if (ConvType->isFunctionType()) {
  7399. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7400. ConvType = Context.getPointerType(ConvType);
  7401. D.setInvalidType();
  7402. }
  7403. // Rebuild the function type "R" without any parameters (in case any
  7404. // of the errors above fired) and with the conversion type as the
  7405. // return type.
  7406. if (D.isInvalidType())
  7407. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7408. // C++0x explicit conversion operators.
  7409. if (DS.isExplicitSpecified())
  7410. Diag(DS.getExplicitSpecLoc(),
  7411. getLangOpts().CPlusPlus11
  7412. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7413. : diag::ext_explicit_conversion_functions)
  7414. << SourceRange(DS.getExplicitSpecLoc());
  7415. }
  7416. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7417. /// the declaration of the given C++ conversion function. This routine
  7418. /// is responsible for recording the conversion function in the C++
  7419. /// class, if possible.
  7420. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7421. assert(Conversion && "Expected to receive a conversion function declaration");
  7422. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7423. // Make sure we aren't redeclaring the conversion function.
  7424. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7425. // C++ [class.conv.fct]p1:
  7426. // [...] A conversion function is never used to convert a
  7427. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7428. // same object type (or a reference to it), to a (possibly
  7429. // cv-qualified) base class of that type (or a reference to it),
  7430. // or to (possibly cv-qualified) void.
  7431. // FIXME: Suppress this warning if the conversion function ends up being a
  7432. // virtual function that overrides a virtual function in a base class.
  7433. QualType ClassType
  7434. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7435. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7436. ConvType = ConvTypeRef->getPointeeType();
  7437. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7438. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7439. /* Suppress diagnostics for instantiations. */;
  7440. else if (ConvType->isRecordType()) {
  7441. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7442. if (ConvType == ClassType)
  7443. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7444. << ClassType;
  7445. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7446. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7447. << ClassType << ConvType;
  7448. } else if (ConvType->isVoidType()) {
  7449. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7450. << ClassType << ConvType;
  7451. }
  7452. if (FunctionTemplateDecl *ConversionTemplate
  7453. = Conversion->getDescribedFunctionTemplate())
  7454. return ConversionTemplate;
  7455. return Conversion;
  7456. }
  7457. namespace {
  7458. /// Utility class to accumulate and print a diagnostic listing the invalid
  7459. /// specifier(s) on a declaration.
  7460. struct BadSpecifierDiagnoser {
  7461. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7462. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7463. ~BadSpecifierDiagnoser() {
  7464. Diagnostic << Specifiers;
  7465. }
  7466. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7467. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7468. }
  7469. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7470. return check(SpecLoc,
  7471. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7472. }
  7473. void check(SourceLocation SpecLoc, const char *Spec) {
  7474. if (SpecLoc.isInvalid()) return;
  7475. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7476. if (!Specifiers.empty()) Specifiers += " ";
  7477. Specifiers += Spec;
  7478. }
  7479. Sema &S;
  7480. Sema::SemaDiagnosticBuilder Diagnostic;
  7481. std::string Specifiers;
  7482. };
  7483. }
  7484. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7485. /// These aren't actually declarators in the grammar, so we need to check that
  7486. /// the user didn't specify any pieces that are not part of the deduction-guide
  7487. /// grammar.
  7488. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7489. StorageClass &SC) {
  7490. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7491. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7492. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7493. // C++ [temp.deduct.guide]p3:
  7494. // A deduction-gide shall be declared in the same scope as the
  7495. // corresponding class template.
  7496. if (!CurContext->getRedeclContext()->Equals(
  7497. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7498. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7499. << GuidedTemplateDecl;
  7500. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7501. }
  7502. auto &DS = D.getMutableDeclSpec();
  7503. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7504. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7505. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7506. DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
  7507. BadSpecifierDiagnoser Diagnoser(
  7508. *this, D.getIdentifierLoc(),
  7509. diag::err_deduction_guide_invalid_specifier);
  7510. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7511. DS.ClearStorageClassSpecs();
  7512. SC = SC_None;
  7513. // 'explicit' is permitted.
  7514. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7515. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7516. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7517. DS.ClearConstexprSpec();
  7518. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7519. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7520. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7521. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7522. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7523. DS.ClearTypeQualifiers();
  7524. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7525. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7526. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7527. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7528. DS.ClearTypeSpecType();
  7529. }
  7530. if (D.isInvalidType())
  7531. return;
  7532. // Check the declarator is simple enough.
  7533. bool FoundFunction = false;
  7534. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7535. if (Chunk.Kind == DeclaratorChunk::Paren)
  7536. continue;
  7537. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7538. Diag(D.getDeclSpec().getBeginLoc(),
  7539. diag::err_deduction_guide_with_complex_decl)
  7540. << D.getSourceRange();
  7541. break;
  7542. }
  7543. if (!Chunk.Fun.hasTrailingReturnType()) {
  7544. Diag(D.getName().getBeginLoc(),
  7545. diag::err_deduction_guide_no_trailing_return_type);
  7546. break;
  7547. }
  7548. // Check that the return type is written as a specialization of
  7549. // the template specified as the deduction-guide's name.
  7550. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7551. TypeSourceInfo *TSI = nullptr;
  7552. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7553. assert(TSI && "deduction guide has valid type but invalid return type?");
  7554. bool AcceptableReturnType = false;
  7555. bool MightInstantiateToSpecialization = false;
  7556. if (auto RetTST =
  7557. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7558. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7559. bool TemplateMatches =
  7560. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7561. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7562. AcceptableReturnType = true;
  7563. else {
  7564. // This could still instantiate to the right type, unless we know it
  7565. // names the wrong class template.
  7566. auto *TD = SpecifiedName.getAsTemplateDecl();
  7567. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7568. !TemplateMatches);
  7569. }
  7570. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7571. MightInstantiateToSpecialization = true;
  7572. }
  7573. if (!AcceptableReturnType) {
  7574. Diag(TSI->getTypeLoc().getBeginLoc(),
  7575. diag::err_deduction_guide_bad_trailing_return_type)
  7576. << GuidedTemplate << TSI->getType()
  7577. << MightInstantiateToSpecialization
  7578. << TSI->getTypeLoc().getSourceRange();
  7579. }
  7580. // Keep going to check that we don't have any inner declarator pieces (we
  7581. // could still have a function returning a pointer to a function).
  7582. FoundFunction = true;
  7583. }
  7584. if (D.isFunctionDefinition())
  7585. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7586. }
  7587. //===----------------------------------------------------------------------===//
  7588. // Namespace Handling
  7589. //===----------------------------------------------------------------------===//
  7590. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7591. /// reopened.
  7592. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7593. SourceLocation Loc,
  7594. IdentifierInfo *II, bool *IsInline,
  7595. NamespaceDecl *PrevNS) {
  7596. assert(*IsInline != PrevNS->isInline());
  7597. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7598. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7599. // inline namespaces, with the intention of bringing names into namespace std.
  7600. //
  7601. // We support this just well enough to get that case working; this is not
  7602. // sufficient to support reopening namespaces as inline in general.
  7603. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7604. S.getSourceManager().isInSystemHeader(Loc)) {
  7605. // Mark all prior declarations of the namespace as inline.
  7606. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7607. NS = NS->getPreviousDecl())
  7608. NS->setInline(*IsInline);
  7609. // Patch up the lookup table for the containing namespace. This isn't really
  7610. // correct, but it's good enough for this particular case.
  7611. for (auto *I : PrevNS->decls())
  7612. if (auto *ND = dyn_cast<NamedDecl>(I))
  7613. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7614. return;
  7615. }
  7616. if (PrevNS->isInline())
  7617. // The user probably just forgot the 'inline', so suggest that it
  7618. // be added back.
  7619. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7620. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7621. else
  7622. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7623. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7624. *IsInline = PrevNS->isInline();
  7625. }
  7626. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7627. /// definition.
  7628. Decl *Sema::ActOnStartNamespaceDef(
  7629. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7630. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7631. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7632. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7633. // For anonymous namespace, take the location of the left brace.
  7634. SourceLocation Loc = II ? IdentLoc : LBrace;
  7635. bool IsInline = InlineLoc.isValid();
  7636. bool IsInvalid = false;
  7637. bool IsStd = false;
  7638. bool AddToKnown = false;
  7639. Scope *DeclRegionScope = NamespcScope->getParent();
  7640. NamespaceDecl *PrevNS = nullptr;
  7641. if (II) {
  7642. // C++ [namespace.def]p2:
  7643. // The identifier in an original-namespace-definition shall not
  7644. // have been previously defined in the declarative region in
  7645. // which the original-namespace-definition appears. The
  7646. // identifier in an original-namespace-definition is the name of
  7647. // the namespace. Subsequently in that declarative region, it is
  7648. // treated as an original-namespace-name.
  7649. //
  7650. // Since namespace names are unique in their scope, and we don't
  7651. // look through using directives, just look for any ordinary names
  7652. // as if by qualified name lookup.
  7653. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7654. ForExternalRedeclaration);
  7655. LookupQualifiedName(R, CurContext->getRedeclContext());
  7656. NamedDecl *PrevDecl =
  7657. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7658. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7659. if (PrevNS) {
  7660. // This is an extended namespace definition.
  7661. if (IsInline != PrevNS->isInline())
  7662. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7663. &IsInline, PrevNS);
  7664. } else if (PrevDecl) {
  7665. // This is an invalid name redefinition.
  7666. Diag(Loc, diag::err_redefinition_different_kind)
  7667. << II;
  7668. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7669. IsInvalid = true;
  7670. // Continue on to push Namespc as current DeclContext and return it.
  7671. } else if (II->isStr("std") &&
  7672. CurContext->getRedeclContext()->isTranslationUnit()) {
  7673. // This is the first "real" definition of the namespace "std", so update
  7674. // our cache of the "std" namespace to point at this definition.
  7675. PrevNS = getStdNamespace();
  7676. IsStd = true;
  7677. AddToKnown = !IsInline;
  7678. } else {
  7679. // We've seen this namespace for the first time.
  7680. AddToKnown = !IsInline;
  7681. }
  7682. } else {
  7683. // Anonymous namespaces.
  7684. // Determine whether the parent already has an anonymous namespace.
  7685. DeclContext *Parent = CurContext->getRedeclContext();
  7686. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7687. PrevNS = TU->getAnonymousNamespace();
  7688. } else {
  7689. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  7690. PrevNS = ND->getAnonymousNamespace();
  7691. }
  7692. if (PrevNS && IsInline != PrevNS->isInline())
  7693. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  7694. &IsInline, PrevNS);
  7695. }
  7696. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  7697. StartLoc, Loc, II, PrevNS);
  7698. if (IsInvalid)
  7699. Namespc->setInvalidDecl();
  7700. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  7701. AddPragmaAttributes(DeclRegionScope, Namespc);
  7702. // FIXME: Should we be merging attributes?
  7703. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  7704. PushNamespaceVisibilityAttr(Attr, Loc);
  7705. if (IsStd)
  7706. StdNamespace = Namespc;
  7707. if (AddToKnown)
  7708. KnownNamespaces[Namespc] = false;
  7709. if (II) {
  7710. PushOnScopeChains(Namespc, DeclRegionScope);
  7711. } else {
  7712. // Link the anonymous namespace into its parent.
  7713. DeclContext *Parent = CurContext->getRedeclContext();
  7714. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7715. TU->setAnonymousNamespace(Namespc);
  7716. } else {
  7717. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  7718. }
  7719. CurContext->addDecl(Namespc);
  7720. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  7721. // behaves as if it were replaced by
  7722. // namespace unique { /* empty body */ }
  7723. // using namespace unique;
  7724. // namespace unique { namespace-body }
  7725. // where all occurrences of 'unique' in a translation unit are
  7726. // replaced by the same identifier and this identifier differs
  7727. // from all other identifiers in the entire program.
  7728. // We just create the namespace with an empty name and then add an
  7729. // implicit using declaration, just like the standard suggests.
  7730. //
  7731. // CodeGen enforces the "universally unique" aspect by giving all
  7732. // declarations semantically contained within an anonymous
  7733. // namespace internal linkage.
  7734. if (!PrevNS) {
  7735. UD = UsingDirectiveDecl::Create(Context, Parent,
  7736. /* 'using' */ LBrace,
  7737. /* 'namespace' */ SourceLocation(),
  7738. /* qualifier */ NestedNameSpecifierLoc(),
  7739. /* identifier */ SourceLocation(),
  7740. Namespc,
  7741. /* Ancestor */ Parent);
  7742. UD->setImplicit();
  7743. Parent->addDecl(UD);
  7744. }
  7745. }
  7746. ActOnDocumentableDecl(Namespc);
  7747. // Although we could have an invalid decl (i.e. the namespace name is a
  7748. // redefinition), push it as current DeclContext and try to continue parsing.
  7749. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  7750. // for the namespace has the declarations that showed up in that particular
  7751. // namespace definition.
  7752. PushDeclContext(NamespcScope, Namespc);
  7753. return Namespc;
  7754. }
  7755. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  7756. /// is a namespace alias, returns the namespace it points to.
  7757. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  7758. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  7759. return AD->getNamespace();
  7760. return dyn_cast_or_null<NamespaceDecl>(D);
  7761. }
  7762. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  7763. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  7764. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  7765. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  7766. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  7767. Namespc->setRBraceLoc(RBrace);
  7768. PopDeclContext();
  7769. if (Namespc->hasAttr<VisibilityAttr>())
  7770. PopPragmaVisibility(true, RBrace);
  7771. }
  7772. CXXRecordDecl *Sema::getStdBadAlloc() const {
  7773. return cast_or_null<CXXRecordDecl>(
  7774. StdBadAlloc.get(Context.getExternalSource()));
  7775. }
  7776. EnumDecl *Sema::getStdAlignValT() const {
  7777. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  7778. }
  7779. NamespaceDecl *Sema::getStdNamespace() const {
  7780. return cast_or_null<NamespaceDecl>(
  7781. StdNamespace.get(Context.getExternalSource()));
  7782. }
  7783. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  7784. if (!StdExperimentalNamespaceCache) {
  7785. if (auto Std = getStdNamespace()) {
  7786. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  7787. SourceLocation(), LookupNamespaceName);
  7788. if (!LookupQualifiedName(Result, Std) ||
  7789. !(StdExperimentalNamespaceCache =
  7790. Result.getAsSingle<NamespaceDecl>()))
  7791. Result.suppressDiagnostics();
  7792. }
  7793. }
  7794. return StdExperimentalNamespaceCache;
  7795. }
  7796. namespace {
  7797. enum UnsupportedSTLSelect {
  7798. USS_InvalidMember,
  7799. USS_MissingMember,
  7800. USS_NonTrivial,
  7801. USS_Other
  7802. };
  7803. struct InvalidSTLDiagnoser {
  7804. Sema &S;
  7805. SourceLocation Loc;
  7806. QualType TyForDiags;
  7807. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  7808. const VarDecl *VD = nullptr) {
  7809. {
  7810. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  7811. << TyForDiags << ((int)Sel);
  7812. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  7813. assert(!Name.empty());
  7814. D << Name;
  7815. }
  7816. }
  7817. if (Sel == USS_InvalidMember) {
  7818. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  7819. << VD << VD->getSourceRange();
  7820. }
  7821. return QualType();
  7822. }
  7823. };
  7824. } // namespace
  7825. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  7826. SourceLocation Loc) {
  7827. assert(getLangOpts().CPlusPlus &&
  7828. "Looking for comparison category type outside of C++.");
  7829. // Check if we've already successfully checked the comparison category type
  7830. // before. If so, skip checking it again.
  7831. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  7832. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  7833. return Info->getType();
  7834. // If lookup failed
  7835. if (!Info) {
  7836. std::string NameForDiags = "std::";
  7837. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  7838. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  7839. << NameForDiags;
  7840. return QualType();
  7841. }
  7842. assert(Info->Kind == Kind);
  7843. assert(Info->Record);
  7844. // Update the Record decl in case we encountered a forward declaration on our
  7845. // first pass. FIXME: This is a bit of a hack.
  7846. if (Info->Record->hasDefinition())
  7847. Info->Record = Info->Record->getDefinition();
  7848. // Use an elaborated type for diagnostics which has a name containing the
  7849. // prepended 'std' namespace but not any inline namespace names.
  7850. QualType TyForDiags = [&]() {
  7851. auto *NNS =
  7852. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  7853. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  7854. }();
  7855. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  7856. return QualType();
  7857. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  7858. if (!Info->Record->isTriviallyCopyable())
  7859. return UnsupportedSTLError(USS_NonTrivial);
  7860. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  7861. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  7862. // Tolerate empty base classes.
  7863. if (Base->isEmpty())
  7864. continue;
  7865. // Reject STL implementations which have at least one non-empty base.
  7866. return UnsupportedSTLError();
  7867. }
  7868. // Check that the STL has implemented the types using a single integer field.
  7869. // This expectation allows better codegen for builtin operators. We require:
  7870. // (1) The class has exactly one field.
  7871. // (2) The field is an integral or enumeration type.
  7872. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  7873. if (std::distance(FIt, FEnd) != 1 ||
  7874. !FIt->getType()->isIntegralOrEnumerationType()) {
  7875. return UnsupportedSTLError();
  7876. }
  7877. // Build each of the require values and store them in Info.
  7878. for (ComparisonCategoryResult CCR :
  7879. ComparisonCategories::getPossibleResultsForType(Kind)) {
  7880. StringRef MemName = ComparisonCategories::getResultString(CCR);
  7881. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  7882. if (!ValInfo)
  7883. return UnsupportedSTLError(USS_MissingMember, MemName);
  7884. VarDecl *VD = ValInfo->VD;
  7885. assert(VD && "should not be null!");
  7886. // Attempt to diagnose reasons why the STL definition of this type
  7887. // might be foobar, including it failing to be a constant expression.
  7888. // TODO Handle more ways the lookup or result can be invalid.
  7889. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  7890. !VD->checkInitIsICE())
  7891. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  7892. // Attempt to evaluate the var decl as a constant expression and extract
  7893. // the value of its first field as a ICE. If this fails, the STL
  7894. // implementation is not supported.
  7895. if (!ValInfo->hasValidIntValue())
  7896. return UnsupportedSTLError();
  7897. MarkVariableReferenced(Loc, VD);
  7898. }
  7899. // We've successfully built the required types and expressions. Update
  7900. // the cache and return the newly cached value.
  7901. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  7902. return Info->getType();
  7903. }
  7904. /// Retrieve the special "std" namespace, which may require us to
  7905. /// implicitly define the namespace.
  7906. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  7907. if (!StdNamespace) {
  7908. // The "std" namespace has not yet been defined, so build one implicitly.
  7909. StdNamespace = NamespaceDecl::Create(Context,
  7910. Context.getTranslationUnitDecl(),
  7911. /*Inline=*/false,
  7912. SourceLocation(), SourceLocation(),
  7913. &PP.getIdentifierTable().get("std"),
  7914. /*PrevDecl=*/nullptr);
  7915. getStdNamespace()->setImplicit(true);
  7916. }
  7917. return getStdNamespace();
  7918. }
  7919. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  7920. assert(getLangOpts().CPlusPlus &&
  7921. "Looking for std::initializer_list outside of C++.");
  7922. // We're looking for implicit instantiations of
  7923. // template <typename E> class std::initializer_list.
  7924. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  7925. return false;
  7926. ClassTemplateDecl *Template = nullptr;
  7927. const TemplateArgument *Arguments = nullptr;
  7928. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  7929. ClassTemplateSpecializationDecl *Specialization =
  7930. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  7931. if (!Specialization)
  7932. return false;
  7933. Template = Specialization->getSpecializedTemplate();
  7934. Arguments = Specialization->getTemplateArgs().data();
  7935. } else if (const TemplateSpecializationType *TST =
  7936. Ty->getAs<TemplateSpecializationType>()) {
  7937. Template = dyn_cast_or_null<ClassTemplateDecl>(
  7938. TST->getTemplateName().getAsTemplateDecl());
  7939. Arguments = TST->getArgs();
  7940. }
  7941. if (!Template)
  7942. return false;
  7943. if (!StdInitializerList) {
  7944. // Haven't recognized std::initializer_list yet, maybe this is it.
  7945. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  7946. if (TemplateClass->getIdentifier() !=
  7947. &PP.getIdentifierTable().get("initializer_list") ||
  7948. !getStdNamespace()->InEnclosingNamespaceSetOf(
  7949. TemplateClass->getDeclContext()))
  7950. return false;
  7951. // This is a template called std::initializer_list, but is it the right
  7952. // template?
  7953. TemplateParameterList *Params = Template->getTemplateParameters();
  7954. if (Params->getMinRequiredArguments() != 1)
  7955. return false;
  7956. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  7957. return false;
  7958. // It's the right template.
  7959. StdInitializerList = Template;
  7960. }
  7961. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  7962. return false;
  7963. // This is an instance of std::initializer_list. Find the argument type.
  7964. if (Element)
  7965. *Element = Arguments[0].getAsType();
  7966. return true;
  7967. }
  7968. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  7969. NamespaceDecl *Std = S.getStdNamespace();
  7970. if (!Std) {
  7971. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  7972. return nullptr;
  7973. }
  7974. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  7975. Loc, Sema::LookupOrdinaryName);
  7976. if (!S.LookupQualifiedName(Result, Std)) {
  7977. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  7978. return nullptr;
  7979. }
  7980. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  7981. if (!Template) {
  7982. Result.suppressDiagnostics();
  7983. // We found something weird. Complain about the first thing we found.
  7984. NamedDecl *Found = *Result.begin();
  7985. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  7986. return nullptr;
  7987. }
  7988. // We found some template called std::initializer_list. Now verify that it's
  7989. // correct.
  7990. TemplateParameterList *Params = Template->getTemplateParameters();
  7991. if (Params->getMinRequiredArguments() != 1 ||
  7992. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  7993. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  7994. return nullptr;
  7995. }
  7996. return Template;
  7997. }
  7998. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  7999. if (!StdInitializerList) {
  8000. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8001. if (!StdInitializerList)
  8002. return QualType();
  8003. }
  8004. TemplateArgumentListInfo Args(Loc, Loc);
  8005. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8006. Context.getTrivialTypeSourceInfo(Element,
  8007. Loc)));
  8008. return Context.getCanonicalType(
  8009. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8010. }
  8011. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8012. // C++ [dcl.init.list]p2:
  8013. // A constructor is an initializer-list constructor if its first parameter
  8014. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8015. // std::initializer_list<E> for some type E, and either there are no other
  8016. // parameters or else all other parameters have default arguments.
  8017. if (Ctor->getNumParams() < 1 ||
  8018. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8019. return false;
  8020. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8021. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8022. ArgType = RT->getPointeeType().getUnqualifiedType();
  8023. return isStdInitializerList(ArgType, nullptr);
  8024. }
  8025. /// Determine whether a using statement is in a context where it will be
  8026. /// apply in all contexts.
  8027. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8028. switch (CurContext->getDeclKind()) {
  8029. case Decl::TranslationUnit:
  8030. return true;
  8031. case Decl::LinkageSpec:
  8032. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8033. default:
  8034. return false;
  8035. }
  8036. }
  8037. namespace {
  8038. // Callback to only accept typo corrections that are namespaces.
  8039. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  8040. public:
  8041. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8042. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8043. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8044. return false;
  8045. }
  8046. };
  8047. }
  8048. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8049. CXXScopeSpec &SS,
  8050. SourceLocation IdentLoc,
  8051. IdentifierInfo *Ident) {
  8052. R.clear();
  8053. if (TypoCorrection Corrected =
  8054. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
  8055. llvm::make_unique<NamespaceValidatorCCC>(),
  8056. Sema::CTK_ErrorRecovery)) {
  8057. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8058. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8059. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8060. Ident->getName().equals(CorrectedStr);
  8061. S.diagnoseTypo(Corrected,
  8062. S.PDiag(diag::err_using_directive_member_suggest)
  8063. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8064. S.PDiag(diag::note_namespace_defined_here));
  8065. } else {
  8066. S.diagnoseTypo(Corrected,
  8067. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8068. S.PDiag(diag::note_namespace_defined_here));
  8069. }
  8070. R.addDecl(Corrected.getFoundDecl());
  8071. return true;
  8072. }
  8073. return false;
  8074. }
  8075. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8076. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8077. SourceLocation IdentLoc,
  8078. IdentifierInfo *NamespcName,
  8079. const ParsedAttributesView &AttrList) {
  8080. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8081. assert(NamespcName && "Invalid NamespcName.");
  8082. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8083. // This can only happen along a recovery path.
  8084. while (S->isTemplateParamScope())
  8085. S = S->getParent();
  8086. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8087. UsingDirectiveDecl *UDir = nullptr;
  8088. NestedNameSpecifier *Qualifier = nullptr;
  8089. if (SS.isSet())
  8090. Qualifier = SS.getScopeRep();
  8091. // Lookup namespace name.
  8092. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8093. LookupParsedName(R, S, &SS);
  8094. if (R.isAmbiguous())
  8095. return nullptr;
  8096. if (R.empty()) {
  8097. R.clear();
  8098. // Allow "using namespace std;" or "using namespace ::std;" even if
  8099. // "std" hasn't been defined yet, for GCC compatibility.
  8100. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8101. NamespcName->isStr("std")) {
  8102. Diag(IdentLoc, diag::ext_using_undefined_std);
  8103. R.addDecl(getOrCreateStdNamespace());
  8104. R.resolveKind();
  8105. }
  8106. // Otherwise, attempt typo correction.
  8107. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8108. }
  8109. if (!R.empty()) {
  8110. NamedDecl *Named = R.getRepresentativeDecl();
  8111. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8112. assert(NS && "expected namespace decl");
  8113. // The use of a nested name specifier may trigger deprecation warnings.
  8114. DiagnoseUseOfDecl(Named, IdentLoc);
  8115. // C++ [namespace.udir]p1:
  8116. // A using-directive specifies that the names in the nominated
  8117. // namespace can be used in the scope in which the
  8118. // using-directive appears after the using-directive. During
  8119. // unqualified name lookup (3.4.1), the names appear as if they
  8120. // were declared in the nearest enclosing namespace which
  8121. // contains both the using-directive and the nominated
  8122. // namespace. [Note: in this context, "contains" means "contains
  8123. // directly or indirectly". ]
  8124. // Find enclosing context containing both using-directive and
  8125. // nominated namespace.
  8126. DeclContext *CommonAncestor = NS;
  8127. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8128. CommonAncestor = CommonAncestor->getParent();
  8129. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8130. SS.getWithLocInContext(Context),
  8131. IdentLoc, Named, CommonAncestor);
  8132. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8133. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8134. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8135. }
  8136. PushUsingDirective(S, UDir);
  8137. } else {
  8138. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8139. }
  8140. if (UDir)
  8141. ProcessDeclAttributeList(S, UDir, AttrList);
  8142. return UDir;
  8143. }
  8144. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8145. // If the scope has an associated entity and the using directive is at
  8146. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8147. // its lookup structure so qualified name lookup can find it.
  8148. DeclContext *Ctx = S->getEntity();
  8149. if (Ctx && !Ctx->isFunctionOrMethod())
  8150. Ctx->addDecl(UDir);
  8151. else
  8152. // Otherwise, it is at block scope. The using-directives will affect lookup
  8153. // only to the end of the scope.
  8154. S->PushUsingDirective(UDir);
  8155. }
  8156. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8157. SourceLocation UsingLoc,
  8158. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8159. UnqualifiedId &Name,
  8160. SourceLocation EllipsisLoc,
  8161. const ParsedAttributesView &AttrList) {
  8162. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8163. if (SS.isEmpty()) {
  8164. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8165. return nullptr;
  8166. }
  8167. switch (Name.getKind()) {
  8168. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8169. case UnqualifiedIdKind::IK_Identifier:
  8170. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8171. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8172. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8173. break;
  8174. case UnqualifiedIdKind::IK_ConstructorName:
  8175. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8176. // C++11 inheriting constructors.
  8177. Diag(Name.getBeginLoc(),
  8178. getLangOpts().CPlusPlus11
  8179. ? diag::warn_cxx98_compat_using_decl_constructor
  8180. : diag::err_using_decl_constructor)
  8181. << SS.getRange();
  8182. if (getLangOpts().CPlusPlus11) break;
  8183. return nullptr;
  8184. case UnqualifiedIdKind::IK_DestructorName:
  8185. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8186. return nullptr;
  8187. case UnqualifiedIdKind::IK_TemplateId:
  8188. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8189. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8190. return nullptr;
  8191. case UnqualifiedIdKind::IK_DeductionGuideName:
  8192. llvm_unreachable("cannot parse qualified deduction guide name");
  8193. }
  8194. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8195. DeclarationName TargetName = TargetNameInfo.getName();
  8196. if (!TargetName)
  8197. return nullptr;
  8198. // Warn about access declarations.
  8199. if (UsingLoc.isInvalid()) {
  8200. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8201. ? diag::err_access_decl
  8202. : diag::warn_access_decl_deprecated)
  8203. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8204. }
  8205. if (EllipsisLoc.isInvalid()) {
  8206. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8207. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8208. return nullptr;
  8209. } else {
  8210. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8211. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8212. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8213. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8214. EllipsisLoc = SourceLocation();
  8215. }
  8216. }
  8217. NamedDecl *UD =
  8218. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8219. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8220. /*IsInstantiation*/false);
  8221. if (UD)
  8222. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8223. return UD;
  8224. }
  8225. /// Determine whether a using declaration considers the given
  8226. /// declarations as "equivalent", e.g., if they are redeclarations of
  8227. /// the same entity or are both typedefs of the same type.
  8228. static bool
  8229. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8230. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8231. return true;
  8232. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8233. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8234. return Context.hasSameType(TD1->getUnderlyingType(),
  8235. TD2->getUnderlyingType());
  8236. return false;
  8237. }
  8238. /// Determines whether to create a using shadow decl for a particular
  8239. /// decl, given the set of decls existing prior to this using lookup.
  8240. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8241. const LookupResult &Previous,
  8242. UsingShadowDecl *&PrevShadow) {
  8243. // Diagnose finding a decl which is not from a base class of the
  8244. // current class. We do this now because there are cases where this
  8245. // function will silently decide not to build a shadow decl, which
  8246. // will pre-empt further diagnostics.
  8247. //
  8248. // We don't need to do this in C++11 because we do the check once on
  8249. // the qualifier.
  8250. //
  8251. // FIXME: diagnose the following if we care enough:
  8252. // struct A { int foo; };
  8253. // struct B : A { using A::foo; };
  8254. // template <class T> struct C : A {};
  8255. // template <class T> struct D : C<T> { using B::foo; } // <---
  8256. // This is invalid (during instantiation) in C++03 because B::foo
  8257. // resolves to the using decl in B, which is not a base class of D<T>.
  8258. // We can't diagnose it immediately because C<T> is an unknown
  8259. // specialization. The UsingShadowDecl in D<T> then points directly
  8260. // to A::foo, which will look well-formed when we instantiate.
  8261. // The right solution is to not collapse the shadow-decl chain.
  8262. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8263. DeclContext *OrigDC = Orig->getDeclContext();
  8264. // Handle enums and anonymous structs.
  8265. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8266. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8267. while (OrigRec->isAnonymousStructOrUnion())
  8268. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8269. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8270. if (OrigDC == CurContext) {
  8271. Diag(Using->getLocation(),
  8272. diag::err_using_decl_nested_name_specifier_is_current_class)
  8273. << Using->getQualifierLoc().getSourceRange();
  8274. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8275. Using->setInvalidDecl();
  8276. return true;
  8277. }
  8278. Diag(Using->getQualifierLoc().getBeginLoc(),
  8279. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8280. << Using->getQualifier()
  8281. << cast<CXXRecordDecl>(CurContext)
  8282. << Using->getQualifierLoc().getSourceRange();
  8283. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8284. Using->setInvalidDecl();
  8285. return true;
  8286. }
  8287. }
  8288. if (Previous.empty()) return false;
  8289. NamedDecl *Target = Orig;
  8290. if (isa<UsingShadowDecl>(Target))
  8291. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8292. // If the target happens to be one of the previous declarations, we
  8293. // don't have a conflict.
  8294. //
  8295. // FIXME: but we might be increasing its access, in which case we
  8296. // should redeclare it.
  8297. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8298. bool FoundEquivalentDecl = false;
  8299. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8300. I != E; ++I) {
  8301. NamedDecl *D = (*I)->getUnderlyingDecl();
  8302. // We can have UsingDecls in our Previous results because we use the same
  8303. // LookupResult for checking whether the UsingDecl itself is a valid
  8304. // redeclaration.
  8305. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8306. continue;
  8307. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8308. // C++ [class.mem]p19:
  8309. // If T is the name of a class, then [every named member other than
  8310. // a non-static data member] shall have a name different from T
  8311. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8312. !isa<IndirectFieldDecl>(Target) &&
  8313. !isa<UnresolvedUsingValueDecl>(Target) &&
  8314. DiagnoseClassNameShadow(
  8315. CurContext,
  8316. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8317. return true;
  8318. }
  8319. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8320. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8321. PrevShadow = Shadow;
  8322. FoundEquivalentDecl = true;
  8323. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8324. // We don't conflict with an existing using shadow decl of an equivalent
  8325. // declaration, but we're not a redeclaration of it.
  8326. FoundEquivalentDecl = true;
  8327. }
  8328. if (isVisible(D))
  8329. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8330. }
  8331. if (FoundEquivalentDecl)
  8332. return false;
  8333. if (FunctionDecl *FD = Target->getAsFunction()) {
  8334. NamedDecl *OldDecl = nullptr;
  8335. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8336. /*IsForUsingDecl*/ true)) {
  8337. case Ovl_Overload:
  8338. return false;
  8339. case Ovl_NonFunction:
  8340. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8341. break;
  8342. // We found a decl with the exact signature.
  8343. case Ovl_Match:
  8344. // If we're in a record, we want to hide the target, so we
  8345. // return true (without a diagnostic) to tell the caller not to
  8346. // build a shadow decl.
  8347. if (CurContext->isRecord())
  8348. return true;
  8349. // If we're not in a record, this is an error.
  8350. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8351. break;
  8352. }
  8353. Diag(Target->getLocation(), diag::note_using_decl_target);
  8354. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8355. Using->setInvalidDecl();
  8356. return true;
  8357. }
  8358. // Target is not a function.
  8359. if (isa<TagDecl>(Target)) {
  8360. // No conflict between a tag and a non-tag.
  8361. if (!Tag) return false;
  8362. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8363. Diag(Target->getLocation(), diag::note_using_decl_target);
  8364. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8365. Using->setInvalidDecl();
  8366. return true;
  8367. }
  8368. // No conflict between a tag and a non-tag.
  8369. if (!NonTag) return false;
  8370. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8371. Diag(Target->getLocation(), diag::note_using_decl_target);
  8372. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8373. Using->setInvalidDecl();
  8374. return true;
  8375. }
  8376. /// Determine whether a direct base class is a virtual base class.
  8377. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8378. if (!Derived->getNumVBases())
  8379. return false;
  8380. for (auto &B : Derived->bases())
  8381. if (B.getType()->getAsCXXRecordDecl() == Base)
  8382. return B.isVirtual();
  8383. llvm_unreachable("not a direct base class");
  8384. }
  8385. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8386. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8387. UsingDecl *UD,
  8388. NamedDecl *Orig,
  8389. UsingShadowDecl *PrevDecl) {
  8390. // If we resolved to another shadow declaration, just coalesce them.
  8391. NamedDecl *Target = Orig;
  8392. if (isa<UsingShadowDecl>(Target)) {
  8393. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8394. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8395. }
  8396. NamedDecl *NonTemplateTarget = Target;
  8397. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8398. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8399. UsingShadowDecl *Shadow;
  8400. if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8401. bool IsVirtualBase =
  8402. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8403. UD->getQualifier()->getAsRecordDecl());
  8404. Shadow = ConstructorUsingShadowDecl::Create(
  8405. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8406. } else {
  8407. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8408. Target);
  8409. }
  8410. UD->addShadowDecl(Shadow);
  8411. Shadow->setAccess(UD->getAccess());
  8412. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8413. Shadow->setInvalidDecl();
  8414. Shadow->setPreviousDecl(PrevDecl);
  8415. if (S)
  8416. PushOnScopeChains(Shadow, S);
  8417. else
  8418. CurContext->addDecl(Shadow);
  8419. return Shadow;
  8420. }
  8421. /// Hides a using shadow declaration. This is required by the current
  8422. /// using-decl implementation when a resolvable using declaration in a
  8423. /// class is followed by a declaration which would hide or override
  8424. /// one or more of the using decl's targets; for example:
  8425. ///
  8426. /// struct Base { void foo(int); };
  8427. /// struct Derived : Base {
  8428. /// using Base::foo;
  8429. /// void foo(int);
  8430. /// };
  8431. ///
  8432. /// The governing language is C++03 [namespace.udecl]p12:
  8433. ///
  8434. /// When a using-declaration brings names from a base class into a
  8435. /// derived class scope, member functions in the derived class
  8436. /// override and/or hide member functions with the same name and
  8437. /// parameter types in a base class (rather than conflicting).
  8438. ///
  8439. /// There are two ways to implement this:
  8440. /// (1) optimistically create shadow decls when they're not hidden
  8441. /// by existing declarations, or
  8442. /// (2) don't create any shadow decls (or at least don't make them
  8443. /// visible) until we've fully parsed/instantiated the class.
  8444. /// The problem with (1) is that we might have to retroactively remove
  8445. /// a shadow decl, which requires several O(n) operations because the
  8446. /// decl structures are (very reasonably) not designed for removal.
  8447. /// (2) avoids this but is very fiddly and phase-dependent.
  8448. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8449. if (Shadow->getDeclName().getNameKind() ==
  8450. DeclarationName::CXXConversionFunctionName)
  8451. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8452. // Remove it from the DeclContext...
  8453. Shadow->getDeclContext()->removeDecl(Shadow);
  8454. // ...and the scope, if applicable...
  8455. if (S) {
  8456. S->RemoveDecl(Shadow);
  8457. IdResolver.RemoveDecl(Shadow);
  8458. }
  8459. // ...and the using decl.
  8460. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8461. // TODO: complain somehow if Shadow was used. It shouldn't
  8462. // be possible for this to happen, because...?
  8463. }
  8464. /// Find the base specifier for a base class with the given type.
  8465. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8466. QualType DesiredBase,
  8467. bool &AnyDependentBases) {
  8468. // Check whether the named type is a direct base class.
  8469. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  8470. for (auto &Base : Derived->bases()) {
  8471. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8472. if (CanonicalDesiredBase == BaseType)
  8473. return &Base;
  8474. if (BaseType->isDependentType())
  8475. AnyDependentBases = true;
  8476. }
  8477. return nullptr;
  8478. }
  8479. namespace {
  8480. class UsingValidatorCCC : public CorrectionCandidateCallback {
  8481. public:
  8482. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8483. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8484. : HasTypenameKeyword(HasTypenameKeyword),
  8485. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8486. RequireMemberOf(RequireMemberOf) {}
  8487. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8488. NamedDecl *ND = Candidate.getCorrectionDecl();
  8489. // Keywords are not valid here.
  8490. if (!ND || isa<NamespaceDecl>(ND))
  8491. return false;
  8492. // Completely unqualified names are invalid for a 'using' declaration.
  8493. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8494. return false;
  8495. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8496. // reject.
  8497. if (RequireMemberOf) {
  8498. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8499. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8500. // No-one ever wants a using-declaration to name an injected-class-name
  8501. // of a base class, unless they're declaring an inheriting constructor.
  8502. ASTContext &Ctx = ND->getASTContext();
  8503. if (!Ctx.getLangOpts().CPlusPlus11)
  8504. return false;
  8505. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8506. // Check that the injected-class-name is named as a member of its own
  8507. // type; we don't want to suggest 'using Derived::Base;', since that
  8508. // means something else.
  8509. NestedNameSpecifier *Specifier =
  8510. Candidate.WillReplaceSpecifier()
  8511. ? Candidate.getCorrectionSpecifier()
  8512. : OldNNS;
  8513. if (!Specifier->getAsType() ||
  8514. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8515. return false;
  8516. // Check that this inheriting constructor declaration actually names a
  8517. // direct base class of the current class.
  8518. bool AnyDependentBases = false;
  8519. if (!findDirectBaseWithType(RequireMemberOf,
  8520. Ctx.getRecordType(FoundRecord),
  8521. AnyDependentBases) &&
  8522. !AnyDependentBases)
  8523. return false;
  8524. } else {
  8525. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8526. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8527. return false;
  8528. // FIXME: Check that the base class member is accessible?
  8529. }
  8530. } else {
  8531. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8532. if (FoundRecord && FoundRecord->isInjectedClassName())
  8533. return false;
  8534. }
  8535. if (isa<TypeDecl>(ND))
  8536. return HasTypenameKeyword || !IsInstantiation;
  8537. return !HasTypenameKeyword;
  8538. }
  8539. private:
  8540. bool HasTypenameKeyword;
  8541. bool IsInstantiation;
  8542. NestedNameSpecifier *OldNNS;
  8543. CXXRecordDecl *RequireMemberOf;
  8544. };
  8545. } // end anonymous namespace
  8546. /// Builds a using declaration.
  8547. ///
  8548. /// \param IsInstantiation - Whether this call arises from an
  8549. /// instantiation of an unresolved using declaration. We treat
  8550. /// the lookup differently for these declarations.
  8551. NamedDecl *Sema::BuildUsingDeclaration(
  8552. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8553. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8554. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8555. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8556. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8557. SourceLocation IdentLoc = NameInfo.getLoc();
  8558. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8559. // FIXME: We ignore attributes for now.
  8560. // For an inheriting constructor declaration, the name of the using
  8561. // declaration is the name of a constructor in this class, not in the
  8562. // base class.
  8563. DeclarationNameInfo UsingName = NameInfo;
  8564. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8565. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8566. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8567. Context.getCanonicalType(Context.getRecordType(RD))));
  8568. // Do the redeclaration lookup in the current scope.
  8569. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8570. ForVisibleRedeclaration);
  8571. Previous.setHideTags(false);
  8572. if (S) {
  8573. LookupName(Previous, S);
  8574. // It is really dumb that we have to do this.
  8575. LookupResult::Filter F = Previous.makeFilter();
  8576. while (F.hasNext()) {
  8577. NamedDecl *D = F.next();
  8578. if (!isDeclInScope(D, CurContext, S))
  8579. F.erase();
  8580. // If we found a local extern declaration that's not ordinarily visible,
  8581. // and this declaration is being added to a non-block scope, ignore it.
  8582. // We're only checking for scope conflicts here, not also for violations
  8583. // of the linkage rules.
  8584. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8585. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8586. F.erase();
  8587. }
  8588. F.done();
  8589. } else {
  8590. assert(IsInstantiation && "no scope in non-instantiation");
  8591. if (CurContext->isRecord())
  8592. LookupQualifiedName(Previous, CurContext);
  8593. else {
  8594. // No redeclaration check is needed here; in non-member contexts we
  8595. // diagnosed all possible conflicts with other using-declarations when
  8596. // building the template:
  8597. //
  8598. // For a dependent non-type using declaration, the only valid case is
  8599. // if we instantiate to a single enumerator. We check for conflicts
  8600. // between shadow declarations we introduce, and we check in the template
  8601. // definition for conflicts between a non-type using declaration and any
  8602. // other declaration, which together covers all cases.
  8603. //
  8604. // A dependent typename using declaration will never successfully
  8605. // instantiate, since it will always name a class member, so we reject
  8606. // that in the template definition.
  8607. }
  8608. }
  8609. // Check for invalid redeclarations.
  8610. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8611. SS, IdentLoc, Previous))
  8612. return nullptr;
  8613. // Check for bad qualifiers.
  8614. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8615. IdentLoc))
  8616. return nullptr;
  8617. DeclContext *LookupContext = computeDeclContext(SS);
  8618. NamedDecl *D;
  8619. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8620. if (!LookupContext || EllipsisLoc.isValid()) {
  8621. if (HasTypenameKeyword) {
  8622. // FIXME: not all declaration name kinds are legal here
  8623. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8624. UsingLoc, TypenameLoc,
  8625. QualifierLoc,
  8626. IdentLoc, NameInfo.getName(),
  8627. EllipsisLoc);
  8628. } else {
  8629. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8630. QualifierLoc, NameInfo, EllipsisLoc);
  8631. }
  8632. D->setAccess(AS);
  8633. CurContext->addDecl(D);
  8634. return D;
  8635. }
  8636. auto Build = [&](bool Invalid) {
  8637. UsingDecl *UD =
  8638. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8639. UsingName, HasTypenameKeyword);
  8640. UD->setAccess(AS);
  8641. CurContext->addDecl(UD);
  8642. UD->setInvalidDecl(Invalid);
  8643. return UD;
  8644. };
  8645. auto BuildInvalid = [&]{ return Build(true); };
  8646. auto BuildValid = [&]{ return Build(false); };
  8647. if (RequireCompleteDeclContext(SS, LookupContext))
  8648. return BuildInvalid();
  8649. // Look up the target name.
  8650. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8651. // Unlike most lookups, we don't always want to hide tag
  8652. // declarations: tag names are visible through the using declaration
  8653. // even if hidden by ordinary names, *except* in a dependent context
  8654. // where it's important for the sanity of two-phase lookup.
  8655. if (!IsInstantiation)
  8656. R.setHideTags(false);
  8657. // For the purposes of this lookup, we have a base object type
  8658. // equal to that of the current context.
  8659. if (CurContext->isRecord()) {
  8660. R.setBaseObjectType(
  8661. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8662. }
  8663. LookupQualifiedName(R, LookupContext);
  8664. // Try to correct typos if possible. If constructor name lookup finds no
  8665. // results, that means the named class has no explicit constructors, and we
  8666. // suppressed declaring implicit ones (probably because it's dependent or
  8667. // invalid).
  8668. if (R.empty() &&
  8669. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8670. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8671. // it will believe that glibc provides a ::gets in cases where it does not,
  8672. // and will try to pull it into namespace std with a using-declaration.
  8673. // Just ignore the using-declaration in that case.
  8674. auto *II = NameInfo.getName().getAsIdentifierInfo();
  8675. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  8676. CurContext->isStdNamespace() &&
  8677. isa<TranslationUnitDecl>(LookupContext) &&
  8678. getSourceManager().isInSystemHeader(UsingLoc))
  8679. return nullptr;
  8680. if (TypoCorrection Corrected = CorrectTypo(
  8681. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  8682. llvm::make_unique<UsingValidatorCCC>(
  8683. HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  8684. dyn_cast<CXXRecordDecl>(CurContext)),
  8685. CTK_ErrorRecovery)) {
  8686. // We reject candidates where DroppedSpecifier == true, hence the
  8687. // literal '0' below.
  8688. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  8689. << NameInfo.getName() << LookupContext << 0
  8690. << SS.getRange());
  8691. // If we picked a correction with no attached Decl we can't do anything
  8692. // useful with it, bail out.
  8693. NamedDecl *ND = Corrected.getCorrectionDecl();
  8694. if (!ND)
  8695. return BuildInvalid();
  8696. // If we corrected to an inheriting constructor, handle it as one.
  8697. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  8698. if (RD && RD->isInjectedClassName()) {
  8699. // The parent of the injected class name is the class itself.
  8700. RD = cast<CXXRecordDecl>(RD->getParent());
  8701. // Fix up the information we'll use to build the using declaration.
  8702. if (Corrected.WillReplaceSpecifier()) {
  8703. NestedNameSpecifierLocBuilder Builder;
  8704. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  8705. QualifierLoc.getSourceRange());
  8706. QualifierLoc = Builder.getWithLocInContext(Context);
  8707. }
  8708. // In this case, the name we introduce is the name of a derived class
  8709. // constructor.
  8710. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  8711. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8712. Context.getCanonicalType(Context.getRecordType(CurClass))));
  8713. UsingName.setNamedTypeInfo(nullptr);
  8714. for (auto *Ctor : LookupConstructors(RD))
  8715. R.addDecl(Ctor);
  8716. R.resolveKind();
  8717. } else {
  8718. // FIXME: Pick up all the declarations if we found an overloaded
  8719. // function.
  8720. UsingName.setName(ND->getDeclName());
  8721. R.addDecl(ND);
  8722. }
  8723. } else {
  8724. Diag(IdentLoc, diag::err_no_member)
  8725. << NameInfo.getName() << LookupContext << SS.getRange();
  8726. return BuildInvalid();
  8727. }
  8728. }
  8729. if (R.isAmbiguous())
  8730. return BuildInvalid();
  8731. if (HasTypenameKeyword) {
  8732. // If we asked for a typename and got a non-type decl, error out.
  8733. if (!R.getAsSingle<TypeDecl>()) {
  8734. Diag(IdentLoc, diag::err_using_typename_non_type);
  8735. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8736. Diag((*I)->getUnderlyingDecl()->getLocation(),
  8737. diag::note_using_decl_target);
  8738. return BuildInvalid();
  8739. }
  8740. } else {
  8741. // If we asked for a non-typename and we got a type, error out,
  8742. // but only if this is an instantiation of an unresolved using
  8743. // decl. Otherwise just silently find the type name.
  8744. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  8745. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  8746. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  8747. return BuildInvalid();
  8748. }
  8749. }
  8750. // C++14 [namespace.udecl]p6:
  8751. // A using-declaration shall not name a namespace.
  8752. if (R.getAsSingle<NamespaceDecl>()) {
  8753. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  8754. << SS.getRange();
  8755. return BuildInvalid();
  8756. }
  8757. // C++14 [namespace.udecl]p7:
  8758. // A using-declaration shall not name a scoped enumerator.
  8759. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  8760. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  8761. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  8762. << SS.getRange();
  8763. return BuildInvalid();
  8764. }
  8765. }
  8766. UsingDecl *UD = BuildValid();
  8767. // Some additional rules apply to inheriting constructors.
  8768. if (UsingName.getName().getNameKind() ==
  8769. DeclarationName::CXXConstructorName) {
  8770. // Suppress access diagnostics; the access check is instead performed at the
  8771. // point of use for an inheriting constructor.
  8772. R.suppressDiagnostics();
  8773. if (CheckInheritingConstructorUsingDecl(UD))
  8774. return UD;
  8775. }
  8776. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8777. UsingShadowDecl *PrevDecl = nullptr;
  8778. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  8779. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  8780. }
  8781. return UD;
  8782. }
  8783. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  8784. ArrayRef<NamedDecl *> Expansions) {
  8785. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  8786. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  8787. isa<UsingPackDecl>(InstantiatedFrom));
  8788. auto *UPD =
  8789. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  8790. UPD->setAccess(InstantiatedFrom->getAccess());
  8791. CurContext->addDecl(UPD);
  8792. return UPD;
  8793. }
  8794. /// Additional checks for a using declaration referring to a constructor name.
  8795. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  8796. assert(!UD->hasTypename() && "expecting a constructor name");
  8797. const Type *SourceType = UD->getQualifier()->getAsType();
  8798. assert(SourceType &&
  8799. "Using decl naming constructor doesn't have type in scope spec.");
  8800. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  8801. // Check whether the named type is a direct base class.
  8802. bool AnyDependentBases = false;
  8803. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  8804. AnyDependentBases);
  8805. if (!Base && !AnyDependentBases) {
  8806. Diag(UD->getUsingLoc(),
  8807. diag::err_using_decl_constructor_not_in_direct_base)
  8808. << UD->getNameInfo().getSourceRange()
  8809. << QualType(SourceType, 0) << TargetClass;
  8810. UD->setInvalidDecl();
  8811. return true;
  8812. }
  8813. if (Base)
  8814. Base->setInheritConstructors();
  8815. return false;
  8816. }
  8817. /// Checks that the given using declaration is not an invalid
  8818. /// redeclaration. Note that this is checking only for the using decl
  8819. /// itself, not for any ill-formedness among the UsingShadowDecls.
  8820. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  8821. bool HasTypenameKeyword,
  8822. const CXXScopeSpec &SS,
  8823. SourceLocation NameLoc,
  8824. const LookupResult &Prev) {
  8825. NestedNameSpecifier *Qual = SS.getScopeRep();
  8826. // C++03 [namespace.udecl]p8:
  8827. // C++0x [namespace.udecl]p10:
  8828. // A using-declaration is a declaration and can therefore be used
  8829. // repeatedly where (and only where) multiple declarations are
  8830. // allowed.
  8831. //
  8832. // That's in non-member contexts.
  8833. if (!CurContext->getRedeclContext()->isRecord()) {
  8834. // A dependent qualifier outside a class can only ever resolve to an
  8835. // enumeration type. Therefore it conflicts with any other non-type
  8836. // declaration in the same scope.
  8837. // FIXME: How should we check for dependent type-type conflicts at block
  8838. // scope?
  8839. if (Qual->isDependent() && !HasTypenameKeyword) {
  8840. for (auto *D : Prev) {
  8841. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  8842. bool OldCouldBeEnumerator =
  8843. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  8844. Diag(NameLoc,
  8845. OldCouldBeEnumerator ? diag::err_redefinition
  8846. : diag::err_redefinition_different_kind)
  8847. << Prev.getLookupName();
  8848. Diag(D->getLocation(), diag::note_previous_definition);
  8849. return true;
  8850. }
  8851. }
  8852. }
  8853. return false;
  8854. }
  8855. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  8856. NamedDecl *D = *I;
  8857. bool DTypename;
  8858. NestedNameSpecifier *DQual;
  8859. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  8860. DTypename = UD->hasTypename();
  8861. DQual = UD->getQualifier();
  8862. } else if (UnresolvedUsingValueDecl *UD
  8863. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  8864. DTypename = false;
  8865. DQual = UD->getQualifier();
  8866. } else if (UnresolvedUsingTypenameDecl *UD
  8867. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  8868. DTypename = true;
  8869. DQual = UD->getQualifier();
  8870. } else continue;
  8871. // using decls differ if one says 'typename' and the other doesn't.
  8872. // FIXME: non-dependent using decls?
  8873. if (HasTypenameKeyword != DTypename) continue;
  8874. // using decls differ if they name different scopes (but note that
  8875. // template instantiation can cause this check to trigger when it
  8876. // didn't before instantiation).
  8877. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  8878. Context.getCanonicalNestedNameSpecifier(DQual))
  8879. continue;
  8880. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  8881. Diag(D->getLocation(), diag::note_using_decl) << 1;
  8882. return true;
  8883. }
  8884. return false;
  8885. }
  8886. /// Checks that the given nested-name qualifier used in a using decl
  8887. /// in the current context is appropriately related to the current
  8888. /// scope. If an error is found, diagnoses it and returns true.
  8889. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  8890. bool HasTypename,
  8891. const CXXScopeSpec &SS,
  8892. const DeclarationNameInfo &NameInfo,
  8893. SourceLocation NameLoc) {
  8894. DeclContext *NamedContext = computeDeclContext(SS);
  8895. if (!CurContext->isRecord()) {
  8896. // C++03 [namespace.udecl]p3:
  8897. // C++0x [namespace.udecl]p8:
  8898. // A using-declaration for a class member shall be a member-declaration.
  8899. // If we weren't able to compute a valid scope, it might validly be a
  8900. // dependent class scope or a dependent enumeration unscoped scope. If
  8901. // we have a 'typename' keyword, the scope must resolve to a class type.
  8902. if ((HasTypename && !NamedContext) ||
  8903. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  8904. auto *RD = NamedContext
  8905. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  8906. : nullptr;
  8907. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  8908. RD = nullptr;
  8909. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  8910. << SS.getRange();
  8911. // If we have a complete, non-dependent source type, try to suggest a
  8912. // way to get the same effect.
  8913. if (!RD)
  8914. return true;
  8915. // Find what this using-declaration was referring to.
  8916. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8917. R.setHideTags(false);
  8918. R.suppressDiagnostics();
  8919. LookupQualifiedName(R, RD);
  8920. if (R.getAsSingle<TypeDecl>()) {
  8921. if (getLangOpts().CPlusPlus11) {
  8922. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  8923. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  8924. << 0 // alias declaration
  8925. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  8926. NameInfo.getName().getAsString() +
  8927. " = ");
  8928. } else {
  8929. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  8930. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  8931. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  8932. << 1 // typedef declaration
  8933. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  8934. << FixItHint::CreateInsertion(
  8935. InsertLoc, " " + NameInfo.getName().getAsString());
  8936. }
  8937. } else if (R.getAsSingle<VarDecl>()) {
  8938. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8939. // repeating the type of the static data member here.
  8940. FixItHint FixIt;
  8941. if (getLangOpts().CPlusPlus11) {
  8942. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  8943. FixIt = FixItHint::CreateReplacement(
  8944. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  8945. }
  8946. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  8947. << 2 // reference declaration
  8948. << FixIt;
  8949. } else if (R.getAsSingle<EnumConstantDecl>()) {
  8950. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8951. // repeating the type of the enumeration here, and we can't do so if
  8952. // the type is anonymous.
  8953. FixItHint FixIt;
  8954. if (getLangOpts().CPlusPlus11) {
  8955. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  8956. FixIt = FixItHint::CreateReplacement(
  8957. UsingLoc,
  8958. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  8959. }
  8960. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  8961. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  8962. << FixIt;
  8963. }
  8964. return true;
  8965. }
  8966. // Otherwise, this might be valid.
  8967. return false;
  8968. }
  8969. // The current scope is a record.
  8970. // If the named context is dependent, we can't decide much.
  8971. if (!NamedContext) {
  8972. // FIXME: in C++0x, we can diagnose if we can prove that the
  8973. // nested-name-specifier does not refer to a base class, which is
  8974. // still possible in some cases.
  8975. // Otherwise we have to conservatively report that things might be
  8976. // okay.
  8977. return false;
  8978. }
  8979. if (!NamedContext->isRecord()) {
  8980. // Ideally this would point at the last name in the specifier,
  8981. // but we don't have that level of source info.
  8982. Diag(SS.getRange().getBegin(),
  8983. diag::err_using_decl_nested_name_specifier_is_not_class)
  8984. << SS.getScopeRep() << SS.getRange();
  8985. return true;
  8986. }
  8987. if (!NamedContext->isDependentContext() &&
  8988. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  8989. return true;
  8990. if (getLangOpts().CPlusPlus11) {
  8991. // C++11 [namespace.udecl]p3:
  8992. // In a using-declaration used as a member-declaration, the
  8993. // nested-name-specifier shall name a base class of the class
  8994. // being defined.
  8995. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  8996. cast<CXXRecordDecl>(NamedContext))) {
  8997. if (CurContext == NamedContext) {
  8998. Diag(NameLoc,
  8999. diag::err_using_decl_nested_name_specifier_is_current_class)
  9000. << SS.getRange();
  9001. return true;
  9002. }
  9003. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9004. Diag(SS.getRange().getBegin(),
  9005. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9006. << SS.getScopeRep()
  9007. << cast<CXXRecordDecl>(CurContext)
  9008. << SS.getRange();
  9009. }
  9010. return true;
  9011. }
  9012. return false;
  9013. }
  9014. // C++03 [namespace.udecl]p4:
  9015. // A using-declaration used as a member-declaration shall refer
  9016. // to a member of a base class of the class being defined [etc.].
  9017. // Salient point: SS doesn't have to name a base class as long as
  9018. // lookup only finds members from base classes. Therefore we can
  9019. // diagnose here only if we can prove that that can't happen,
  9020. // i.e. if the class hierarchies provably don't intersect.
  9021. // TODO: it would be nice if "definitely valid" results were cached
  9022. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9023. // need to be repeated.
  9024. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9025. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9026. Bases.insert(Base);
  9027. return true;
  9028. };
  9029. // Collect all bases. Return false if we find a dependent base.
  9030. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9031. return false;
  9032. // Returns true if the base is dependent or is one of the accumulated base
  9033. // classes.
  9034. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9035. return !Bases.count(Base);
  9036. };
  9037. // Return false if the class has a dependent base or if it or one
  9038. // of its bases is present in the base set of the current context.
  9039. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9040. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9041. return false;
  9042. Diag(SS.getRange().getBegin(),
  9043. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9044. << SS.getScopeRep()
  9045. << cast<CXXRecordDecl>(CurContext)
  9046. << SS.getRange();
  9047. return true;
  9048. }
  9049. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9050. MultiTemplateParamsArg TemplateParamLists,
  9051. SourceLocation UsingLoc, UnqualifiedId &Name,
  9052. const ParsedAttributesView &AttrList,
  9053. TypeResult Type, Decl *DeclFromDeclSpec) {
  9054. // Skip up to the relevant declaration scope.
  9055. while (S->isTemplateParamScope())
  9056. S = S->getParent();
  9057. assert((S->getFlags() & Scope::DeclScope) &&
  9058. "got alias-declaration outside of declaration scope");
  9059. if (Type.isInvalid())
  9060. return nullptr;
  9061. bool Invalid = false;
  9062. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9063. TypeSourceInfo *TInfo = nullptr;
  9064. GetTypeFromParser(Type.get(), &TInfo);
  9065. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9066. return nullptr;
  9067. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9068. UPPC_DeclarationType)) {
  9069. Invalid = true;
  9070. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9071. TInfo->getTypeLoc().getBeginLoc());
  9072. }
  9073. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9074. TemplateParamLists.size()
  9075. ? forRedeclarationInCurContext()
  9076. : ForVisibleRedeclaration);
  9077. LookupName(Previous, S);
  9078. // Warn about shadowing the name of a template parameter.
  9079. if (Previous.isSingleResult() &&
  9080. Previous.getFoundDecl()->isTemplateParameter()) {
  9081. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9082. Previous.clear();
  9083. }
  9084. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9085. "name in alias declaration must be an identifier");
  9086. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9087. Name.StartLocation,
  9088. Name.Identifier, TInfo);
  9089. NewTD->setAccess(AS);
  9090. if (Invalid)
  9091. NewTD->setInvalidDecl();
  9092. ProcessDeclAttributeList(S, NewTD, AttrList);
  9093. AddPragmaAttributes(S, NewTD);
  9094. CheckTypedefForVariablyModifiedType(S, NewTD);
  9095. Invalid |= NewTD->isInvalidDecl();
  9096. bool Redeclaration = false;
  9097. NamedDecl *NewND;
  9098. if (TemplateParamLists.size()) {
  9099. TypeAliasTemplateDecl *OldDecl = nullptr;
  9100. TemplateParameterList *OldTemplateParams = nullptr;
  9101. if (TemplateParamLists.size() != 1) {
  9102. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9103. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9104. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9105. }
  9106. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9107. // Check that we can declare a template here.
  9108. if (CheckTemplateDeclScope(S, TemplateParams))
  9109. return nullptr;
  9110. // Only consider previous declarations in the same scope.
  9111. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9112. /*ExplicitInstantiationOrSpecialization*/false);
  9113. if (!Previous.empty()) {
  9114. Redeclaration = true;
  9115. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9116. if (!OldDecl && !Invalid) {
  9117. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9118. << Name.Identifier;
  9119. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9120. if (OldD->getLocation().isValid())
  9121. Diag(OldD->getLocation(), diag::note_previous_definition);
  9122. Invalid = true;
  9123. }
  9124. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9125. if (TemplateParameterListsAreEqual(TemplateParams,
  9126. OldDecl->getTemplateParameters(),
  9127. /*Complain=*/true,
  9128. TPL_TemplateMatch))
  9129. OldTemplateParams =
  9130. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9131. else
  9132. Invalid = true;
  9133. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9134. if (!Invalid &&
  9135. !Context.hasSameType(OldTD->getUnderlyingType(),
  9136. NewTD->getUnderlyingType())) {
  9137. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9138. // but we can't reasonably accept it.
  9139. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9140. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9141. if (OldTD->getLocation().isValid())
  9142. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9143. Invalid = true;
  9144. }
  9145. }
  9146. }
  9147. // Merge any previous default template arguments into our parameters,
  9148. // and check the parameter list.
  9149. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9150. TPC_TypeAliasTemplate))
  9151. return nullptr;
  9152. TypeAliasTemplateDecl *NewDecl =
  9153. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9154. Name.Identifier, TemplateParams,
  9155. NewTD);
  9156. NewTD->setDescribedAliasTemplate(NewDecl);
  9157. NewDecl->setAccess(AS);
  9158. if (Invalid)
  9159. NewDecl->setInvalidDecl();
  9160. else if (OldDecl) {
  9161. NewDecl->setPreviousDecl(OldDecl);
  9162. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9163. }
  9164. NewND = NewDecl;
  9165. } else {
  9166. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9167. setTagNameForLinkagePurposes(TD, NewTD);
  9168. handleTagNumbering(TD, S);
  9169. }
  9170. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9171. NewND = NewTD;
  9172. }
  9173. PushOnScopeChains(NewND, S);
  9174. ActOnDocumentableDecl(NewND);
  9175. return NewND;
  9176. }
  9177. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9178. SourceLocation AliasLoc,
  9179. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9180. SourceLocation IdentLoc,
  9181. IdentifierInfo *Ident) {
  9182. // Lookup the namespace name.
  9183. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9184. LookupParsedName(R, S, &SS);
  9185. if (R.isAmbiguous())
  9186. return nullptr;
  9187. if (R.empty()) {
  9188. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9189. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9190. return nullptr;
  9191. }
  9192. }
  9193. assert(!R.isAmbiguous() && !R.empty());
  9194. NamedDecl *ND = R.getRepresentativeDecl();
  9195. // Check if we have a previous declaration with the same name.
  9196. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9197. ForVisibleRedeclaration);
  9198. LookupName(PrevR, S);
  9199. // Check we're not shadowing a template parameter.
  9200. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9201. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9202. PrevR.clear();
  9203. }
  9204. // Filter out any other lookup result from an enclosing scope.
  9205. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9206. /*AllowInlineNamespace*/false);
  9207. // Find the previous declaration and check that we can redeclare it.
  9208. NamespaceAliasDecl *Prev = nullptr;
  9209. if (PrevR.isSingleResult()) {
  9210. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9211. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9212. // We already have an alias with the same name that points to the same
  9213. // namespace; check that it matches.
  9214. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9215. Prev = AD;
  9216. } else if (isVisible(PrevDecl)) {
  9217. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9218. << Alias;
  9219. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9220. << AD->getNamespace();
  9221. return nullptr;
  9222. }
  9223. } else if (isVisible(PrevDecl)) {
  9224. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9225. ? diag::err_redefinition
  9226. : diag::err_redefinition_different_kind;
  9227. Diag(AliasLoc, DiagID) << Alias;
  9228. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9229. return nullptr;
  9230. }
  9231. }
  9232. // The use of a nested name specifier may trigger deprecation warnings.
  9233. DiagnoseUseOfDecl(ND, IdentLoc);
  9234. NamespaceAliasDecl *AliasDecl =
  9235. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9236. Alias, SS.getWithLocInContext(Context),
  9237. IdentLoc, ND);
  9238. if (Prev)
  9239. AliasDecl->setPreviousDecl(Prev);
  9240. PushOnScopeChains(AliasDecl, S);
  9241. return AliasDecl;
  9242. }
  9243. namespace {
  9244. struct SpecialMemberExceptionSpecInfo
  9245. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9246. SourceLocation Loc;
  9247. Sema::ImplicitExceptionSpecification ExceptSpec;
  9248. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9249. Sema::CXXSpecialMember CSM,
  9250. Sema::InheritedConstructorInfo *ICI,
  9251. SourceLocation Loc)
  9252. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9253. bool visitBase(CXXBaseSpecifier *Base);
  9254. bool visitField(FieldDecl *FD);
  9255. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9256. unsigned Quals);
  9257. void visitSubobjectCall(Subobject Subobj,
  9258. Sema::SpecialMemberOverloadResult SMOR);
  9259. };
  9260. }
  9261. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9262. auto *RT = Base->getType()->getAs<RecordType>();
  9263. if (!RT)
  9264. return false;
  9265. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9266. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9267. if (auto *BaseCtor = SMOR.getMethod()) {
  9268. visitSubobjectCall(Base, BaseCtor);
  9269. return false;
  9270. }
  9271. visitClassSubobject(BaseClass, Base, 0);
  9272. return false;
  9273. }
  9274. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9275. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9276. Expr *E = FD->getInClassInitializer();
  9277. if (!E)
  9278. // FIXME: It's a little wasteful to build and throw away a
  9279. // CXXDefaultInitExpr here.
  9280. // FIXME: We should have a single context note pointing at Loc, and
  9281. // this location should be MD->getLocation() instead, since that's
  9282. // the location where we actually use the default init expression.
  9283. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9284. if (E)
  9285. ExceptSpec.CalledExpr(E);
  9286. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9287. ->getAs<RecordType>()) {
  9288. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9289. FD->getType().getCVRQualifiers());
  9290. }
  9291. return false;
  9292. }
  9293. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9294. Subobject Subobj,
  9295. unsigned Quals) {
  9296. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9297. bool IsMutable = Field && Field->isMutable();
  9298. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9299. }
  9300. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9301. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9302. // Note, if lookup fails, it doesn't matter what exception specification we
  9303. // choose because the special member will be deleted.
  9304. if (CXXMethodDecl *MD = SMOR.getMethod())
  9305. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9306. }
  9307. namespace {
  9308. /// RAII object to register a special member as being currently declared.
  9309. struct ComputingExceptionSpec {
  9310. Sema &S;
  9311. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9312. : S(S) {
  9313. Sema::CodeSynthesisContext Ctx;
  9314. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9315. Ctx.PointOfInstantiation = Loc;
  9316. Ctx.Entity = MD;
  9317. S.pushCodeSynthesisContext(Ctx);
  9318. }
  9319. ~ComputingExceptionSpec() {
  9320. S.popCodeSynthesisContext();
  9321. }
  9322. };
  9323. }
  9324. static Sema::ImplicitExceptionSpecification
  9325. ComputeDefaultedSpecialMemberExceptionSpec(
  9326. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9327. Sema::InheritedConstructorInfo *ICI) {
  9328. ComputingExceptionSpec CES(S, MD, Loc);
  9329. CXXRecordDecl *ClassDecl = MD->getParent();
  9330. // C++ [except.spec]p14:
  9331. // An implicitly declared special member function (Clause 12) shall have an
  9332. // exception-specification. [...]
  9333. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9334. if (ClassDecl->isInvalidDecl())
  9335. return Info.ExceptSpec;
  9336. // FIXME: If this diagnostic fires, we're probably missing a check for
  9337. // attempting to resolve an exception specification before it's known
  9338. // at a higher level.
  9339. if (S.RequireCompleteType(MD->getLocation(),
  9340. S.Context.getRecordType(ClassDecl),
  9341. diag::err_exception_spec_incomplete_type))
  9342. return Info.ExceptSpec;
  9343. // C++1z [except.spec]p7:
  9344. // [Look for exceptions thrown by] a constructor selected [...] to
  9345. // initialize a potentially constructed subobject,
  9346. // C++1z [except.spec]p8:
  9347. // The exception specification for an implicitly-declared destructor, or a
  9348. // destructor without a noexcept-specifier, is potentially-throwing if and
  9349. // only if any of the destructors for any of its potentially constructed
  9350. // subojects is potentially throwing.
  9351. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9352. // in the second rule to resolve a core issue (no number yet) that would have
  9353. // us reject:
  9354. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9355. // struct B : A {};
  9356. // struct C : B { void f(); };
  9357. // ... due to giving B::~B() a non-throwing exception specification.
  9358. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9359. : Info.VisitAllBases);
  9360. return Info.ExceptSpec;
  9361. }
  9362. namespace {
  9363. /// RAII object to register a special member as being currently declared.
  9364. struct DeclaringSpecialMember {
  9365. Sema &S;
  9366. Sema::SpecialMemberDecl D;
  9367. Sema::ContextRAII SavedContext;
  9368. bool WasAlreadyBeingDeclared;
  9369. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9370. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9371. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9372. if (WasAlreadyBeingDeclared)
  9373. // This almost never happens, but if it does, ensure that our cache
  9374. // doesn't contain a stale result.
  9375. S.SpecialMemberCache.clear();
  9376. else {
  9377. // Register a note to be produced if we encounter an error while
  9378. // declaring the special member.
  9379. Sema::CodeSynthesisContext Ctx;
  9380. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9381. // FIXME: We don't have a location to use here. Using the class's
  9382. // location maintains the fiction that we declare all special members
  9383. // with the class, but (1) it's not clear that lying about that helps our
  9384. // users understand what's going on, and (2) there may be outer contexts
  9385. // on the stack (some of which are relevant) and printing them exposes
  9386. // our lies.
  9387. Ctx.PointOfInstantiation = RD->getLocation();
  9388. Ctx.Entity = RD;
  9389. Ctx.SpecialMember = CSM;
  9390. S.pushCodeSynthesisContext(Ctx);
  9391. }
  9392. }
  9393. ~DeclaringSpecialMember() {
  9394. if (!WasAlreadyBeingDeclared) {
  9395. S.SpecialMembersBeingDeclared.erase(D);
  9396. S.popCodeSynthesisContext();
  9397. }
  9398. }
  9399. /// Are we already trying to declare this special member?
  9400. bool isAlreadyBeingDeclared() const {
  9401. return WasAlreadyBeingDeclared;
  9402. }
  9403. };
  9404. }
  9405. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9406. // Look up any existing declarations, but don't trigger declaration of all
  9407. // implicit special members with this name.
  9408. DeclarationName Name = FD->getDeclName();
  9409. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9410. ForExternalRedeclaration);
  9411. for (auto *D : FD->getParent()->lookup(Name))
  9412. if (auto *Acceptable = R.getAcceptableDecl(D))
  9413. R.addDecl(Acceptable);
  9414. R.resolveKind();
  9415. R.suppressDiagnostics();
  9416. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9417. }
  9418. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9419. CXXRecordDecl *ClassDecl) {
  9420. // C++ [class.ctor]p5:
  9421. // A default constructor for a class X is a constructor of class X
  9422. // that can be called without an argument. If there is no
  9423. // user-declared constructor for class X, a default constructor is
  9424. // implicitly declared. An implicitly-declared default constructor
  9425. // is an inline public member of its class.
  9426. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9427. "Should not build implicit default constructor!");
  9428. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9429. if (DSM.isAlreadyBeingDeclared())
  9430. return nullptr;
  9431. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9432. CXXDefaultConstructor,
  9433. false);
  9434. // Create the actual constructor declaration.
  9435. CanQualType ClassType
  9436. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9437. SourceLocation ClassLoc = ClassDecl->getLocation();
  9438. DeclarationName Name
  9439. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9440. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9441. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9442. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
  9443. /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
  9444. /*isImplicitlyDeclared=*/true, Constexpr);
  9445. DefaultCon->setAccess(AS_public);
  9446. DefaultCon->setDefaulted();
  9447. if (getLangOpts().CUDA) {
  9448. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9449. DefaultCon,
  9450. /* ConstRHS */ false,
  9451. /* Diagnose */ false);
  9452. }
  9453. // Build an exception specification pointing back at this constructor.
  9454. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
  9455. DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9456. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9457. // constructors is easy to compute.
  9458. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9459. // Note that we have declared this constructor.
  9460. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  9461. Scope *S = getScopeForContext(ClassDecl);
  9462. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9463. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9464. SetDeclDeleted(DefaultCon, ClassLoc);
  9465. if (S)
  9466. PushOnScopeChains(DefaultCon, S, false);
  9467. ClassDecl->addDecl(DefaultCon);
  9468. return DefaultCon;
  9469. }
  9470. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9471. CXXConstructorDecl *Constructor) {
  9472. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9473. !Constructor->doesThisDeclarationHaveABody() &&
  9474. !Constructor->isDeleted()) &&
  9475. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9476. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9477. return;
  9478. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9479. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9480. SynthesizedFunctionScope Scope(*this, Constructor);
  9481. // The exception specification is needed because we are defining the
  9482. // function.
  9483. ResolveExceptionSpec(CurrentLocation,
  9484. Constructor->getType()->castAs<FunctionProtoType>());
  9485. MarkVTableUsed(CurrentLocation, ClassDecl);
  9486. // Add a context note for diagnostics produced after this point.
  9487. Scope.addContextNote(CurrentLocation);
  9488. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9489. Constructor->setInvalidDecl();
  9490. return;
  9491. }
  9492. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9493. ? Constructor->getEndLoc()
  9494. : Constructor->getLocation();
  9495. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9496. Constructor->markUsed(Context);
  9497. if (ASTMutationListener *L = getASTMutationListener()) {
  9498. L->CompletedImplicitDefinition(Constructor);
  9499. }
  9500. DiagnoseUninitializedFields(*this, Constructor);
  9501. }
  9502. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9503. // Perform any delayed checks on exception specifications.
  9504. CheckDelayedMemberExceptionSpecs();
  9505. }
  9506. /// Find or create the fake constructor we synthesize to model constructing an
  9507. /// object of a derived class via a constructor of a base class.
  9508. CXXConstructorDecl *
  9509. Sema::findInheritingConstructor(SourceLocation Loc,
  9510. CXXConstructorDecl *BaseCtor,
  9511. ConstructorUsingShadowDecl *Shadow) {
  9512. CXXRecordDecl *Derived = Shadow->getParent();
  9513. SourceLocation UsingLoc = Shadow->getLocation();
  9514. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9515. // For now we use the name of the base class constructor as a member of the
  9516. // derived class to indicate a (fake) inherited constructor name.
  9517. DeclarationName Name = BaseCtor->getDeclName();
  9518. // Check to see if we already have a fake constructor for this inherited
  9519. // constructor call.
  9520. for (NamedDecl *Ctor : Derived->lookup(Name))
  9521. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9522. ->getInheritedConstructor()
  9523. .getConstructor(),
  9524. BaseCtor))
  9525. return cast<CXXConstructorDecl>(Ctor);
  9526. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9527. TypeSourceInfo *TInfo =
  9528. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9529. FunctionProtoTypeLoc ProtoLoc =
  9530. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9531. // Check the inherited constructor is valid and find the list of base classes
  9532. // from which it was inherited.
  9533. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9534. bool Constexpr =
  9535. BaseCtor->isConstexpr() &&
  9536. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9537. false, BaseCtor, &ICI);
  9538. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9539. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9540. BaseCtor->isExplicit(), /*Inline=*/true,
  9541. /*ImplicitlyDeclared=*/true, Constexpr,
  9542. InheritedConstructor(Shadow, BaseCtor));
  9543. if (Shadow->isInvalidDecl())
  9544. DerivedCtor->setInvalidDecl();
  9545. // Build an unevaluated exception specification for this fake constructor.
  9546. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9547. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9548. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9549. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9550. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9551. FPT->getParamTypes(), EPI));
  9552. // Build the parameter declarations.
  9553. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9554. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9555. TypeSourceInfo *TInfo =
  9556. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9557. ParmVarDecl *PD = ParmVarDecl::Create(
  9558. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9559. FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
  9560. PD->setScopeInfo(0, I);
  9561. PD->setImplicit();
  9562. // Ensure attributes are propagated onto parameters (this matters for
  9563. // format, pass_object_size, ...).
  9564. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9565. ParamDecls.push_back(PD);
  9566. ProtoLoc.setParam(I, PD);
  9567. }
  9568. // Set up the new constructor.
  9569. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9570. DerivedCtor->setAccess(BaseCtor->getAccess());
  9571. DerivedCtor->setParams(ParamDecls);
  9572. Derived->addDecl(DerivedCtor);
  9573. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9574. SetDeclDeleted(DerivedCtor, UsingLoc);
  9575. return DerivedCtor;
  9576. }
  9577. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9578. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9579. Ctor->getInheritedConstructor().getShadowDecl());
  9580. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9581. /*Diagnose*/true);
  9582. }
  9583. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9584. CXXConstructorDecl *Constructor) {
  9585. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9586. assert(Constructor->getInheritedConstructor() &&
  9587. !Constructor->doesThisDeclarationHaveABody() &&
  9588. !Constructor->isDeleted());
  9589. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9590. return;
  9591. // Initializations are performed "as if by a defaulted default constructor",
  9592. // so enter the appropriate scope.
  9593. SynthesizedFunctionScope Scope(*this, Constructor);
  9594. // The exception specification is needed because we are defining the
  9595. // function.
  9596. ResolveExceptionSpec(CurrentLocation,
  9597. Constructor->getType()->castAs<FunctionProtoType>());
  9598. MarkVTableUsed(CurrentLocation, ClassDecl);
  9599. // Add a context note for diagnostics produced after this point.
  9600. Scope.addContextNote(CurrentLocation);
  9601. ConstructorUsingShadowDecl *Shadow =
  9602. Constructor->getInheritedConstructor().getShadowDecl();
  9603. CXXConstructorDecl *InheritedCtor =
  9604. Constructor->getInheritedConstructor().getConstructor();
  9605. // [class.inhctor.init]p1:
  9606. // initialization proceeds as if a defaulted default constructor is used to
  9607. // initialize the D object and each base class subobject from which the
  9608. // constructor was inherited
  9609. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9610. CXXRecordDecl *RD = Shadow->getParent();
  9611. SourceLocation InitLoc = Shadow->getLocation();
  9612. // Build explicit initializers for all base classes from which the
  9613. // constructor was inherited.
  9614. SmallVector<CXXCtorInitializer*, 8> Inits;
  9615. for (bool VBase : {false, true}) {
  9616. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9617. if (B.isVirtual() != VBase)
  9618. continue;
  9619. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9620. if (!BaseRD)
  9621. continue;
  9622. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9623. if (!BaseCtor.first)
  9624. continue;
  9625. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9626. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9627. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9628. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9629. Inits.push_back(new (Context) CXXCtorInitializer(
  9630. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9631. SourceLocation()));
  9632. }
  9633. }
  9634. // We now proceed as if for a defaulted default constructor, with the relevant
  9635. // initializers replaced.
  9636. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  9637. Constructor->setInvalidDecl();
  9638. return;
  9639. }
  9640. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9641. Constructor->markUsed(Context);
  9642. if (ASTMutationListener *L = getASTMutationListener()) {
  9643. L->CompletedImplicitDefinition(Constructor);
  9644. }
  9645. DiagnoseUninitializedFields(*this, Constructor);
  9646. }
  9647. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  9648. // C++ [class.dtor]p2:
  9649. // If a class has no user-declared destructor, a destructor is
  9650. // declared implicitly. An implicitly-declared destructor is an
  9651. // inline public member of its class.
  9652. assert(ClassDecl->needsImplicitDestructor());
  9653. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  9654. if (DSM.isAlreadyBeingDeclared())
  9655. return nullptr;
  9656. // Create the actual destructor declaration.
  9657. CanQualType ClassType
  9658. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9659. SourceLocation ClassLoc = ClassDecl->getLocation();
  9660. DeclarationName Name
  9661. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  9662. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9663. CXXDestructorDecl *Destructor
  9664. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  9665. QualType(), nullptr, /*isInline=*/true,
  9666. /*isImplicitlyDeclared=*/true);
  9667. Destructor->setAccess(AS_public);
  9668. Destructor->setDefaulted();
  9669. if (getLangOpts().CUDA) {
  9670. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  9671. Destructor,
  9672. /* ConstRHS */ false,
  9673. /* Diagnose */ false);
  9674. }
  9675. // Build an exception specification pointing back at this destructor.
  9676. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
  9677. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9678. // We don't need to use SpecialMemberIsTrivial here; triviality for
  9679. // destructors is easy to compute.
  9680. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  9681. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  9682. ClassDecl->hasTrivialDestructorForCall());
  9683. // Note that we have declared this destructor.
  9684. ++ASTContext::NumImplicitDestructorsDeclared;
  9685. Scope *S = getScopeForContext(ClassDecl);
  9686. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  9687. // We can't check whether an implicit destructor is deleted before we complete
  9688. // the definition of the class, because its validity depends on the alignment
  9689. // of the class. We'll check this from ActOnFields once the class is complete.
  9690. if (ClassDecl->isCompleteDefinition() &&
  9691. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  9692. SetDeclDeleted(Destructor, ClassLoc);
  9693. // Introduce this destructor into its scope.
  9694. if (S)
  9695. PushOnScopeChains(Destructor, S, false);
  9696. ClassDecl->addDecl(Destructor);
  9697. return Destructor;
  9698. }
  9699. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  9700. CXXDestructorDecl *Destructor) {
  9701. assert((Destructor->isDefaulted() &&
  9702. !Destructor->doesThisDeclarationHaveABody() &&
  9703. !Destructor->isDeleted()) &&
  9704. "DefineImplicitDestructor - call it for implicit default dtor");
  9705. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  9706. return;
  9707. CXXRecordDecl *ClassDecl = Destructor->getParent();
  9708. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  9709. SynthesizedFunctionScope Scope(*this, Destructor);
  9710. // The exception specification is needed because we are defining the
  9711. // function.
  9712. ResolveExceptionSpec(CurrentLocation,
  9713. Destructor->getType()->castAs<FunctionProtoType>());
  9714. MarkVTableUsed(CurrentLocation, ClassDecl);
  9715. // Add a context note for diagnostics produced after this point.
  9716. Scope.addContextNote(CurrentLocation);
  9717. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9718. Destructor->getParent());
  9719. if (CheckDestructor(Destructor)) {
  9720. Destructor->setInvalidDecl();
  9721. return;
  9722. }
  9723. SourceLocation Loc = Destructor->getEndLoc().isValid()
  9724. ? Destructor->getEndLoc()
  9725. : Destructor->getLocation();
  9726. Destructor->setBody(new (Context) CompoundStmt(Loc));
  9727. Destructor->markUsed(Context);
  9728. if (ASTMutationListener *L = getASTMutationListener()) {
  9729. L->CompletedImplicitDefinition(Destructor);
  9730. }
  9731. }
  9732. /// Perform any semantic analysis which needs to be delayed until all
  9733. /// pending class member declarations have been parsed.
  9734. void Sema::ActOnFinishCXXMemberDecls() {
  9735. // If the context is an invalid C++ class, just suppress these checks.
  9736. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  9737. if (Record->isInvalidDecl()) {
  9738. DelayedOverridingExceptionSpecChecks.clear();
  9739. DelayedEquivalentExceptionSpecChecks.clear();
  9740. DelayedDefaultedMemberExceptionSpecs.clear();
  9741. return;
  9742. }
  9743. checkForMultipleExportedDefaultConstructors(*this, Record);
  9744. }
  9745. }
  9746. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  9747. referenceDLLExportedClassMethods();
  9748. }
  9749. void Sema::referenceDLLExportedClassMethods() {
  9750. if (!DelayedDllExportClasses.empty()) {
  9751. // Calling ReferenceDllExportedMembers might cause the current function to
  9752. // be called again, so use a local copy of DelayedDllExportClasses.
  9753. SmallVector<CXXRecordDecl *, 4> WorkList;
  9754. std::swap(DelayedDllExportClasses, WorkList);
  9755. for (CXXRecordDecl *Class : WorkList)
  9756. ReferenceDllExportedMembers(*this, Class);
  9757. }
  9758. }
  9759. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  9760. assert(getLangOpts().CPlusPlus11 &&
  9761. "adjusting dtor exception specs was introduced in c++11");
  9762. if (Destructor->isDependentContext())
  9763. return;
  9764. // C++11 [class.dtor]p3:
  9765. // A declaration of a destructor that does not have an exception-
  9766. // specification is implicitly considered to have the same exception-
  9767. // specification as an implicit declaration.
  9768. const FunctionProtoType *DtorType = Destructor->getType()->
  9769. getAs<FunctionProtoType>();
  9770. if (DtorType->hasExceptionSpec())
  9771. return;
  9772. // Replace the destructor's type, building off the existing one. Fortunately,
  9773. // the only thing of interest in the destructor type is its extended info.
  9774. // The return and arguments are fixed.
  9775. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  9776. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9777. EPI.ExceptionSpec.SourceDecl = Destructor;
  9778. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9779. // FIXME: If the destructor has a body that could throw, and the newly created
  9780. // spec doesn't allow exceptions, we should emit a warning, because this
  9781. // change in behavior can break conforming C++03 programs at runtime.
  9782. // However, we don't have a body or an exception specification yet, so it
  9783. // needs to be done somewhere else.
  9784. }
  9785. namespace {
  9786. /// An abstract base class for all helper classes used in building the
  9787. // copy/move operators. These classes serve as factory functions and help us
  9788. // avoid using the same Expr* in the AST twice.
  9789. class ExprBuilder {
  9790. ExprBuilder(const ExprBuilder&) = delete;
  9791. ExprBuilder &operator=(const ExprBuilder&) = delete;
  9792. protected:
  9793. static Expr *assertNotNull(Expr *E) {
  9794. assert(E && "Expression construction must not fail.");
  9795. return E;
  9796. }
  9797. public:
  9798. ExprBuilder() {}
  9799. virtual ~ExprBuilder() {}
  9800. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  9801. };
  9802. class RefBuilder: public ExprBuilder {
  9803. VarDecl *Var;
  9804. QualType VarType;
  9805. public:
  9806. Expr *build(Sema &S, SourceLocation Loc) const override {
  9807. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
  9808. }
  9809. RefBuilder(VarDecl *Var, QualType VarType)
  9810. : Var(Var), VarType(VarType) {}
  9811. };
  9812. class ThisBuilder: public ExprBuilder {
  9813. public:
  9814. Expr *build(Sema &S, SourceLocation Loc) const override {
  9815. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  9816. }
  9817. };
  9818. class CastBuilder: public ExprBuilder {
  9819. const ExprBuilder &Builder;
  9820. QualType Type;
  9821. ExprValueKind Kind;
  9822. const CXXCastPath &Path;
  9823. public:
  9824. Expr *build(Sema &S, SourceLocation Loc) const override {
  9825. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  9826. CK_UncheckedDerivedToBase, Kind,
  9827. &Path).get());
  9828. }
  9829. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  9830. const CXXCastPath &Path)
  9831. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  9832. };
  9833. class DerefBuilder: public ExprBuilder {
  9834. const ExprBuilder &Builder;
  9835. public:
  9836. Expr *build(Sema &S, SourceLocation Loc) const override {
  9837. return assertNotNull(
  9838. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  9839. }
  9840. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9841. };
  9842. class MemberBuilder: public ExprBuilder {
  9843. const ExprBuilder &Builder;
  9844. QualType Type;
  9845. CXXScopeSpec SS;
  9846. bool IsArrow;
  9847. LookupResult &MemberLookup;
  9848. public:
  9849. Expr *build(Sema &S, SourceLocation Loc) const override {
  9850. return assertNotNull(S.BuildMemberReferenceExpr(
  9851. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  9852. nullptr, MemberLookup, nullptr, nullptr).get());
  9853. }
  9854. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  9855. LookupResult &MemberLookup)
  9856. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  9857. MemberLookup(MemberLookup) {}
  9858. };
  9859. class MoveCastBuilder: public ExprBuilder {
  9860. const ExprBuilder &Builder;
  9861. public:
  9862. Expr *build(Sema &S, SourceLocation Loc) const override {
  9863. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  9864. }
  9865. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9866. };
  9867. class LvalueConvBuilder: public ExprBuilder {
  9868. const ExprBuilder &Builder;
  9869. public:
  9870. Expr *build(Sema &S, SourceLocation Loc) const override {
  9871. return assertNotNull(
  9872. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  9873. }
  9874. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9875. };
  9876. class SubscriptBuilder: public ExprBuilder {
  9877. const ExprBuilder &Base;
  9878. const ExprBuilder &Index;
  9879. public:
  9880. Expr *build(Sema &S, SourceLocation Loc) const override {
  9881. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  9882. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  9883. }
  9884. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  9885. : Base(Base), Index(Index) {}
  9886. };
  9887. } // end anonymous namespace
  9888. /// When generating a defaulted copy or move assignment operator, if a field
  9889. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  9890. /// do so. This optimization only applies for arrays of scalars, and for arrays
  9891. /// of class type where the selected copy/move-assignment operator is trivial.
  9892. static StmtResult
  9893. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  9894. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  9895. // Compute the size of the memory buffer to be copied.
  9896. QualType SizeType = S.Context.getSizeType();
  9897. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  9898. S.Context.getTypeSizeInChars(T).getQuantity());
  9899. // Take the address of the field references for "from" and "to". We
  9900. // directly construct UnaryOperators here because semantic analysis
  9901. // does not permit us to take the address of an xvalue.
  9902. Expr *From = FromB.build(S, Loc);
  9903. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  9904. S.Context.getPointerType(From->getType()),
  9905. VK_RValue, OK_Ordinary, Loc, false);
  9906. Expr *To = ToB.build(S, Loc);
  9907. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  9908. S.Context.getPointerType(To->getType()),
  9909. VK_RValue, OK_Ordinary, Loc, false);
  9910. const Type *E = T->getBaseElementTypeUnsafe();
  9911. bool NeedsCollectableMemCpy =
  9912. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  9913. // Create a reference to the __builtin_objc_memmove_collectable function
  9914. StringRef MemCpyName = NeedsCollectableMemCpy ?
  9915. "__builtin_objc_memmove_collectable" :
  9916. "__builtin_memcpy";
  9917. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  9918. Sema::LookupOrdinaryName);
  9919. S.LookupName(R, S.TUScope, true);
  9920. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  9921. if (!MemCpy)
  9922. // Something went horribly wrong earlier, and we will have complained
  9923. // about it.
  9924. return StmtError();
  9925. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  9926. VK_RValue, Loc, nullptr);
  9927. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  9928. Expr *CallArgs[] = {
  9929. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  9930. };
  9931. ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  9932. Loc, CallArgs, Loc);
  9933. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  9934. return Call.getAs<Stmt>();
  9935. }
  9936. /// Builds a statement that copies/moves the given entity from \p From to
  9937. /// \c To.
  9938. ///
  9939. /// This routine is used to copy/move the members of a class with an
  9940. /// implicitly-declared copy/move assignment operator. When the entities being
  9941. /// copied are arrays, this routine builds for loops to copy them.
  9942. ///
  9943. /// \param S The Sema object used for type-checking.
  9944. ///
  9945. /// \param Loc The location where the implicit copy/move is being generated.
  9946. ///
  9947. /// \param T The type of the expressions being copied/moved. Both expressions
  9948. /// must have this type.
  9949. ///
  9950. /// \param To The expression we are copying/moving to.
  9951. ///
  9952. /// \param From The expression we are copying/moving from.
  9953. ///
  9954. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  9955. /// Otherwise, it's a non-static member subobject.
  9956. ///
  9957. /// \param Copying Whether we're copying or moving.
  9958. ///
  9959. /// \param Depth Internal parameter recording the depth of the recursion.
  9960. ///
  9961. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  9962. /// if a memcpy should be used instead.
  9963. static StmtResult
  9964. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  9965. const ExprBuilder &To, const ExprBuilder &From,
  9966. bool CopyingBaseSubobject, bool Copying,
  9967. unsigned Depth = 0) {
  9968. // C++11 [class.copy]p28:
  9969. // Each subobject is assigned in the manner appropriate to its type:
  9970. //
  9971. // - if the subobject is of class type, as if by a call to operator= with
  9972. // the subobject as the object expression and the corresponding
  9973. // subobject of x as a single function argument (as if by explicit
  9974. // qualification; that is, ignoring any possible virtual overriding
  9975. // functions in more derived classes);
  9976. //
  9977. // C++03 [class.copy]p13:
  9978. // - if the subobject is of class type, the copy assignment operator for
  9979. // the class is used (as if by explicit qualification; that is,
  9980. // ignoring any possible virtual overriding functions in more derived
  9981. // classes);
  9982. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  9983. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  9984. // Look for operator=.
  9985. DeclarationName Name
  9986. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  9987. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  9988. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  9989. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  9990. // operator.
  9991. if (!S.getLangOpts().CPlusPlus11) {
  9992. LookupResult::Filter F = OpLookup.makeFilter();
  9993. while (F.hasNext()) {
  9994. NamedDecl *D = F.next();
  9995. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  9996. if (Method->isCopyAssignmentOperator() ||
  9997. (!Copying && Method->isMoveAssignmentOperator()))
  9998. continue;
  9999. F.erase();
  10000. }
  10001. F.done();
  10002. }
  10003. // Suppress the protected check (C++ [class.protected]) for each of the
  10004. // assignment operators we found. This strange dance is required when
  10005. // we're assigning via a base classes's copy-assignment operator. To
  10006. // ensure that we're getting the right base class subobject (without
  10007. // ambiguities), we need to cast "this" to that subobject type; to
  10008. // ensure that we don't go through the virtual call mechanism, we need
  10009. // to qualify the operator= name with the base class (see below). However,
  10010. // this means that if the base class has a protected copy assignment
  10011. // operator, the protected member access check will fail. So, we
  10012. // rewrite "protected" access to "public" access in this case, since we
  10013. // know by construction that we're calling from a derived class.
  10014. if (CopyingBaseSubobject) {
  10015. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10016. L != LEnd; ++L) {
  10017. if (L.getAccess() == AS_protected)
  10018. L.setAccess(AS_public);
  10019. }
  10020. }
  10021. // Create the nested-name-specifier that will be used to qualify the
  10022. // reference to operator=; this is required to suppress the virtual
  10023. // call mechanism.
  10024. CXXScopeSpec SS;
  10025. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10026. SS.MakeTrivial(S.Context,
  10027. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10028. CanonicalT),
  10029. Loc);
  10030. // Create the reference to operator=.
  10031. ExprResult OpEqualRef
  10032. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
  10033. SS, /*TemplateKWLoc=*/SourceLocation(),
  10034. /*FirstQualifierInScope=*/nullptr,
  10035. OpLookup,
  10036. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10037. /*SuppressQualifierCheck=*/true);
  10038. if (OpEqualRef.isInvalid())
  10039. return StmtError();
  10040. // Build the call to the assignment operator.
  10041. Expr *FromInst = From.build(S, Loc);
  10042. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10043. OpEqualRef.getAs<Expr>(),
  10044. Loc, FromInst, Loc);
  10045. if (Call.isInvalid())
  10046. return StmtError();
  10047. // If we built a call to a trivial 'operator=' while copying an array,
  10048. // bail out. We'll replace the whole shebang with a memcpy.
  10049. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10050. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10051. return StmtResult((Stmt*)nullptr);
  10052. // Convert to an expression-statement, and clean up any produced
  10053. // temporaries.
  10054. return S.ActOnExprStmt(Call);
  10055. }
  10056. // - if the subobject is of scalar type, the built-in assignment
  10057. // operator is used.
  10058. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10059. if (!ArrayTy) {
  10060. ExprResult Assignment = S.CreateBuiltinBinOp(
  10061. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10062. if (Assignment.isInvalid())
  10063. return StmtError();
  10064. return S.ActOnExprStmt(Assignment);
  10065. }
  10066. // - if the subobject is an array, each element is assigned, in the
  10067. // manner appropriate to the element type;
  10068. // Construct a loop over the array bounds, e.g.,
  10069. //
  10070. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10071. //
  10072. // that will copy each of the array elements.
  10073. QualType SizeType = S.Context.getSizeType();
  10074. // Create the iteration variable.
  10075. IdentifierInfo *IterationVarName = nullptr;
  10076. {
  10077. SmallString<8> Str;
  10078. llvm::raw_svector_ostream OS(Str);
  10079. OS << "__i" << Depth;
  10080. IterationVarName = &S.Context.Idents.get(OS.str());
  10081. }
  10082. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10083. IterationVarName, SizeType,
  10084. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10085. SC_None);
  10086. // Initialize the iteration variable to zero.
  10087. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10088. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10089. // Creates a reference to the iteration variable.
  10090. RefBuilder IterationVarRef(IterationVar, SizeType);
  10091. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10092. // Create the DeclStmt that holds the iteration variable.
  10093. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10094. // Subscript the "from" and "to" expressions with the iteration variable.
  10095. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10096. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10097. const ExprBuilder *FromIndex;
  10098. if (Copying)
  10099. FromIndex = &FromIndexCopy;
  10100. else
  10101. FromIndex = &FromIndexMove;
  10102. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10103. // Build the copy/move for an individual element of the array.
  10104. StmtResult Copy =
  10105. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10106. ToIndex, *FromIndex, CopyingBaseSubobject,
  10107. Copying, Depth + 1);
  10108. // Bail out if copying fails or if we determined that we should use memcpy.
  10109. if (Copy.isInvalid() || !Copy.get())
  10110. return Copy;
  10111. // Create the comparison against the array bound.
  10112. llvm::APInt Upper
  10113. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10114. Expr *Comparison
  10115. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10116. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10117. BO_NE, S.Context.BoolTy,
  10118. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10119. // Create the pre-increment of the iteration variable. We can determine
  10120. // whether the increment will overflow based on the value of the array
  10121. // bound.
  10122. Expr *Increment = new (S.Context)
  10123. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10124. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10125. // Construct the loop that copies all elements of this array.
  10126. return S.ActOnForStmt(
  10127. Loc, Loc, InitStmt,
  10128. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10129. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10130. }
  10131. static StmtResult
  10132. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10133. const ExprBuilder &To, const ExprBuilder &From,
  10134. bool CopyingBaseSubobject, bool Copying) {
  10135. // Maybe we should use a memcpy?
  10136. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10137. T.isTriviallyCopyableType(S.Context))
  10138. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10139. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10140. CopyingBaseSubobject,
  10141. Copying, 0));
  10142. // If we ended up picking a trivial assignment operator for an array of a
  10143. // non-trivially-copyable class type, just emit a memcpy.
  10144. if (!Result.isInvalid() && !Result.get())
  10145. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10146. return Result;
  10147. }
  10148. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10149. // Note: The following rules are largely analoguous to the copy
  10150. // constructor rules. Note that virtual bases are not taken into account
  10151. // for determining the argument type of the operator. Note also that
  10152. // operators taking an object instead of a reference are allowed.
  10153. assert(ClassDecl->needsImplicitCopyAssignment());
  10154. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10155. if (DSM.isAlreadyBeingDeclared())
  10156. return nullptr;
  10157. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10158. QualType RetType = Context.getLValueReferenceType(ArgType);
  10159. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10160. if (Const)
  10161. ArgType = ArgType.withConst();
  10162. ArgType = Context.getLValueReferenceType(ArgType);
  10163. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10164. CXXCopyAssignment,
  10165. Const);
  10166. // An implicitly-declared copy assignment operator is an inline public
  10167. // member of its class.
  10168. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10169. SourceLocation ClassLoc = ClassDecl->getLocation();
  10170. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10171. CXXMethodDecl *CopyAssignment =
  10172. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10173. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10174. /*isInline=*/true, Constexpr, SourceLocation());
  10175. CopyAssignment->setAccess(AS_public);
  10176. CopyAssignment->setDefaulted();
  10177. CopyAssignment->setImplicit();
  10178. if (getLangOpts().CUDA) {
  10179. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10180. CopyAssignment,
  10181. /* ConstRHS */ Const,
  10182. /* Diagnose */ false);
  10183. }
  10184. // Build an exception specification pointing back at this member.
  10185. FunctionProtoType::ExtProtoInfo EPI =
  10186. getImplicitMethodEPI(*this, CopyAssignment);
  10187. CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10188. // Add the parameter to the operator.
  10189. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10190. ClassLoc, ClassLoc,
  10191. /*Id=*/nullptr, ArgType,
  10192. /*TInfo=*/nullptr, SC_None,
  10193. nullptr);
  10194. CopyAssignment->setParams(FromParam);
  10195. CopyAssignment->setTrivial(
  10196. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10197. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10198. : ClassDecl->hasTrivialCopyAssignment());
  10199. // Note that we have added this copy-assignment operator.
  10200. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  10201. Scope *S = getScopeForContext(ClassDecl);
  10202. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10203. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10204. SetDeclDeleted(CopyAssignment, ClassLoc);
  10205. if (S)
  10206. PushOnScopeChains(CopyAssignment, S, false);
  10207. ClassDecl->addDecl(CopyAssignment);
  10208. return CopyAssignment;
  10209. }
  10210. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10211. /// which is deprecated because the class has a user-declared copy constructor,
  10212. /// copy assignment operator, or destructor.
  10213. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10214. assert(CopyOp->isImplicit());
  10215. CXXRecordDecl *RD = CopyOp->getParent();
  10216. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10217. // In Microsoft mode, assignment operations don't affect constructors and
  10218. // vice versa.
  10219. if (RD->hasUserDeclaredDestructor()) {
  10220. UserDeclaredOperation = RD->getDestructor();
  10221. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10222. RD->hasUserDeclaredCopyConstructor() &&
  10223. !S.getLangOpts().MSVCCompat) {
  10224. // Find any user-declared copy constructor.
  10225. for (auto *I : RD->ctors()) {
  10226. if (I->isCopyConstructor()) {
  10227. UserDeclaredOperation = I;
  10228. break;
  10229. }
  10230. }
  10231. assert(UserDeclaredOperation);
  10232. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10233. RD->hasUserDeclaredCopyAssignment() &&
  10234. !S.getLangOpts().MSVCCompat) {
  10235. // Find any user-declared move assignment operator.
  10236. for (auto *I : RD->methods()) {
  10237. if (I->isCopyAssignmentOperator()) {
  10238. UserDeclaredOperation = I;
  10239. break;
  10240. }
  10241. }
  10242. assert(UserDeclaredOperation);
  10243. }
  10244. if (UserDeclaredOperation) {
  10245. S.Diag(UserDeclaredOperation->getLocation(),
  10246. diag::warn_deprecated_copy_operation)
  10247. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10248. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10249. }
  10250. }
  10251. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10252. CXXMethodDecl *CopyAssignOperator) {
  10253. assert((CopyAssignOperator->isDefaulted() &&
  10254. CopyAssignOperator->isOverloadedOperator() &&
  10255. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10256. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10257. !CopyAssignOperator->isDeleted()) &&
  10258. "DefineImplicitCopyAssignment called for wrong function");
  10259. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10260. return;
  10261. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10262. if (ClassDecl->isInvalidDecl()) {
  10263. CopyAssignOperator->setInvalidDecl();
  10264. return;
  10265. }
  10266. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10267. // The exception specification is needed because we are defining the
  10268. // function.
  10269. ResolveExceptionSpec(CurrentLocation,
  10270. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10271. // Add a context note for diagnostics produced after this point.
  10272. Scope.addContextNote(CurrentLocation);
  10273. // C++11 [class.copy]p18:
  10274. // The [definition of an implicitly declared copy assignment operator] is
  10275. // deprecated if the class has a user-declared copy constructor or a
  10276. // user-declared destructor.
  10277. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10278. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10279. // C++0x [class.copy]p30:
  10280. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10281. // for a non-union class X performs memberwise copy assignment of its
  10282. // subobjects. The direct base classes of X are assigned first, in the
  10283. // order of their declaration in the base-specifier-list, and then the
  10284. // immediate non-static data members of X are assigned, in the order in
  10285. // which they were declared in the class definition.
  10286. // The statements that form the synthesized function body.
  10287. SmallVector<Stmt*, 8> Statements;
  10288. // The parameter for the "other" object, which we are copying from.
  10289. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10290. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10291. QualType OtherRefType = Other->getType();
  10292. if (const LValueReferenceType *OtherRef
  10293. = OtherRefType->getAs<LValueReferenceType>()) {
  10294. OtherRefType = OtherRef->getPointeeType();
  10295. OtherQuals = OtherRefType.getQualifiers();
  10296. }
  10297. // Our location for everything implicitly-generated.
  10298. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10299. ? CopyAssignOperator->getEndLoc()
  10300. : CopyAssignOperator->getLocation();
  10301. // Builds a DeclRefExpr for the "other" object.
  10302. RefBuilder OtherRef(Other, OtherRefType);
  10303. // Builds the "this" pointer.
  10304. ThisBuilder This;
  10305. // Assign base classes.
  10306. bool Invalid = false;
  10307. for (auto &Base : ClassDecl->bases()) {
  10308. // Form the assignment:
  10309. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10310. QualType BaseType = Base.getType().getUnqualifiedType();
  10311. if (!BaseType->isRecordType()) {
  10312. Invalid = true;
  10313. continue;
  10314. }
  10315. CXXCastPath BasePath;
  10316. BasePath.push_back(&Base);
  10317. // Construct the "from" expression, which is an implicit cast to the
  10318. // appropriately-qualified base type.
  10319. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10320. VK_LValue, BasePath);
  10321. // Dereference "this".
  10322. DerefBuilder DerefThis(This);
  10323. CastBuilder To(DerefThis,
  10324. Context.getCVRQualifiedType(
  10325. BaseType, CopyAssignOperator->getTypeQualifiers()),
  10326. VK_LValue, BasePath);
  10327. // Build the copy.
  10328. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10329. To, From,
  10330. /*CopyingBaseSubobject=*/true,
  10331. /*Copying=*/true);
  10332. if (Copy.isInvalid()) {
  10333. CopyAssignOperator->setInvalidDecl();
  10334. return;
  10335. }
  10336. // Success! Record the copy.
  10337. Statements.push_back(Copy.getAs<Expr>());
  10338. }
  10339. // Assign non-static members.
  10340. for (auto *Field : ClassDecl->fields()) {
  10341. // FIXME: We should form some kind of AST representation for the implied
  10342. // memcpy in a union copy operation.
  10343. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10344. continue;
  10345. if (Field->isInvalidDecl()) {
  10346. Invalid = true;
  10347. continue;
  10348. }
  10349. // Check for members of reference type; we can't copy those.
  10350. if (Field->getType()->isReferenceType()) {
  10351. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10352. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10353. Diag(Field->getLocation(), diag::note_declared_at);
  10354. Invalid = true;
  10355. continue;
  10356. }
  10357. // Check for members of const-qualified, non-class type.
  10358. QualType BaseType = Context.getBaseElementType(Field->getType());
  10359. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10360. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10361. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10362. Diag(Field->getLocation(), diag::note_declared_at);
  10363. Invalid = true;
  10364. continue;
  10365. }
  10366. // Suppress assigning zero-width bitfields.
  10367. if (Field->isZeroLengthBitField(Context))
  10368. continue;
  10369. QualType FieldType = Field->getType().getNonReferenceType();
  10370. if (FieldType->isIncompleteArrayType()) {
  10371. assert(ClassDecl->hasFlexibleArrayMember() &&
  10372. "Incomplete array type is not valid");
  10373. continue;
  10374. }
  10375. // Build references to the field in the object we're copying from and to.
  10376. CXXScopeSpec SS; // Intentionally empty
  10377. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10378. LookupMemberName);
  10379. MemberLookup.addDecl(Field);
  10380. MemberLookup.resolveKind();
  10381. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10382. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10383. // Build the copy of this field.
  10384. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10385. To, From,
  10386. /*CopyingBaseSubobject=*/false,
  10387. /*Copying=*/true);
  10388. if (Copy.isInvalid()) {
  10389. CopyAssignOperator->setInvalidDecl();
  10390. return;
  10391. }
  10392. // Success! Record the copy.
  10393. Statements.push_back(Copy.getAs<Stmt>());
  10394. }
  10395. if (!Invalid) {
  10396. // Add a "return *this;"
  10397. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10398. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10399. if (Return.isInvalid())
  10400. Invalid = true;
  10401. else
  10402. Statements.push_back(Return.getAs<Stmt>());
  10403. }
  10404. if (Invalid) {
  10405. CopyAssignOperator->setInvalidDecl();
  10406. return;
  10407. }
  10408. StmtResult Body;
  10409. {
  10410. CompoundScopeRAII CompoundScope(*this);
  10411. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10412. /*isStmtExpr=*/false);
  10413. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10414. }
  10415. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10416. CopyAssignOperator->markUsed(Context);
  10417. if (ASTMutationListener *L = getASTMutationListener()) {
  10418. L->CompletedImplicitDefinition(CopyAssignOperator);
  10419. }
  10420. }
  10421. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10422. assert(ClassDecl->needsImplicitMoveAssignment());
  10423. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10424. if (DSM.isAlreadyBeingDeclared())
  10425. return nullptr;
  10426. // Note: The following rules are largely analoguous to the move
  10427. // constructor rules.
  10428. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10429. QualType RetType = Context.getLValueReferenceType(ArgType);
  10430. ArgType = Context.getRValueReferenceType(ArgType);
  10431. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10432. CXXMoveAssignment,
  10433. false);
  10434. // An implicitly-declared move assignment operator is an inline public
  10435. // member of its class.
  10436. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10437. SourceLocation ClassLoc = ClassDecl->getLocation();
  10438. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10439. CXXMethodDecl *MoveAssignment =
  10440. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10441. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10442. /*isInline=*/true, Constexpr, SourceLocation());
  10443. MoveAssignment->setAccess(AS_public);
  10444. MoveAssignment->setDefaulted();
  10445. MoveAssignment->setImplicit();
  10446. if (getLangOpts().CUDA) {
  10447. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10448. MoveAssignment,
  10449. /* ConstRHS */ false,
  10450. /* Diagnose */ false);
  10451. }
  10452. // Build an exception specification pointing back at this member.
  10453. FunctionProtoType::ExtProtoInfo EPI =
  10454. getImplicitMethodEPI(*this, MoveAssignment);
  10455. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10456. // Add the parameter to the operator.
  10457. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10458. ClassLoc, ClassLoc,
  10459. /*Id=*/nullptr, ArgType,
  10460. /*TInfo=*/nullptr, SC_None,
  10461. nullptr);
  10462. MoveAssignment->setParams(FromParam);
  10463. MoveAssignment->setTrivial(
  10464. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10465. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10466. : ClassDecl->hasTrivialMoveAssignment());
  10467. // Note that we have added this copy-assignment operator.
  10468. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  10469. Scope *S = getScopeForContext(ClassDecl);
  10470. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10471. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10472. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10473. SetDeclDeleted(MoveAssignment, ClassLoc);
  10474. }
  10475. if (S)
  10476. PushOnScopeChains(MoveAssignment, S, false);
  10477. ClassDecl->addDecl(MoveAssignment);
  10478. return MoveAssignment;
  10479. }
  10480. /// Check if we're implicitly defining a move assignment operator for a class
  10481. /// with virtual bases. Such a move assignment might move-assign the virtual
  10482. /// base multiple times.
  10483. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10484. SourceLocation CurrentLocation) {
  10485. assert(!Class->isDependentContext() && "should not define dependent move");
  10486. // Only a virtual base could get implicitly move-assigned multiple times.
  10487. // Only a non-trivial move assignment can observe this. We only want to
  10488. // diagnose if we implicitly define an assignment operator that assigns
  10489. // two base classes, both of which move-assign the same virtual base.
  10490. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10491. Class->getNumBases() < 2)
  10492. return;
  10493. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10494. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10495. VBaseMap VBases;
  10496. for (auto &BI : Class->bases()) {
  10497. Worklist.push_back(&BI);
  10498. while (!Worklist.empty()) {
  10499. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10500. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10501. // If the base has no non-trivial move assignment operators,
  10502. // we don't care about moves from it.
  10503. if (!Base->hasNonTrivialMoveAssignment())
  10504. continue;
  10505. // If there's nothing virtual here, skip it.
  10506. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10507. continue;
  10508. // If we're not actually going to call a move assignment for this base,
  10509. // or the selected move assignment is trivial, skip it.
  10510. Sema::SpecialMemberOverloadResult SMOR =
  10511. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10512. /*ConstArg*/false, /*VolatileArg*/false,
  10513. /*RValueThis*/true, /*ConstThis*/false,
  10514. /*VolatileThis*/false);
  10515. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10516. !SMOR.getMethod()->isMoveAssignmentOperator())
  10517. continue;
  10518. if (BaseSpec->isVirtual()) {
  10519. // We're going to move-assign this virtual base, and its move
  10520. // assignment operator is not trivial. If this can happen for
  10521. // multiple distinct direct bases of Class, diagnose it. (If it
  10522. // only happens in one base, we'll diagnose it when synthesizing
  10523. // that base class's move assignment operator.)
  10524. CXXBaseSpecifier *&Existing =
  10525. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10526. .first->second;
  10527. if (Existing && Existing != &BI) {
  10528. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10529. << Class << Base;
  10530. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10531. << (Base->getCanonicalDecl() ==
  10532. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10533. << Base << Existing->getType() << Existing->getSourceRange();
  10534. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10535. << (Base->getCanonicalDecl() ==
  10536. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10537. << Base << BI.getType() << BaseSpec->getSourceRange();
  10538. // Only diagnose each vbase once.
  10539. Existing = nullptr;
  10540. }
  10541. } else {
  10542. // Only walk over bases that have defaulted move assignment operators.
  10543. // We assume that any user-provided move assignment operator handles
  10544. // the multiple-moves-of-vbase case itself somehow.
  10545. if (!SMOR.getMethod()->isDefaulted())
  10546. continue;
  10547. // We're going to move the base classes of Base. Add them to the list.
  10548. for (auto &BI : Base->bases())
  10549. Worklist.push_back(&BI);
  10550. }
  10551. }
  10552. }
  10553. }
  10554. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10555. CXXMethodDecl *MoveAssignOperator) {
  10556. assert((MoveAssignOperator->isDefaulted() &&
  10557. MoveAssignOperator->isOverloadedOperator() &&
  10558. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10559. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10560. !MoveAssignOperator->isDeleted()) &&
  10561. "DefineImplicitMoveAssignment called for wrong function");
  10562. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10563. return;
  10564. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10565. if (ClassDecl->isInvalidDecl()) {
  10566. MoveAssignOperator->setInvalidDecl();
  10567. return;
  10568. }
  10569. // C++0x [class.copy]p28:
  10570. // The implicitly-defined or move assignment operator for a non-union class
  10571. // X performs memberwise move assignment of its subobjects. The direct base
  10572. // classes of X are assigned first, in the order of their declaration in the
  10573. // base-specifier-list, and then the immediate non-static data members of X
  10574. // are assigned, in the order in which they were declared in the class
  10575. // definition.
  10576. // Issue a warning if our implicit move assignment operator will move
  10577. // from a virtual base more than once.
  10578. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10579. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10580. // The exception specification is needed because we are defining the
  10581. // function.
  10582. ResolveExceptionSpec(CurrentLocation,
  10583. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10584. // Add a context note for diagnostics produced after this point.
  10585. Scope.addContextNote(CurrentLocation);
  10586. // The statements that form the synthesized function body.
  10587. SmallVector<Stmt*, 8> Statements;
  10588. // The parameter for the "other" object, which we are move from.
  10589. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10590. QualType OtherRefType = Other->getType()->
  10591. getAs<RValueReferenceType>()->getPointeeType();
  10592. assert(!OtherRefType.getQualifiers() &&
  10593. "Bad argument type of defaulted move assignment");
  10594. // Our location for everything implicitly-generated.
  10595. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10596. ? MoveAssignOperator->getEndLoc()
  10597. : MoveAssignOperator->getLocation();
  10598. // Builds a reference to the "other" object.
  10599. RefBuilder OtherRef(Other, OtherRefType);
  10600. // Cast to rvalue.
  10601. MoveCastBuilder MoveOther(OtherRef);
  10602. // Builds the "this" pointer.
  10603. ThisBuilder This;
  10604. // Assign base classes.
  10605. bool Invalid = false;
  10606. for (auto &Base : ClassDecl->bases()) {
  10607. // C++11 [class.copy]p28:
  10608. // It is unspecified whether subobjects representing virtual base classes
  10609. // are assigned more than once by the implicitly-defined copy assignment
  10610. // operator.
  10611. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10612. // class. For a move-assignment, this can result in the vbase being moved
  10613. // multiple times.
  10614. // Form the assignment:
  10615. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10616. QualType BaseType = Base.getType().getUnqualifiedType();
  10617. if (!BaseType->isRecordType()) {
  10618. Invalid = true;
  10619. continue;
  10620. }
  10621. CXXCastPath BasePath;
  10622. BasePath.push_back(&Base);
  10623. // Construct the "from" expression, which is an implicit cast to the
  10624. // appropriately-qualified base type.
  10625. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  10626. // Dereference "this".
  10627. DerefBuilder DerefThis(This);
  10628. // Implicitly cast "this" to the appropriately-qualified base type.
  10629. CastBuilder To(DerefThis,
  10630. Context.getCVRQualifiedType(
  10631. BaseType, MoveAssignOperator->getTypeQualifiers()),
  10632. VK_LValue, BasePath);
  10633. // Build the move.
  10634. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  10635. To, From,
  10636. /*CopyingBaseSubobject=*/true,
  10637. /*Copying=*/false);
  10638. if (Move.isInvalid()) {
  10639. MoveAssignOperator->setInvalidDecl();
  10640. return;
  10641. }
  10642. // Success! Record the move.
  10643. Statements.push_back(Move.getAs<Expr>());
  10644. }
  10645. // Assign non-static members.
  10646. for (auto *Field : ClassDecl->fields()) {
  10647. // FIXME: We should form some kind of AST representation for the implied
  10648. // memcpy in a union copy operation.
  10649. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10650. continue;
  10651. if (Field->isInvalidDecl()) {
  10652. Invalid = true;
  10653. continue;
  10654. }
  10655. // Check for members of reference type; we can't move those.
  10656. if (Field->getType()->isReferenceType()) {
  10657. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10658. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10659. Diag(Field->getLocation(), diag::note_declared_at);
  10660. Invalid = true;
  10661. continue;
  10662. }
  10663. // Check for members of const-qualified, non-class type.
  10664. QualType BaseType = Context.getBaseElementType(Field->getType());
  10665. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10666. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10667. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10668. Diag(Field->getLocation(), diag::note_declared_at);
  10669. Invalid = true;
  10670. continue;
  10671. }
  10672. // Suppress assigning zero-width bitfields.
  10673. if (Field->isZeroLengthBitField(Context))
  10674. continue;
  10675. QualType FieldType = Field->getType().getNonReferenceType();
  10676. if (FieldType->isIncompleteArrayType()) {
  10677. assert(ClassDecl->hasFlexibleArrayMember() &&
  10678. "Incomplete array type is not valid");
  10679. continue;
  10680. }
  10681. // Build references to the field in the object we're copying from and to.
  10682. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10683. LookupMemberName);
  10684. MemberLookup.addDecl(Field);
  10685. MemberLookup.resolveKind();
  10686. MemberBuilder From(MoveOther, OtherRefType,
  10687. /*IsArrow=*/false, MemberLookup);
  10688. MemberBuilder To(This, getCurrentThisType(),
  10689. /*IsArrow=*/true, MemberLookup);
  10690. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  10691. "Member reference with rvalue base must be rvalue except for reference "
  10692. "members, which aren't allowed for move assignment.");
  10693. // Build the move of this field.
  10694. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  10695. To, From,
  10696. /*CopyingBaseSubobject=*/false,
  10697. /*Copying=*/false);
  10698. if (Move.isInvalid()) {
  10699. MoveAssignOperator->setInvalidDecl();
  10700. return;
  10701. }
  10702. // Success! Record the copy.
  10703. Statements.push_back(Move.getAs<Stmt>());
  10704. }
  10705. if (!Invalid) {
  10706. // Add a "return *this;"
  10707. ExprResult ThisObj =
  10708. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10709. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10710. if (Return.isInvalid())
  10711. Invalid = true;
  10712. else
  10713. Statements.push_back(Return.getAs<Stmt>());
  10714. }
  10715. if (Invalid) {
  10716. MoveAssignOperator->setInvalidDecl();
  10717. return;
  10718. }
  10719. StmtResult Body;
  10720. {
  10721. CompoundScopeRAII CompoundScope(*this);
  10722. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10723. /*isStmtExpr=*/false);
  10724. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10725. }
  10726. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  10727. MoveAssignOperator->markUsed(Context);
  10728. if (ASTMutationListener *L = getASTMutationListener()) {
  10729. L->CompletedImplicitDefinition(MoveAssignOperator);
  10730. }
  10731. }
  10732. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  10733. CXXRecordDecl *ClassDecl) {
  10734. // C++ [class.copy]p4:
  10735. // If the class definition does not explicitly declare a copy
  10736. // constructor, one is declared implicitly.
  10737. assert(ClassDecl->needsImplicitCopyConstructor());
  10738. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  10739. if (DSM.isAlreadyBeingDeclared())
  10740. return nullptr;
  10741. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10742. QualType ArgType = ClassType;
  10743. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  10744. if (Const)
  10745. ArgType = ArgType.withConst();
  10746. ArgType = Context.getLValueReferenceType(ArgType);
  10747. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10748. CXXCopyConstructor,
  10749. Const);
  10750. DeclarationName Name
  10751. = Context.DeclarationNames.getCXXConstructorName(
  10752. Context.getCanonicalType(ClassType));
  10753. SourceLocation ClassLoc = ClassDecl->getLocation();
  10754. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10755. // An implicitly-declared copy constructor is an inline public
  10756. // member of its class.
  10757. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  10758. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10759. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10760. Constexpr);
  10761. CopyConstructor->setAccess(AS_public);
  10762. CopyConstructor->setDefaulted();
  10763. if (getLangOpts().CUDA) {
  10764. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  10765. CopyConstructor,
  10766. /* ConstRHS */ Const,
  10767. /* Diagnose */ false);
  10768. }
  10769. // Build an exception specification pointing back at this member.
  10770. FunctionProtoType::ExtProtoInfo EPI =
  10771. getImplicitMethodEPI(*this, CopyConstructor);
  10772. CopyConstructor->setType(
  10773. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10774. // Add the parameter to the constructor.
  10775. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  10776. ClassLoc, ClassLoc,
  10777. /*IdentifierInfo=*/nullptr,
  10778. ArgType, /*TInfo=*/nullptr,
  10779. SC_None, nullptr);
  10780. CopyConstructor->setParams(FromParam);
  10781. CopyConstructor->setTrivial(
  10782. ClassDecl->needsOverloadResolutionForCopyConstructor()
  10783. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  10784. : ClassDecl->hasTrivialCopyConstructor());
  10785. CopyConstructor->setTrivialForCall(
  10786. ClassDecl->hasAttr<TrivialABIAttr>() ||
  10787. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  10788. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  10789. TAH_ConsiderTrivialABI)
  10790. : ClassDecl->hasTrivialCopyConstructorForCall()));
  10791. // Note that we have declared this constructor.
  10792. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  10793. Scope *S = getScopeForContext(ClassDecl);
  10794. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  10795. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  10796. ClassDecl->setImplicitCopyConstructorIsDeleted();
  10797. SetDeclDeleted(CopyConstructor, ClassLoc);
  10798. }
  10799. if (S)
  10800. PushOnScopeChains(CopyConstructor, S, false);
  10801. ClassDecl->addDecl(CopyConstructor);
  10802. return CopyConstructor;
  10803. }
  10804. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  10805. CXXConstructorDecl *CopyConstructor) {
  10806. assert((CopyConstructor->isDefaulted() &&
  10807. CopyConstructor->isCopyConstructor() &&
  10808. !CopyConstructor->doesThisDeclarationHaveABody() &&
  10809. !CopyConstructor->isDeleted()) &&
  10810. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  10811. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  10812. return;
  10813. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  10814. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  10815. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  10816. // The exception specification is needed because we are defining the
  10817. // function.
  10818. ResolveExceptionSpec(CurrentLocation,
  10819. CopyConstructor->getType()->castAs<FunctionProtoType>());
  10820. MarkVTableUsed(CurrentLocation, ClassDecl);
  10821. // Add a context note for diagnostics produced after this point.
  10822. Scope.addContextNote(CurrentLocation);
  10823. // C++11 [class.copy]p7:
  10824. // The [definition of an implicitly declared copy constructor] is
  10825. // deprecated if the class has a user-declared copy assignment operator
  10826. // or a user-declared destructor.
  10827. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  10828. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  10829. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  10830. CopyConstructor->setInvalidDecl();
  10831. } else {
  10832. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  10833. ? CopyConstructor->getEndLoc()
  10834. : CopyConstructor->getLocation();
  10835. Sema::CompoundScopeRAII CompoundScope(*this);
  10836. CopyConstructor->setBody(
  10837. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  10838. CopyConstructor->markUsed(Context);
  10839. }
  10840. if (ASTMutationListener *L = getASTMutationListener()) {
  10841. L->CompletedImplicitDefinition(CopyConstructor);
  10842. }
  10843. }
  10844. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  10845. CXXRecordDecl *ClassDecl) {
  10846. assert(ClassDecl->needsImplicitMoveConstructor());
  10847. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  10848. if (DSM.isAlreadyBeingDeclared())
  10849. return nullptr;
  10850. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10851. QualType ArgType = Context.getRValueReferenceType(ClassType);
  10852. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10853. CXXMoveConstructor,
  10854. false);
  10855. DeclarationName Name
  10856. = Context.DeclarationNames.getCXXConstructorName(
  10857. Context.getCanonicalType(ClassType));
  10858. SourceLocation ClassLoc = ClassDecl->getLocation();
  10859. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10860. // C++11 [class.copy]p11:
  10861. // An implicitly-declared copy/move constructor is an inline public
  10862. // member of its class.
  10863. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  10864. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10865. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10866. Constexpr);
  10867. MoveConstructor->setAccess(AS_public);
  10868. MoveConstructor->setDefaulted();
  10869. if (getLangOpts().CUDA) {
  10870. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  10871. MoveConstructor,
  10872. /* ConstRHS */ false,
  10873. /* Diagnose */ false);
  10874. }
  10875. // Build an exception specification pointing back at this member.
  10876. FunctionProtoType::ExtProtoInfo EPI =
  10877. getImplicitMethodEPI(*this, MoveConstructor);
  10878. MoveConstructor->setType(
  10879. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10880. // Add the parameter to the constructor.
  10881. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  10882. ClassLoc, ClassLoc,
  10883. /*IdentifierInfo=*/nullptr,
  10884. ArgType, /*TInfo=*/nullptr,
  10885. SC_None, nullptr);
  10886. MoveConstructor->setParams(FromParam);
  10887. MoveConstructor->setTrivial(
  10888. ClassDecl->needsOverloadResolutionForMoveConstructor()
  10889. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  10890. : ClassDecl->hasTrivialMoveConstructor());
  10891. MoveConstructor->setTrivialForCall(
  10892. ClassDecl->hasAttr<TrivialABIAttr>() ||
  10893. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  10894. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  10895. TAH_ConsiderTrivialABI)
  10896. : ClassDecl->hasTrivialMoveConstructorForCall()));
  10897. // Note that we have declared this constructor.
  10898. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  10899. Scope *S = getScopeForContext(ClassDecl);
  10900. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  10901. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  10902. ClassDecl->setImplicitMoveConstructorIsDeleted();
  10903. SetDeclDeleted(MoveConstructor, ClassLoc);
  10904. }
  10905. if (S)
  10906. PushOnScopeChains(MoveConstructor, S, false);
  10907. ClassDecl->addDecl(MoveConstructor);
  10908. return MoveConstructor;
  10909. }
  10910. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  10911. CXXConstructorDecl *MoveConstructor) {
  10912. assert((MoveConstructor->isDefaulted() &&
  10913. MoveConstructor->isMoveConstructor() &&
  10914. !MoveConstructor->doesThisDeclarationHaveABody() &&
  10915. !MoveConstructor->isDeleted()) &&
  10916. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  10917. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  10918. return;
  10919. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  10920. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  10921. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  10922. // The exception specification is needed because we are defining the
  10923. // function.
  10924. ResolveExceptionSpec(CurrentLocation,
  10925. MoveConstructor->getType()->castAs<FunctionProtoType>());
  10926. MarkVTableUsed(CurrentLocation, ClassDecl);
  10927. // Add a context note for diagnostics produced after this point.
  10928. Scope.addContextNote(CurrentLocation);
  10929. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  10930. MoveConstructor->setInvalidDecl();
  10931. } else {
  10932. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  10933. ? MoveConstructor->getEndLoc()
  10934. : MoveConstructor->getLocation();
  10935. Sema::CompoundScopeRAII CompoundScope(*this);
  10936. MoveConstructor->setBody(ActOnCompoundStmt(
  10937. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  10938. MoveConstructor->markUsed(Context);
  10939. }
  10940. if (ASTMutationListener *L = getASTMutationListener()) {
  10941. L->CompletedImplicitDefinition(MoveConstructor);
  10942. }
  10943. }
  10944. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  10945. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  10946. }
  10947. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  10948. SourceLocation CurrentLocation,
  10949. CXXConversionDecl *Conv) {
  10950. SynthesizedFunctionScope Scope(*this, Conv);
  10951. assert(!Conv->getReturnType()->isUndeducedType());
  10952. CXXRecordDecl *Lambda = Conv->getParent();
  10953. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  10954. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  10955. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  10956. CallOp = InstantiateFunctionDeclaration(
  10957. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  10958. if (!CallOp)
  10959. return;
  10960. Invoker = InstantiateFunctionDeclaration(
  10961. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  10962. if (!Invoker)
  10963. return;
  10964. }
  10965. if (CallOp->isInvalidDecl())
  10966. return;
  10967. // Mark the call operator referenced (and add to pending instantiations
  10968. // if necessary).
  10969. // For both the conversion and static-invoker template specializations
  10970. // we construct their body's in this function, so no need to add them
  10971. // to the PendingInstantiations.
  10972. MarkFunctionReferenced(CurrentLocation, CallOp);
  10973. // Fill in the __invoke function with a dummy implementation. IR generation
  10974. // will fill in the actual details. Update its type in case it contained
  10975. // an 'auto'.
  10976. Invoker->markUsed(Context);
  10977. Invoker->setReferenced();
  10978. Invoker->setType(Conv->getReturnType()->getPointeeType());
  10979. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  10980. // Construct the body of the conversion function { return __invoke; }.
  10981. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  10982. VK_LValue, Conv->getLocation()).get();
  10983. assert(FunctionRef && "Can't refer to __invoke function?");
  10984. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  10985. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  10986. Conv->getLocation()));
  10987. Conv->markUsed(Context);
  10988. Conv->setReferenced();
  10989. if (ASTMutationListener *L = getASTMutationListener()) {
  10990. L->CompletedImplicitDefinition(Conv);
  10991. L->CompletedImplicitDefinition(Invoker);
  10992. }
  10993. }
  10994. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  10995. SourceLocation CurrentLocation,
  10996. CXXConversionDecl *Conv)
  10997. {
  10998. assert(!Conv->getParent()->isGenericLambda());
  10999. SynthesizedFunctionScope Scope(*this, Conv);
  11000. // Copy-initialize the lambda object as needed to capture it.
  11001. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11002. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11003. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11004. Conv->getLocation(),
  11005. Conv, DerefThis);
  11006. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11007. // behavior. Note that only the general conversion function does this
  11008. // (since it's unusable otherwise); in the case where we inline the
  11009. // block literal, it has block literal lifetime semantics.
  11010. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11011. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11012. CK_CopyAndAutoreleaseBlockObject,
  11013. BuildBlock.get(), nullptr, VK_RValue);
  11014. if (BuildBlock.isInvalid()) {
  11015. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11016. Conv->setInvalidDecl();
  11017. return;
  11018. }
  11019. // Create the return statement that returns the block from the conversion
  11020. // function.
  11021. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11022. if (Return.isInvalid()) {
  11023. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11024. Conv->setInvalidDecl();
  11025. return;
  11026. }
  11027. // Set the body of the conversion function.
  11028. Stmt *ReturnS = Return.get();
  11029. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11030. Conv->getLocation()));
  11031. Conv->markUsed(Context);
  11032. // We're done; notify the mutation listener, if any.
  11033. if (ASTMutationListener *L = getASTMutationListener()) {
  11034. L->CompletedImplicitDefinition(Conv);
  11035. }
  11036. }
  11037. /// Determine whether the given list arguments contains exactly one
  11038. /// "real" (non-default) argument.
  11039. static bool hasOneRealArgument(MultiExprArg Args) {
  11040. switch (Args.size()) {
  11041. case 0:
  11042. return false;
  11043. default:
  11044. if (!Args[1]->isDefaultArgument())
  11045. return false;
  11046. LLVM_FALLTHROUGH;
  11047. case 1:
  11048. return !Args[0]->isDefaultArgument();
  11049. }
  11050. return false;
  11051. }
  11052. ExprResult
  11053. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11054. NamedDecl *FoundDecl,
  11055. CXXConstructorDecl *Constructor,
  11056. MultiExprArg ExprArgs,
  11057. bool HadMultipleCandidates,
  11058. bool IsListInitialization,
  11059. bool IsStdInitListInitialization,
  11060. bool RequiresZeroInit,
  11061. unsigned ConstructKind,
  11062. SourceRange ParenRange) {
  11063. bool Elidable = false;
  11064. // C++0x [class.copy]p34:
  11065. // When certain criteria are met, an implementation is allowed to
  11066. // omit the copy/move construction of a class object, even if the
  11067. // copy/move constructor and/or destructor for the object have
  11068. // side effects. [...]
  11069. // - when a temporary class object that has not been bound to a
  11070. // reference (12.2) would be copied/moved to a class object
  11071. // with the same cv-unqualified type, the copy/move operation
  11072. // can be omitted by constructing the temporary object
  11073. // directly into the target of the omitted copy/move
  11074. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11075. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11076. Expr *SubExpr = ExprArgs[0];
  11077. Elidable = SubExpr->isTemporaryObject(
  11078. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11079. }
  11080. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11081. FoundDecl, Constructor,
  11082. Elidable, ExprArgs, HadMultipleCandidates,
  11083. IsListInitialization,
  11084. IsStdInitListInitialization, RequiresZeroInit,
  11085. ConstructKind, ParenRange);
  11086. }
  11087. ExprResult
  11088. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11089. NamedDecl *FoundDecl,
  11090. CXXConstructorDecl *Constructor,
  11091. bool Elidable,
  11092. MultiExprArg ExprArgs,
  11093. bool HadMultipleCandidates,
  11094. bool IsListInitialization,
  11095. bool IsStdInitListInitialization,
  11096. bool RequiresZeroInit,
  11097. unsigned ConstructKind,
  11098. SourceRange ParenRange) {
  11099. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11100. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11101. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11102. return ExprError();
  11103. }
  11104. return BuildCXXConstructExpr(
  11105. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11106. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11107. RequiresZeroInit, ConstructKind, ParenRange);
  11108. }
  11109. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11110. /// including handling of its default argument expressions.
  11111. ExprResult
  11112. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11113. CXXConstructorDecl *Constructor,
  11114. bool Elidable,
  11115. MultiExprArg ExprArgs,
  11116. bool HadMultipleCandidates,
  11117. bool IsListInitialization,
  11118. bool IsStdInitListInitialization,
  11119. bool RequiresZeroInit,
  11120. unsigned ConstructKind,
  11121. SourceRange ParenRange) {
  11122. assert(declaresSameEntity(
  11123. Constructor->getParent(),
  11124. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11125. "given constructor for wrong type");
  11126. MarkFunctionReferenced(ConstructLoc, Constructor);
  11127. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11128. return ExprError();
  11129. return CXXConstructExpr::Create(
  11130. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11131. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11132. IsStdInitListInitialization, RequiresZeroInit,
  11133. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11134. ParenRange);
  11135. }
  11136. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11137. assert(Field->hasInClassInitializer());
  11138. // If we already have the in-class initializer nothing needs to be done.
  11139. if (Field->getInClassInitializer())
  11140. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  11141. // If we might have already tried and failed to instantiate, don't try again.
  11142. if (Field->isInvalidDecl())
  11143. return ExprError();
  11144. // Maybe we haven't instantiated the in-class initializer. Go check the
  11145. // pattern FieldDecl to see if it has one.
  11146. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11147. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11148. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11149. DeclContext::lookup_result Lookup =
  11150. ClassPattern->lookup(Field->getDeclName());
  11151. // Lookup can return at most two results: the pattern for the field, or the
  11152. // injected class name of the parent record. No other member can have the
  11153. // same name as the field.
  11154. // In modules mode, lookup can return multiple results (coming from
  11155. // different modules).
  11156. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11157. "more than two lookup results for field name");
  11158. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11159. if (!Pattern) {
  11160. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11161. "cannot have other non-field member with same name");
  11162. for (auto L : Lookup)
  11163. if (isa<FieldDecl>(L)) {
  11164. Pattern = cast<FieldDecl>(L);
  11165. break;
  11166. }
  11167. assert(Pattern && "We must have set the Pattern!");
  11168. }
  11169. if (!Pattern->hasInClassInitializer() ||
  11170. InstantiateInClassInitializer(Loc, Field, Pattern,
  11171. getTemplateInstantiationArgs(Field))) {
  11172. // Don't diagnose this again.
  11173. Field->setInvalidDecl();
  11174. return ExprError();
  11175. }
  11176. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  11177. }
  11178. // DR1351:
  11179. // If the brace-or-equal-initializer of a non-static data member
  11180. // invokes a defaulted default constructor of its class or of an
  11181. // enclosing class in a potentially evaluated subexpression, the
  11182. // program is ill-formed.
  11183. //
  11184. // This resolution is unworkable: the exception specification of the
  11185. // default constructor can be needed in an unevaluated context, in
  11186. // particular, in the operand of a noexcept-expression, and we can be
  11187. // unable to compute an exception specification for an enclosed class.
  11188. //
  11189. // Any attempt to resolve the exception specification of a defaulted default
  11190. // constructor before the initializer is lexically complete will ultimately
  11191. // come here at which point we can diagnose it.
  11192. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11193. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11194. << OutermostClass << Field;
  11195. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11196. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11197. if (!isSFINAEContext())
  11198. Field->setInvalidDecl();
  11199. return ExprError();
  11200. }
  11201. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11202. if (VD->isInvalidDecl()) return;
  11203. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11204. if (ClassDecl->isInvalidDecl()) return;
  11205. if (ClassDecl->hasIrrelevantDestructor()) return;
  11206. if (ClassDecl->isDependentContext()) return;
  11207. if (VD->isNoDestroy(getASTContext()))
  11208. return;
  11209. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11210. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11211. CheckDestructorAccess(VD->getLocation(), Destructor,
  11212. PDiag(diag::err_access_dtor_var)
  11213. << VD->getDeclName()
  11214. << VD->getType());
  11215. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11216. if (Destructor->isTrivial()) return;
  11217. if (!VD->hasGlobalStorage()) return;
  11218. // Emit warning for non-trivial dtor in global scope (a real global,
  11219. // class-static, function-static).
  11220. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11221. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11222. if (!VD->isStaticLocal())
  11223. Diag(VD->getLocation(), diag::warn_global_destructor);
  11224. }
  11225. /// Given a constructor and the set of arguments provided for the
  11226. /// constructor, convert the arguments and add any required default arguments
  11227. /// to form a proper call to this constructor.
  11228. ///
  11229. /// \returns true if an error occurred, false otherwise.
  11230. bool
  11231. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11232. MultiExprArg ArgsPtr,
  11233. SourceLocation Loc,
  11234. SmallVectorImpl<Expr*> &ConvertedArgs,
  11235. bool AllowExplicit,
  11236. bool IsListInitialization) {
  11237. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11238. unsigned NumArgs = ArgsPtr.size();
  11239. Expr **Args = ArgsPtr.data();
  11240. const FunctionProtoType *Proto
  11241. = Constructor->getType()->getAs<FunctionProtoType>();
  11242. assert(Proto && "Constructor without a prototype?");
  11243. unsigned NumParams = Proto->getNumParams();
  11244. // If too few arguments are available, we'll fill in the rest with defaults.
  11245. if (NumArgs < NumParams)
  11246. ConvertedArgs.reserve(NumParams);
  11247. else
  11248. ConvertedArgs.reserve(NumArgs);
  11249. VariadicCallType CallType =
  11250. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11251. SmallVector<Expr *, 8> AllArgs;
  11252. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11253. Proto, 0,
  11254. llvm::makeArrayRef(Args, NumArgs),
  11255. AllArgs,
  11256. CallType, AllowExplicit,
  11257. IsListInitialization);
  11258. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11259. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11260. CheckConstructorCall(Constructor,
  11261. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11262. Proto, Loc);
  11263. return Invalid;
  11264. }
  11265. static inline bool
  11266. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11267. const FunctionDecl *FnDecl) {
  11268. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11269. if (isa<NamespaceDecl>(DC)) {
  11270. return SemaRef.Diag(FnDecl->getLocation(),
  11271. diag::err_operator_new_delete_declared_in_namespace)
  11272. << FnDecl->getDeclName();
  11273. }
  11274. if (isa<TranslationUnitDecl>(DC) &&
  11275. FnDecl->getStorageClass() == SC_Static) {
  11276. return SemaRef.Diag(FnDecl->getLocation(),
  11277. diag::err_operator_new_delete_declared_static)
  11278. << FnDecl->getDeclName();
  11279. }
  11280. return false;
  11281. }
  11282. static QualType
  11283. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11284. QualType QTy = PtrTy->getPointeeType();
  11285. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11286. return SemaRef.Context.getPointerType(QTy);
  11287. }
  11288. static inline bool
  11289. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11290. CanQualType ExpectedResultType,
  11291. CanQualType ExpectedFirstParamType,
  11292. unsigned DependentParamTypeDiag,
  11293. unsigned InvalidParamTypeDiag) {
  11294. QualType ResultType =
  11295. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11296. // Check that the result type is not dependent.
  11297. if (ResultType->isDependentType())
  11298. return SemaRef.Diag(FnDecl->getLocation(),
  11299. diag::err_operator_new_delete_dependent_result_type)
  11300. << FnDecl->getDeclName() << ExpectedResultType;
  11301. // OpenCL C++: the operator is valid on any address space.
  11302. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11303. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11304. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11305. }
  11306. }
  11307. // Check that the result type is what we expect.
  11308. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11309. return SemaRef.Diag(FnDecl->getLocation(),
  11310. diag::err_operator_new_delete_invalid_result_type)
  11311. << FnDecl->getDeclName() << ExpectedResultType;
  11312. // A function template must have at least 2 parameters.
  11313. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11314. return SemaRef.Diag(FnDecl->getLocation(),
  11315. diag::err_operator_new_delete_template_too_few_parameters)
  11316. << FnDecl->getDeclName();
  11317. // The function decl must have at least 1 parameter.
  11318. if (FnDecl->getNumParams() == 0)
  11319. return SemaRef.Diag(FnDecl->getLocation(),
  11320. diag::err_operator_new_delete_too_few_parameters)
  11321. << FnDecl->getDeclName();
  11322. // Check the first parameter type is not dependent.
  11323. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11324. if (FirstParamType->isDependentType())
  11325. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11326. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11327. // Check that the first parameter type is what we expect.
  11328. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11329. // OpenCL C++: the operator is valid on any address space.
  11330. if (auto *PtrTy =
  11331. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11332. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11333. }
  11334. }
  11335. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11336. ExpectedFirstParamType)
  11337. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11338. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11339. return false;
  11340. }
  11341. static bool
  11342. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11343. // C++ [basic.stc.dynamic.allocation]p1:
  11344. // A program is ill-formed if an allocation function is declared in a
  11345. // namespace scope other than global scope or declared static in global
  11346. // scope.
  11347. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11348. return true;
  11349. CanQualType SizeTy =
  11350. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11351. // C++ [basic.stc.dynamic.allocation]p1:
  11352. // The return type shall be void*. The first parameter shall have type
  11353. // std::size_t.
  11354. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11355. SizeTy,
  11356. diag::err_operator_new_dependent_param_type,
  11357. diag::err_operator_new_param_type))
  11358. return true;
  11359. // C++ [basic.stc.dynamic.allocation]p1:
  11360. // The first parameter shall not have an associated default argument.
  11361. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11362. return SemaRef.Diag(FnDecl->getLocation(),
  11363. diag::err_operator_new_default_arg)
  11364. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11365. return false;
  11366. }
  11367. static bool
  11368. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11369. // C++ [basic.stc.dynamic.deallocation]p1:
  11370. // A program is ill-formed if deallocation functions are declared in a
  11371. // namespace scope other than global scope or declared static in global
  11372. // scope.
  11373. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11374. return true;
  11375. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11376. // C++ P0722:
  11377. // Within a class C, the first parameter of a destroying operator delete
  11378. // shall be of type C *. The first parameter of any other deallocation
  11379. // function shall be of type void *.
  11380. CanQualType ExpectedFirstParamType =
  11381. MD && MD->isDestroyingOperatorDelete()
  11382. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11383. SemaRef.Context.getRecordType(MD->getParent())))
  11384. : SemaRef.Context.VoidPtrTy;
  11385. // C++ [basic.stc.dynamic.deallocation]p2:
  11386. // Each deallocation function shall return void
  11387. if (CheckOperatorNewDeleteTypes(
  11388. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11389. diag::err_operator_delete_dependent_param_type,
  11390. diag::err_operator_delete_param_type))
  11391. return true;
  11392. // C++ P0722:
  11393. // A destroying operator delete shall be a usual deallocation function.
  11394. if (MD && !MD->getParent()->isDependentContext() &&
  11395. MD->isDestroyingOperatorDelete() &&
  11396. !SemaRef.isUsualDeallocationFunction(MD)) {
  11397. SemaRef.Diag(MD->getLocation(),
  11398. diag::err_destroying_operator_delete_not_usual);
  11399. return true;
  11400. }
  11401. return false;
  11402. }
  11403. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11404. /// of this overloaded operator is well-formed. If so, returns false;
  11405. /// otherwise, emits appropriate diagnostics and returns true.
  11406. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11407. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11408. "Expected an overloaded operator declaration");
  11409. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11410. // C++ [over.oper]p5:
  11411. // The allocation and deallocation functions, operator new,
  11412. // operator new[], operator delete and operator delete[], are
  11413. // described completely in 3.7.3. The attributes and restrictions
  11414. // found in the rest of this subclause do not apply to them unless
  11415. // explicitly stated in 3.7.3.
  11416. if (Op == OO_Delete || Op == OO_Array_Delete)
  11417. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11418. if (Op == OO_New || Op == OO_Array_New)
  11419. return CheckOperatorNewDeclaration(*this, FnDecl);
  11420. // C++ [over.oper]p6:
  11421. // An operator function shall either be a non-static member
  11422. // function or be a non-member function and have at least one
  11423. // parameter whose type is a class, a reference to a class, an
  11424. // enumeration, or a reference to an enumeration.
  11425. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11426. if (MethodDecl->isStatic())
  11427. return Diag(FnDecl->getLocation(),
  11428. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11429. } else {
  11430. bool ClassOrEnumParam = false;
  11431. for (auto Param : FnDecl->parameters()) {
  11432. QualType ParamType = Param->getType().getNonReferenceType();
  11433. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11434. ParamType->isEnumeralType()) {
  11435. ClassOrEnumParam = true;
  11436. break;
  11437. }
  11438. }
  11439. if (!ClassOrEnumParam)
  11440. return Diag(FnDecl->getLocation(),
  11441. diag::err_operator_overload_needs_class_or_enum)
  11442. << FnDecl->getDeclName();
  11443. }
  11444. // C++ [over.oper]p8:
  11445. // An operator function cannot have default arguments (8.3.6),
  11446. // except where explicitly stated below.
  11447. //
  11448. // Only the function-call operator allows default arguments
  11449. // (C++ [over.call]p1).
  11450. if (Op != OO_Call) {
  11451. for (auto Param : FnDecl->parameters()) {
  11452. if (Param->hasDefaultArg())
  11453. return Diag(Param->getLocation(),
  11454. diag::err_operator_overload_default_arg)
  11455. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11456. }
  11457. }
  11458. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11459. { false, false, false }
  11460. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11461. , { Unary, Binary, MemberOnly }
  11462. #include "clang/Basic/OperatorKinds.def"
  11463. };
  11464. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11465. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11466. bool MustBeMemberOperator = OperatorUses[Op][2];
  11467. // C++ [over.oper]p8:
  11468. // [...] Operator functions cannot have more or fewer parameters
  11469. // than the number required for the corresponding operator, as
  11470. // described in the rest of this subclause.
  11471. unsigned NumParams = FnDecl->getNumParams()
  11472. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11473. if (Op != OO_Call &&
  11474. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11475. (NumParams == 2 && !CanBeBinaryOperator) ||
  11476. (NumParams < 1) || (NumParams > 2))) {
  11477. // We have the wrong number of parameters.
  11478. unsigned ErrorKind;
  11479. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11480. ErrorKind = 2; // 2 -> unary or binary.
  11481. } else if (CanBeUnaryOperator) {
  11482. ErrorKind = 0; // 0 -> unary
  11483. } else {
  11484. assert(CanBeBinaryOperator &&
  11485. "All non-call overloaded operators are unary or binary!");
  11486. ErrorKind = 1; // 1 -> binary
  11487. }
  11488. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11489. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11490. }
  11491. // Overloaded operators other than operator() cannot be variadic.
  11492. if (Op != OO_Call &&
  11493. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11494. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11495. << FnDecl->getDeclName();
  11496. }
  11497. // Some operators must be non-static member functions.
  11498. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11499. return Diag(FnDecl->getLocation(),
  11500. diag::err_operator_overload_must_be_member)
  11501. << FnDecl->getDeclName();
  11502. }
  11503. // C++ [over.inc]p1:
  11504. // The user-defined function called operator++ implements the
  11505. // prefix and postfix ++ operator. If this function is a member
  11506. // function with no parameters, or a non-member function with one
  11507. // parameter of class or enumeration type, it defines the prefix
  11508. // increment operator ++ for objects of that type. If the function
  11509. // is a member function with one parameter (which shall be of type
  11510. // int) or a non-member function with two parameters (the second
  11511. // of which shall be of type int), it defines the postfix
  11512. // increment operator ++ for objects of that type.
  11513. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11514. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11515. QualType ParamType = LastParam->getType();
  11516. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11517. !ParamType->isDependentType())
  11518. return Diag(LastParam->getLocation(),
  11519. diag::err_operator_overload_post_incdec_must_be_int)
  11520. << LastParam->getType() << (Op == OO_MinusMinus);
  11521. }
  11522. return false;
  11523. }
  11524. static bool
  11525. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11526. FunctionTemplateDecl *TpDecl) {
  11527. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11528. // Must have one or two template parameters.
  11529. if (TemplateParams->size() == 1) {
  11530. NonTypeTemplateParmDecl *PmDecl =
  11531. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11532. // The template parameter must be a char parameter pack.
  11533. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11534. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11535. return false;
  11536. } else if (TemplateParams->size() == 2) {
  11537. TemplateTypeParmDecl *PmType =
  11538. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11539. NonTypeTemplateParmDecl *PmArgs =
  11540. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11541. // The second template parameter must be a parameter pack with the
  11542. // first template parameter as its type.
  11543. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11544. PmArgs->isTemplateParameterPack()) {
  11545. const TemplateTypeParmType *TArgs =
  11546. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11547. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11548. TArgs->getIndex() == PmType->getIndex()) {
  11549. if (!SemaRef.inTemplateInstantiation())
  11550. SemaRef.Diag(TpDecl->getLocation(),
  11551. diag::ext_string_literal_operator_template);
  11552. return false;
  11553. }
  11554. }
  11555. }
  11556. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11557. diag::err_literal_operator_template)
  11558. << TpDecl->getTemplateParameters()->getSourceRange();
  11559. return true;
  11560. }
  11561. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11562. /// of this literal operator function is well-formed. If so, returns
  11563. /// false; otherwise, emits appropriate diagnostics and returns true.
  11564. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11565. if (isa<CXXMethodDecl>(FnDecl)) {
  11566. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11567. << FnDecl->getDeclName();
  11568. return true;
  11569. }
  11570. if (FnDecl->isExternC()) {
  11571. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11572. if (const LinkageSpecDecl *LSD =
  11573. FnDecl->getDeclContext()->getExternCContext())
  11574. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11575. return true;
  11576. }
  11577. // This might be the definition of a literal operator template.
  11578. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11579. // This might be a specialization of a literal operator template.
  11580. if (!TpDecl)
  11581. TpDecl = FnDecl->getPrimaryTemplate();
  11582. // template <char...> type operator "" name() and
  11583. // template <class T, T...> type operator "" name() are the only valid
  11584. // template signatures, and the only valid signatures with no parameters.
  11585. if (TpDecl) {
  11586. if (FnDecl->param_size() != 0) {
  11587. Diag(FnDecl->getLocation(),
  11588. diag::err_literal_operator_template_with_params);
  11589. return true;
  11590. }
  11591. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11592. return true;
  11593. } else if (FnDecl->param_size() == 1) {
  11594. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11595. QualType ParamType = Param->getType().getUnqualifiedType();
  11596. // Only unsigned long long int, long double, any character type, and const
  11597. // char * are allowed as the only parameters.
  11598. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11599. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11600. Context.hasSameType(ParamType, Context.CharTy) ||
  11601. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11602. Context.hasSameType(ParamType, Context.Char8Ty) ||
  11603. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11604. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11605. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11606. QualType InnerType = Ptr->getPointeeType();
  11607. // Pointer parameter must be a const char *.
  11608. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  11609. Context.CharTy) &&
  11610. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  11611. Diag(Param->getSourceRange().getBegin(),
  11612. diag::err_literal_operator_param)
  11613. << ParamType << "'const char *'" << Param->getSourceRange();
  11614. return true;
  11615. }
  11616. } else if (ParamType->isRealFloatingType()) {
  11617. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11618. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  11619. return true;
  11620. } else if (ParamType->isIntegerType()) {
  11621. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11622. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  11623. return true;
  11624. } else {
  11625. Diag(Param->getSourceRange().getBegin(),
  11626. diag::err_literal_operator_invalid_param)
  11627. << ParamType << Param->getSourceRange();
  11628. return true;
  11629. }
  11630. } else if (FnDecl->param_size() == 2) {
  11631. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  11632. // First, verify that the first parameter is correct.
  11633. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  11634. // Two parameter function must have a pointer to const as a
  11635. // first parameter; let's strip those qualifiers.
  11636. const PointerType *PT = FirstParamType->getAs<PointerType>();
  11637. if (!PT) {
  11638. Diag((*Param)->getSourceRange().getBegin(),
  11639. diag::err_literal_operator_param)
  11640. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11641. return true;
  11642. }
  11643. QualType PointeeType = PT->getPointeeType();
  11644. // First parameter must be const
  11645. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  11646. Diag((*Param)->getSourceRange().getBegin(),
  11647. diag::err_literal_operator_param)
  11648. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11649. return true;
  11650. }
  11651. QualType InnerType = PointeeType.getUnqualifiedType();
  11652. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  11653. // const char32_t* are allowed as the first parameter to a two-parameter
  11654. // function
  11655. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  11656. Context.hasSameType(InnerType, Context.WideCharTy) ||
  11657. Context.hasSameType(InnerType, Context.Char8Ty) ||
  11658. Context.hasSameType(InnerType, Context.Char16Ty) ||
  11659. Context.hasSameType(InnerType, Context.Char32Ty))) {
  11660. Diag((*Param)->getSourceRange().getBegin(),
  11661. diag::err_literal_operator_param)
  11662. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11663. return true;
  11664. }
  11665. // Move on to the second and final parameter.
  11666. ++Param;
  11667. // The second parameter must be a std::size_t.
  11668. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  11669. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  11670. Diag((*Param)->getSourceRange().getBegin(),
  11671. diag::err_literal_operator_param)
  11672. << SecondParamType << Context.getSizeType()
  11673. << (*Param)->getSourceRange();
  11674. return true;
  11675. }
  11676. } else {
  11677. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  11678. return true;
  11679. }
  11680. // Parameters are good.
  11681. // A parameter-declaration-clause containing a default argument is not
  11682. // equivalent to any of the permitted forms.
  11683. for (auto Param : FnDecl->parameters()) {
  11684. if (Param->hasDefaultArg()) {
  11685. Diag(Param->getDefaultArgRange().getBegin(),
  11686. diag::err_literal_operator_default_argument)
  11687. << Param->getDefaultArgRange();
  11688. break;
  11689. }
  11690. }
  11691. StringRef LiteralName
  11692. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  11693. if (LiteralName[0] != '_' &&
  11694. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  11695. // C++11 [usrlit.suffix]p1:
  11696. // Literal suffix identifiers that do not start with an underscore
  11697. // are reserved for future standardization.
  11698. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  11699. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  11700. }
  11701. return false;
  11702. }
  11703. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  11704. /// linkage specification, including the language and (if present)
  11705. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  11706. /// language string literal. LBraceLoc, if valid, provides the location of
  11707. /// the '{' brace. Otherwise, this linkage specification does not
  11708. /// have any braces.
  11709. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  11710. Expr *LangStr,
  11711. SourceLocation LBraceLoc) {
  11712. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  11713. if (!Lit->isAscii()) {
  11714. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  11715. << LangStr->getSourceRange();
  11716. return nullptr;
  11717. }
  11718. StringRef Lang = Lit->getString();
  11719. LinkageSpecDecl::LanguageIDs Language;
  11720. if (Lang == "C")
  11721. Language = LinkageSpecDecl::lang_c;
  11722. else if (Lang == "C++")
  11723. Language = LinkageSpecDecl::lang_cxx;
  11724. else {
  11725. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  11726. << LangStr->getSourceRange();
  11727. return nullptr;
  11728. }
  11729. // FIXME: Add all the various semantics of linkage specifications
  11730. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  11731. LangStr->getExprLoc(), Language,
  11732. LBraceLoc.isValid());
  11733. CurContext->addDecl(D);
  11734. PushDeclContext(S, D);
  11735. return D;
  11736. }
  11737. /// ActOnFinishLinkageSpecification - Complete the definition of
  11738. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  11739. /// valid, it's the position of the closing '}' brace in a linkage
  11740. /// specification that uses braces.
  11741. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  11742. Decl *LinkageSpec,
  11743. SourceLocation RBraceLoc) {
  11744. if (RBraceLoc.isValid()) {
  11745. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  11746. LSDecl->setRBraceLoc(RBraceLoc);
  11747. }
  11748. PopDeclContext();
  11749. return LinkageSpec;
  11750. }
  11751. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  11752. const ParsedAttributesView &AttrList,
  11753. SourceLocation SemiLoc) {
  11754. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  11755. // Attribute declarations appertain to empty declaration so we handle
  11756. // them here.
  11757. ProcessDeclAttributeList(S, ED, AttrList);
  11758. CurContext->addDecl(ED);
  11759. return ED;
  11760. }
  11761. /// Perform semantic analysis for the variable declaration that
  11762. /// occurs within a C++ catch clause, returning the newly-created
  11763. /// variable.
  11764. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  11765. TypeSourceInfo *TInfo,
  11766. SourceLocation StartLoc,
  11767. SourceLocation Loc,
  11768. IdentifierInfo *Name) {
  11769. bool Invalid = false;
  11770. QualType ExDeclType = TInfo->getType();
  11771. // Arrays and functions decay.
  11772. if (ExDeclType->isArrayType())
  11773. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  11774. else if (ExDeclType->isFunctionType())
  11775. ExDeclType = Context.getPointerType(ExDeclType);
  11776. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  11777. // The exception-declaration shall not denote a pointer or reference to an
  11778. // incomplete type, other than [cv] void*.
  11779. // N2844 forbids rvalue references.
  11780. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  11781. Diag(Loc, diag::err_catch_rvalue_ref);
  11782. Invalid = true;
  11783. }
  11784. if (ExDeclType->isVariablyModifiedType()) {
  11785. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  11786. Invalid = true;
  11787. }
  11788. QualType BaseType = ExDeclType;
  11789. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  11790. unsigned DK = diag::err_catch_incomplete;
  11791. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  11792. BaseType = Ptr->getPointeeType();
  11793. Mode = 1;
  11794. DK = diag::err_catch_incomplete_ptr;
  11795. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  11796. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  11797. BaseType = Ref->getPointeeType();
  11798. Mode = 2;
  11799. DK = diag::err_catch_incomplete_ref;
  11800. }
  11801. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  11802. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  11803. Invalid = true;
  11804. if (!Invalid && !ExDeclType->isDependentType() &&
  11805. RequireNonAbstractType(Loc, ExDeclType,
  11806. diag::err_abstract_type_in_decl,
  11807. AbstractVariableType))
  11808. Invalid = true;
  11809. // Only the non-fragile NeXT runtime currently supports C++ catches
  11810. // of ObjC types, and no runtime supports catching ObjC types by value.
  11811. if (!Invalid && getLangOpts().ObjC1) {
  11812. QualType T = ExDeclType;
  11813. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  11814. T = RT->getPointeeType();
  11815. if (T->isObjCObjectType()) {
  11816. Diag(Loc, diag::err_objc_object_catch);
  11817. Invalid = true;
  11818. } else if (T->isObjCObjectPointerType()) {
  11819. // FIXME: should this be a test for macosx-fragile specifically?
  11820. if (getLangOpts().ObjCRuntime.isFragile())
  11821. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  11822. }
  11823. }
  11824. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  11825. ExDeclType, TInfo, SC_None);
  11826. ExDecl->setExceptionVariable(true);
  11827. // In ARC, infer 'retaining' for variables of retainable type.
  11828. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  11829. Invalid = true;
  11830. if (!Invalid && !ExDeclType->isDependentType()) {
  11831. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  11832. // Insulate this from anything else we might currently be parsing.
  11833. EnterExpressionEvaluationContext scope(
  11834. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  11835. // C++ [except.handle]p16:
  11836. // The object declared in an exception-declaration or, if the
  11837. // exception-declaration does not specify a name, a temporary (12.2) is
  11838. // copy-initialized (8.5) from the exception object. [...]
  11839. // The object is destroyed when the handler exits, after the destruction
  11840. // of any automatic objects initialized within the handler.
  11841. //
  11842. // We just pretend to initialize the object with itself, then make sure
  11843. // it can be destroyed later.
  11844. QualType initType = Context.getExceptionObjectType(ExDeclType);
  11845. InitializedEntity entity =
  11846. InitializedEntity::InitializeVariable(ExDecl);
  11847. InitializationKind initKind =
  11848. InitializationKind::CreateCopy(Loc, SourceLocation());
  11849. Expr *opaqueValue =
  11850. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  11851. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  11852. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  11853. if (result.isInvalid())
  11854. Invalid = true;
  11855. else {
  11856. // If the constructor used was non-trivial, set this as the
  11857. // "initializer".
  11858. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  11859. if (!construct->getConstructor()->isTrivial()) {
  11860. Expr *init = MaybeCreateExprWithCleanups(construct);
  11861. ExDecl->setInit(init);
  11862. }
  11863. // And make sure it's destructable.
  11864. FinalizeVarWithDestructor(ExDecl, recordType);
  11865. }
  11866. }
  11867. }
  11868. if (Invalid)
  11869. ExDecl->setInvalidDecl();
  11870. return ExDecl;
  11871. }
  11872. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  11873. /// handler.
  11874. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  11875. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11876. bool Invalid = D.isInvalidType();
  11877. // Check for unexpanded parameter packs.
  11878. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11879. UPPC_ExceptionType)) {
  11880. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  11881. D.getIdentifierLoc());
  11882. Invalid = true;
  11883. }
  11884. IdentifierInfo *II = D.getIdentifier();
  11885. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  11886. LookupOrdinaryName,
  11887. ForVisibleRedeclaration)) {
  11888. // The scope should be freshly made just for us. There is just no way
  11889. // it contains any previous declaration, except for function parameters in
  11890. // a function-try-block's catch statement.
  11891. assert(!S->isDeclScope(PrevDecl));
  11892. if (isDeclInScope(PrevDecl, CurContext, S)) {
  11893. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  11894. << D.getIdentifier();
  11895. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11896. Invalid = true;
  11897. } else if (PrevDecl->isTemplateParameter())
  11898. // Maybe we will complain about the shadowed template parameter.
  11899. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11900. }
  11901. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  11902. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  11903. << D.getCXXScopeSpec().getRange();
  11904. Invalid = true;
  11905. }
  11906. VarDecl *ExDecl = BuildExceptionDeclaration(
  11907. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  11908. if (Invalid)
  11909. ExDecl->setInvalidDecl();
  11910. // Add the exception declaration into this scope.
  11911. if (II)
  11912. PushOnScopeChains(ExDecl, S);
  11913. else
  11914. CurContext->addDecl(ExDecl);
  11915. ProcessDeclAttributes(S, ExDecl, D);
  11916. return ExDecl;
  11917. }
  11918. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11919. Expr *AssertExpr,
  11920. Expr *AssertMessageExpr,
  11921. SourceLocation RParenLoc) {
  11922. StringLiteral *AssertMessage =
  11923. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  11924. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  11925. return nullptr;
  11926. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  11927. AssertMessage, RParenLoc, false);
  11928. }
  11929. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11930. Expr *AssertExpr,
  11931. StringLiteral *AssertMessage,
  11932. SourceLocation RParenLoc,
  11933. bool Failed) {
  11934. assert(AssertExpr != nullptr && "Expected non-null condition");
  11935. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  11936. !Failed) {
  11937. // In a static_assert-declaration, the constant-expression shall be a
  11938. // constant expression that can be contextually converted to bool.
  11939. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  11940. if (Converted.isInvalid())
  11941. Failed = true;
  11942. llvm::APSInt Cond;
  11943. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  11944. diag::err_static_assert_expression_is_not_constant,
  11945. /*AllowFold=*/false).isInvalid())
  11946. Failed = true;
  11947. if (!Failed && !Cond) {
  11948. SmallString<256> MsgBuffer;
  11949. llvm::raw_svector_ostream Msg(MsgBuffer);
  11950. if (AssertMessage)
  11951. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  11952. Expr *InnerCond = nullptr;
  11953. std::string InnerCondDescription;
  11954. std::tie(InnerCond, InnerCondDescription) =
  11955. findFailedBooleanCondition(Converted.get(),
  11956. /*AllowTopLevelCond=*/false);
  11957. if (InnerCond) {
  11958. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  11959. << InnerCondDescription << !AssertMessage
  11960. << Msg.str() << InnerCond->getSourceRange();
  11961. } else {
  11962. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  11963. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  11964. }
  11965. Failed = true;
  11966. }
  11967. }
  11968. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  11969. /*DiscardedValue*/false,
  11970. /*IsConstexpr*/true);
  11971. if (FullAssertExpr.isInvalid())
  11972. Failed = true;
  11973. else
  11974. AssertExpr = FullAssertExpr.get();
  11975. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  11976. AssertExpr, AssertMessage, RParenLoc,
  11977. Failed);
  11978. CurContext->addDecl(Decl);
  11979. return Decl;
  11980. }
  11981. /// Perform semantic analysis of the given friend type declaration.
  11982. ///
  11983. /// \returns A friend declaration that.
  11984. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  11985. SourceLocation FriendLoc,
  11986. TypeSourceInfo *TSInfo) {
  11987. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  11988. QualType T = TSInfo->getType();
  11989. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  11990. // C++03 [class.friend]p2:
  11991. // An elaborated-type-specifier shall be used in a friend declaration
  11992. // for a class.*
  11993. //
  11994. // * The class-key of the elaborated-type-specifier is required.
  11995. if (!CodeSynthesisContexts.empty()) {
  11996. // Do not complain about the form of friend template types during any kind
  11997. // of code synthesis. For template instantiation, we will have complained
  11998. // when the template was defined.
  11999. } else {
  12000. if (!T->isElaboratedTypeSpecifier()) {
  12001. // If we evaluated the type to a record type, suggest putting
  12002. // a tag in front.
  12003. if (const RecordType *RT = T->getAs<RecordType>()) {
  12004. RecordDecl *RD = RT->getDecl();
  12005. SmallString<16> InsertionText(" ");
  12006. InsertionText += RD->getKindName();
  12007. Diag(TypeRange.getBegin(),
  12008. getLangOpts().CPlusPlus11 ?
  12009. diag::warn_cxx98_compat_unelaborated_friend_type :
  12010. diag::ext_unelaborated_friend_type)
  12011. << (unsigned) RD->getTagKind()
  12012. << T
  12013. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12014. InsertionText);
  12015. } else {
  12016. Diag(FriendLoc,
  12017. getLangOpts().CPlusPlus11 ?
  12018. diag::warn_cxx98_compat_nonclass_type_friend :
  12019. diag::ext_nonclass_type_friend)
  12020. << T
  12021. << TypeRange;
  12022. }
  12023. } else if (T->getAs<EnumType>()) {
  12024. Diag(FriendLoc,
  12025. getLangOpts().CPlusPlus11 ?
  12026. diag::warn_cxx98_compat_enum_friend :
  12027. diag::ext_enum_friend)
  12028. << T
  12029. << TypeRange;
  12030. }
  12031. // C++11 [class.friend]p3:
  12032. // A friend declaration that does not declare a function shall have one
  12033. // of the following forms:
  12034. // friend elaborated-type-specifier ;
  12035. // friend simple-type-specifier ;
  12036. // friend typename-specifier ;
  12037. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12038. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12039. }
  12040. // If the type specifier in a friend declaration designates a (possibly
  12041. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12042. // the friend declaration is ignored.
  12043. return FriendDecl::Create(Context, CurContext,
  12044. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12045. FriendLoc);
  12046. }
  12047. /// Handle a friend tag declaration where the scope specifier was
  12048. /// templated.
  12049. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12050. unsigned TagSpec, SourceLocation TagLoc,
  12051. CXXScopeSpec &SS, IdentifierInfo *Name,
  12052. SourceLocation NameLoc,
  12053. const ParsedAttributesView &Attr,
  12054. MultiTemplateParamsArg TempParamLists) {
  12055. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12056. bool IsMemberSpecialization = false;
  12057. bool Invalid = false;
  12058. if (TemplateParameterList *TemplateParams =
  12059. MatchTemplateParametersToScopeSpecifier(
  12060. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12061. IsMemberSpecialization, Invalid)) {
  12062. if (TemplateParams->size() > 0) {
  12063. // This is a declaration of a class template.
  12064. if (Invalid)
  12065. return nullptr;
  12066. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12067. NameLoc, Attr, TemplateParams, AS_public,
  12068. /*ModulePrivateLoc=*/SourceLocation(),
  12069. FriendLoc, TempParamLists.size() - 1,
  12070. TempParamLists.data()).get();
  12071. } else {
  12072. // The "template<>" header is extraneous.
  12073. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12074. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12075. IsMemberSpecialization = true;
  12076. }
  12077. }
  12078. if (Invalid) return nullptr;
  12079. bool isAllExplicitSpecializations = true;
  12080. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12081. if (TempParamLists[I]->size()) {
  12082. isAllExplicitSpecializations = false;
  12083. break;
  12084. }
  12085. }
  12086. // FIXME: don't ignore attributes.
  12087. // If it's explicit specializations all the way down, just forget
  12088. // about the template header and build an appropriate non-templated
  12089. // friend. TODO: for source fidelity, remember the headers.
  12090. if (isAllExplicitSpecializations) {
  12091. if (SS.isEmpty()) {
  12092. bool Owned = false;
  12093. bool IsDependent = false;
  12094. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12095. Attr, AS_public,
  12096. /*ModulePrivateLoc=*/SourceLocation(),
  12097. MultiTemplateParamsArg(), Owned, IsDependent,
  12098. /*ScopedEnumKWLoc=*/SourceLocation(),
  12099. /*ScopedEnumUsesClassTag=*/false,
  12100. /*UnderlyingType=*/TypeResult(),
  12101. /*IsTypeSpecifier=*/false,
  12102. /*IsTemplateParamOrArg=*/false);
  12103. }
  12104. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12105. ElaboratedTypeKeyword Keyword
  12106. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12107. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12108. *Name, NameLoc);
  12109. if (T.isNull())
  12110. return nullptr;
  12111. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12112. if (isa<DependentNameType>(T)) {
  12113. DependentNameTypeLoc TL =
  12114. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12115. TL.setElaboratedKeywordLoc(TagLoc);
  12116. TL.setQualifierLoc(QualifierLoc);
  12117. TL.setNameLoc(NameLoc);
  12118. } else {
  12119. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12120. TL.setElaboratedKeywordLoc(TagLoc);
  12121. TL.setQualifierLoc(QualifierLoc);
  12122. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12123. }
  12124. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12125. TSI, FriendLoc, TempParamLists);
  12126. Friend->setAccess(AS_public);
  12127. CurContext->addDecl(Friend);
  12128. return Friend;
  12129. }
  12130. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12131. // Handle the case of a templated-scope friend class. e.g.
  12132. // template <class T> class A<T>::B;
  12133. // FIXME: we don't support these right now.
  12134. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12135. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12136. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12137. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12138. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12139. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12140. TL.setElaboratedKeywordLoc(TagLoc);
  12141. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12142. TL.setNameLoc(NameLoc);
  12143. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12144. TSI, FriendLoc, TempParamLists);
  12145. Friend->setAccess(AS_public);
  12146. Friend->setUnsupportedFriend(true);
  12147. CurContext->addDecl(Friend);
  12148. return Friend;
  12149. }
  12150. /// Handle a friend type declaration. This works in tandem with
  12151. /// ActOnTag.
  12152. ///
  12153. /// Notes on friend class templates:
  12154. ///
  12155. /// We generally treat friend class declarations as if they were
  12156. /// declaring a class. So, for example, the elaborated type specifier
  12157. /// in a friend declaration is required to obey the restrictions of a
  12158. /// class-head (i.e. no typedefs in the scope chain), template
  12159. /// parameters are required to match up with simple template-ids, &c.
  12160. /// However, unlike when declaring a template specialization, it's
  12161. /// okay to refer to a template specialization without an empty
  12162. /// template parameter declaration, e.g.
  12163. /// friend class A<T>::B<unsigned>;
  12164. /// We permit this as a special case; if there are any template
  12165. /// parameters present at all, require proper matching, i.e.
  12166. /// template <> template \<class T> friend class A<int>::B;
  12167. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12168. MultiTemplateParamsArg TempParams) {
  12169. SourceLocation Loc = DS.getBeginLoc();
  12170. assert(DS.isFriendSpecified());
  12171. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12172. // C++ [class.friend]p3:
  12173. // A friend declaration that does not declare a function shall have one of
  12174. // the following forms:
  12175. // friend elaborated-type-specifier ;
  12176. // friend simple-type-specifier ;
  12177. // friend typename-specifier ;
  12178. //
  12179. // Any declaration with a type qualifier does not have that form. (It's
  12180. // legal to specify a qualified type as a friend, you just can't write the
  12181. // keywords.)
  12182. if (DS.getTypeQualifiers()) {
  12183. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12184. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12185. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12186. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12187. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12188. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12189. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12190. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12191. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12192. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12193. }
  12194. // Try to convert the decl specifier to a type. This works for
  12195. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12196. // for a TUK_Friend.
  12197. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12198. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12199. QualType T = TSI->getType();
  12200. if (TheDeclarator.isInvalidType())
  12201. return nullptr;
  12202. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12203. return nullptr;
  12204. // This is definitely an error in C++98. It's probably meant to
  12205. // be forbidden in C++0x, too, but the specification is just
  12206. // poorly written.
  12207. //
  12208. // The problem is with declarations like the following:
  12209. // template <T> friend A<T>::foo;
  12210. // where deciding whether a class C is a friend or not now hinges
  12211. // on whether there exists an instantiation of A that causes
  12212. // 'foo' to equal C. There are restrictions on class-heads
  12213. // (which we declare (by fiat) elaborated friend declarations to
  12214. // be) that makes this tractable.
  12215. //
  12216. // FIXME: handle "template <> friend class A<T>;", which
  12217. // is possibly well-formed? Who even knows?
  12218. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12219. Diag(Loc, diag::err_tagless_friend_type_template)
  12220. << DS.getSourceRange();
  12221. return nullptr;
  12222. }
  12223. // C++98 [class.friend]p1: A friend of a class is a function
  12224. // or class that is not a member of the class . . .
  12225. // This is fixed in DR77, which just barely didn't make the C++03
  12226. // deadline. It's also a very silly restriction that seriously
  12227. // affects inner classes and which nobody else seems to implement;
  12228. // thus we never diagnose it, not even in -pedantic.
  12229. //
  12230. // But note that we could warn about it: it's always useless to
  12231. // friend one of your own members (it's not, however, worthless to
  12232. // friend a member of an arbitrary specialization of your template).
  12233. Decl *D;
  12234. if (!TempParams.empty())
  12235. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12236. TempParams,
  12237. TSI,
  12238. DS.getFriendSpecLoc());
  12239. else
  12240. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12241. if (!D)
  12242. return nullptr;
  12243. D->setAccess(AS_public);
  12244. CurContext->addDecl(D);
  12245. return D;
  12246. }
  12247. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12248. MultiTemplateParamsArg TemplateParams) {
  12249. const DeclSpec &DS = D.getDeclSpec();
  12250. assert(DS.isFriendSpecified());
  12251. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12252. SourceLocation Loc = D.getIdentifierLoc();
  12253. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12254. // C++ [class.friend]p1
  12255. // A friend of a class is a function or class....
  12256. // Note that this sees through typedefs, which is intended.
  12257. // It *doesn't* see through dependent types, which is correct
  12258. // according to [temp.arg.type]p3:
  12259. // If a declaration acquires a function type through a
  12260. // type dependent on a template-parameter and this causes
  12261. // a declaration that does not use the syntactic form of a
  12262. // function declarator to have a function type, the program
  12263. // is ill-formed.
  12264. if (!TInfo->getType()->isFunctionType()) {
  12265. Diag(Loc, diag::err_unexpected_friend);
  12266. // It might be worthwhile to try to recover by creating an
  12267. // appropriate declaration.
  12268. return nullptr;
  12269. }
  12270. // C++ [namespace.memdef]p3
  12271. // - If a friend declaration in a non-local class first declares a
  12272. // class or function, the friend class or function is a member
  12273. // of the innermost enclosing namespace.
  12274. // - The name of the friend is not found by simple name lookup
  12275. // until a matching declaration is provided in that namespace
  12276. // scope (either before or after the class declaration granting
  12277. // friendship).
  12278. // - If a friend function is called, its name may be found by the
  12279. // name lookup that considers functions from namespaces and
  12280. // classes associated with the types of the function arguments.
  12281. // - When looking for a prior declaration of a class or a function
  12282. // declared as a friend, scopes outside the innermost enclosing
  12283. // namespace scope are not considered.
  12284. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12285. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12286. DeclarationName Name = NameInfo.getName();
  12287. assert(Name);
  12288. // Check for unexpanded parameter packs.
  12289. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12290. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12291. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12292. return nullptr;
  12293. // The context we found the declaration in, or in which we should
  12294. // create the declaration.
  12295. DeclContext *DC;
  12296. Scope *DCScope = S;
  12297. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12298. ForExternalRedeclaration);
  12299. // There are five cases here.
  12300. // - There's no scope specifier and we're in a local class. Only look
  12301. // for functions declared in the immediately-enclosing block scope.
  12302. // We recover from invalid scope qualifiers as if they just weren't there.
  12303. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12304. if ((SS.isInvalid() || !SS.isSet()) &&
  12305. (FunctionContainingLocalClass =
  12306. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12307. // C++11 [class.friend]p11:
  12308. // If a friend declaration appears in a local class and the name
  12309. // specified is an unqualified name, a prior declaration is
  12310. // looked up without considering scopes that are outside the
  12311. // innermost enclosing non-class scope. For a friend function
  12312. // declaration, if there is no prior declaration, the program is
  12313. // ill-formed.
  12314. // Find the innermost enclosing non-class scope. This is the block
  12315. // scope containing the local class definition (or for a nested class,
  12316. // the outer local class).
  12317. DCScope = S->getFnParent();
  12318. // Look up the function name in the scope.
  12319. Previous.clear(LookupLocalFriendName);
  12320. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12321. if (!Previous.empty()) {
  12322. // All possible previous declarations must have the same context:
  12323. // either they were declared at block scope or they are members of
  12324. // one of the enclosing local classes.
  12325. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12326. } else {
  12327. // This is ill-formed, but provide the context that we would have
  12328. // declared the function in, if we were permitted to, for error recovery.
  12329. DC = FunctionContainingLocalClass;
  12330. }
  12331. adjustContextForLocalExternDecl(DC);
  12332. // C++ [class.friend]p6:
  12333. // A function can be defined in a friend declaration of a class if and
  12334. // only if the class is a non-local class (9.8), the function name is
  12335. // unqualified, and the function has namespace scope.
  12336. if (D.isFunctionDefinition()) {
  12337. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12338. }
  12339. // - There's no scope specifier, in which case we just go to the
  12340. // appropriate scope and look for a function or function template
  12341. // there as appropriate.
  12342. } else if (SS.isInvalid() || !SS.isSet()) {
  12343. // C++11 [namespace.memdef]p3:
  12344. // If the name in a friend declaration is neither qualified nor
  12345. // a template-id and the declaration is a function or an
  12346. // elaborated-type-specifier, the lookup to determine whether
  12347. // the entity has been previously declared shall not consider
  12348. // any scopes outside the innermost enclosing namespace.
  12349. bool isTemplateId =
  12350. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12351. // Find the appropriate context according to the above.
  12352. DC = CurContext;
  12353. // Skip class contexts. If someone can cite chapter and verse
  12354. // for this behavior, that would be nice --- it's what GCC and
  12355. // EDG do, and it seems like a reasonable intent, but the spec
  12356. // really only says that checks for unqualified existing
  12357. // declarations should stop at the nearest enclosing namespace,
  12358. // not that they should only consider the nearest enclosing
  12359. // namespace.
  12360. while (DC->isRecord())
  12361. DC = DC->getParent();
  12362. DeclContext *LookupDC = DC;
  12363. while (LookupDC->isTransparentContext())
  12364. LookupDC = LookupDC->getParent();
  12365. while (true) {
  12366. LookupQualifiedName(Previous, LookupDC);
  12367. if (!Previous.empty()) {
  12368. DC = LookupDC;
  12369. break;
  12370. }
  12371. if (isTemplateId) {
  12372. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12373. } else {
  12374. if (LookupDC->isFileContext()) break;
  12375. }
  12376. LookupDC = LookupDC->getParent();
  12377. }
  12378. DCScope = getScopeForDeclContext(S, DC);
  12379. // - There's a non-dependent scope specifier, in which case we
  12380. // compute it and do a previous lookup there for a function
  12381. // or function template.
  12382. } else if (!SS.getScopeRep()->isDependent()) {
  12383. DC = computeDeclContext(SS);
  12384. if (!DC) return nullptr;
  12385. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12386. LookupQualifiedName(Previous, DC);
  12387. // Ignore things found implicitly in the wrong scope.
  12388. // TODO: better diagnostics for this case. Suggesting the right
  12389. // qualified scope would be nice...
  12390. LookupResult::Filter F = Previous.makeFilter();
  12391. while (F.hasNext()) {
  12392. NamedDecl *D = F.next();
  12393. if (!DC->InEnclosingNamespaceSetOf(
  12394. D->getDeclContext()->getRedeclContext()))
  12395. F.erase();
  12396. }
  12397. F.done();
  12398. if (Previous.empty()) {
  12399. D.setInvalidType();
  12400. Diag(Loc, diag::err_qualified_friend_not_found)
  12401. << Name << TInfo->getType();
  12402. return nullptr;
  12403. }
  12404. // C++ [class.friend]p1: A friend of a class is a function or
  12405. // class that is not a member of the class . . .
  12406. if (DC->Equals(CurContext))
  12407. Diag(DS.getFriendSpecLoc(),
  12408. getLangOpts().CPlusPlus11 ?
  12409. diag::warn_cxx98_compat_friend_is_member :
  12410. diag::err_friend_is_member);
  12411. if (D.isFunctionDefinition()) {
  12412. // C++ [class.friend]p6:
  12413. // A function can be defined in a friend declaration of a class if and
  12414. // only if the class is a non-local class (9.8), the function name is
  12415. // unqualified, and the function has namespace scope.
  12416. SemaDiagnosticBuilder DB
  12417. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12418. DB << SS.getScopeRep();
  12419. if (DC->isFileContext())
  12420. DB << FixItHint::CreateRemoval(SS.getRange());
  12421. SS.clear();
  12422. }
  12423. // - There's a scope specifier that does not match any template
  12424. // parameter lists, in which case we use some arbitrary context,
  12425. // create a method or method template, and wait for instantiation.
  12426. // - There's a scope specifier that does match some template
  12427. // parameter lists, which we don't handle right now.
  12428. } else {
  12429. if (D.isFunctionDefinition()) {
  12430. // C++ [class.friend]p6:
  12431. // A function can be defined in a friend declaration of a class if and
  12432. // only if the class is a non-local class (9.8), the function name is
  12433. // unqualified, and the function has namespace scope.
  12434. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12435. << SS.getScopeRep();
  12436. }
  12437. DC = CurContext;
  12438. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12439. }
  12440. if (!DC->isRecord()) {
  12441. int DiagArg = -1;
  12442. switch (D.getName().getKind()) {
  12443. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12444. case UnqualifiedIdKind::IK_ConstructorName:
  12445. DiagArg = 0;
  12446. break;
  12447. case UnqualifiedIdKind::IK_DestructorName:
  12448. DiagArg = 1;
  12449. break;
  12450. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12451. DiagArg = 2;
  12452. break;
  12453. case UnqualifiedIdKind::IK_DeductionGuideName:
  12454. DiagArg = 3;
  12455. break;
  12456. case UnqualifiedIdKind::IK_Identifier:
  12457. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12458. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12459. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12460. case UnqualifiedIdKind::IK_TemplateId:
  12461. break;
  12462. }
  12463. // This implies that it has to be an operator or function.
  12464. if (DiagArg >= 0) {
  12465. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12466. return nullptr;
  12467. }
  12468. }
  12469. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12470. // does not contain the declaration context, i.e., in an out-of-line
  12471. // definition of a class.
  12472. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12473. if (!DCScope) {
  12474. FakeDCScope.setEntity(DC);
  12475. DCScope = &FakeDCScope;
  12476. }
  12477. bool AddToScope = true;
  12478. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12479. TemplateParams, AddToScope);
  12480. if (!ND) return nullptr;
  12481. assert(ND->getLexicalDeclContext() == CurContext);
  12482. // If we performed typo correction, we might have added a scope specifier
  12483. // and changed the decl context.
  12484. DC = ND->getDeclContext();
  12485. // Add the function declaration to the appropriate lookup tables,
  12486. // adjusting the redeclarations list as necessary. We don't
  12487. // want to do this yet if the friending class is dependent.
  12488. //
  12489. // Also update the scope-based lookup if the target context's
  12490. // lookup context is in lexical scope.
  12491. if (!CurContext->isDependentContext()) {
  12492. DC = DC->getRedeclContext();
  12493. DC->makeDeclVisibleInContext(ND);
  12494. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12495. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12496. }
  12497. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12498. D.getIdentifierLoc(), ND,
  12499. DS.getFriendSpecLoc());
  12500. FrD->setAccess(AS_public);
  12501. CurContext->addDecl(FrD);
  12502. if (ND->isInvalidDecl()) {
  12503. FrD->setInvalidDecl();
  12504. } else {
  12505. if (DC->isRecord()) CheckFriendAccess(ND);
  12506. FunctionDecl *FD;
  12507. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12508. FD = FTD->getTemplatedDecl();
  12509. else
  12510. FD = cast<FunctionDecl>(ND);
  12511. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12512. // default argument expression, that declaration shall be a definition
  12513. // and shall be the only declaration of the function or function
  12514. // template in the translation unit.
  12515. if (functionDeclHasDefaultArgument(FD)) {
  12516. // We can't look at FD->getPreviousDecl() because it may not have been set
  12517. // if we're in a dependent context. If the function is known to be a
  12518. // redeclaration, we will have narrowed Previous down to the right decl.
  12519. if (D.isRedeclaration()) {
  12520. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12521. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12522. diag::note_previous_declaration);
  12523. } else if (!D.isFunctionDefinition())
  12524. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12525. }
  12526. // Mark templated-scope function declarations as unsupported.
  12527. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12528. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12529. << SS.getScopeRep() << SS.getRange()
  12530. << cast<CXXRecordDecl>(CurContext);
  12531. FrD->setUnsupportedFriend(true);
  12532. }
  12533. }
  12534. return ND;
  12535. }
  12536. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12537. AdjustDeclIfTemplate(Dcl);
  12538. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12539. if (!Fn) {
  12540. Diag(DelLoc, diag::err_deleted_non_function);
  12541. return;
  12542. }
  12543. // Deleted function does not have a body.
  12544. Fn->setWillHaveBody(false);
  12545. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12546. // Don't consider the implicit declaration we generate for explicit
  12547. // specializations. FIXME: Do not generate these implicit declarations.
  12548. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12549. Prev->getPreviousDecl()) &&
  12550. !Prev->isDefined()) {
  12551. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12552. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12553. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12554. : diag::note_previous_declaration);
  12555. }
  12556. // If the declaration wasn't the first, we delete the function anyway for
  12557. // recovery.
  12558. Fn = Fn->getCanonicalDecl();
  12559. }
  12560. // dllimport/dllexport cannot be deleted.
  12561. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12562. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12563. Fn->setInvalidDecl();
  12564. }
  12565. if (Fn->isDeleted())
  12566. return;
  12567. // See if we're deleting a function which is already known to override a
  12568. // non-deleted virtual function.
  12569. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12570. bool IssuedDiagnostic = false;
  12571. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12572. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12573. if (!IssuedDiagnostic) {
  12574. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12575. IssuedDiagnostic = true;
  12576. }
  12577. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12578. }
  12579. }
  12580. // If this function was implicitly deleted because it was defaulted,
  12581. // explain why it was deleted.
  12582. if (IssuedDiagnostic && MD->isDefaulted())
  12583. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12584. /*Diagnose*/true);
  12585. }
  12586. // C++11 [basic.start.main]p3:
  12587. // A program that defines main as deleted [...] is ill-formed.
  12588. if (Fn->isMain())
  12589. Diag(DelLoc, diag::err_deleted_main);
  12590. // C++11 [dcl.fct.def.delete]p4:
  12591. // A deleted function is implicitly inline.
  12592. Fn->setImplicitlyInline();
  12593. Fn->setDeletedAsWritten();
  12594. }
  12595. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12596. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12597. if (MD) {
  12598. if (MD->getParent()->isDependentType()) {
  12599. MD->setDefaulted();
  12600. MD->setExplicitlyDefaulted();
  12601. return;
  12602. }
  12603. CXXSpecialMember Member = getSpecialMember(MD);
  12604. if (Member == CXXInvalid) {
  12605. if (!MD->isInvalidDecl())
  12606. Diag(DefaultLoc, diag::err_default_special_members);
  12607. return;
  12608. }
  12609. MD->setDefaulted();
  12610. MD->setExplicitlyDefaulted();
  12611. // Unset that we will have a body for this function. We might not,
  12612. // if it turns out to be trivial, and we don't need this marking now
  12613. // that we've marked it as defaulted.
  12614. MD->setWillHaveBody(false);
  12615. // If this definition appears within the record, do the checking when
  12616. // the record is complete.
  12617. const FunctionDecl *Primary = MD;
  12618. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  12619. // Ask the template instantiation pattern that actually had the
  12620. // '= default' on it.
  12621. Primary = Pattern;
  12622. // If the method was defaulted on its first declaration, we will have
  12623. // already performed the checking in CheckCompletedCXXClass. Such a
  12624. // declaration doesn't trigger an implicit definition.
  12625. if (Primary->getCanonicalDecl()->isDefaulted())
  12626. return;
  12627. CheckExplicitlyDefaultedSpecialMember(MD);
  12628. if (!MD->isInvalidDecl())
  12629. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  12630. } else {
  12631. Diag(DefaultLoc, diag::err_default_special_members);
  12632. }
  12633. }
  12634. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  12635. for (Stmt *SubStmt : S->children()) {
  12636. if (!SubStmt)
  12637. continue;
  12638. if (isa<ReturnStmt>(SubStmt))
  12639. Self.Diag(SubStmt->getBeginLoc(),
  12640. diag::err_return_in_constructor_handler);
  12641. if (!isa<Expr>(SubStmt))
  12642. SearchForReturnInStmt(Self, SubStmt);
  12643. }
  12644. }
  12645. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  12646. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  12647. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  12648. SearchForReturnInStmt(*this, Handler);
  12649. }
  12650. }
  12651. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  12652. const CXXMethodDecl *Old) {
  12653. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  12654. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  12655. if (OldFT->hasExtParameterInfos()) {
  12656. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  12657. // A parameter of the overriding method should be annotated with noescape
  12658. // if the corresponding parameter of the overridden method is annotated.
  12659. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  12660. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  12661. Diag(New->getParamDecl(I)->getLocation(),
  12662. diag::warn_overriding_method_missing_noescape);
  12663. Diag(Old->getParamDecl(I)->getLocation(),
  12664. diag::note_overridden_marked_noescape);
  12665. }
  12666. }
  12667. // Virtual overrides must have the same code_seg.
  12668. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  12669. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  12670. if ((NewCSA || OldCSA) &&
  12671. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  12672. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  12673. Diag(Old->getLocation(), diag::note_previous_declaration);
  12674. return true;
  12675. }
  12676. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  12677. // If the calling conventions match, everything is fine
  12678. if (NewCC == OldCC)
  12679. return false;
  12680. // If the calling conventions mismatch because the new function is static,
  12681. // suppress the calling convention mismatch error; the error about static
  12682. // function override (err_static_overrides_virtual from
  12683. // Sema::CheckFunctionDeclaration) is more clear.
  12684. if (New->getStorageClass() == SC_Static)
  12685. return false;
  12686. Diag(New->getLocation(),
  12687. diag::err_conflicting_overriding_cc_attributes)
  12688. << New->getDeclName() << New->getType() << Old->getType();
  12689. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  12690. return true;
  12691. }
  12692. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  12693. const CXXMethodDecl *Old) {
  12694. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  12695. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  12696. if (Context.hasSameType(NewTy, OldTy) ||
  12697. NewTy->isDependentType() || OldTy->isDependentType())
  12698. return false;
  12699. // Check if the return types are covariant
  12700. QualType NewClassTy, OldClassTy;
  12701. /// Both types must be pointers or references to classes.
  12702. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  12703. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  12704. NewClassTy = NewPT->getPointeeType();
  12705. OldClassTy = OldPT->getPointeeType();
  12706. }
  12707. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  12708. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  12709. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  12710. NewClassTy = NewRT->getPointeeType();
  12711. OldClassTy = OldRT->getPointeeType();
  12712. }
  12713. }
  12714. }
  12715. // The return types aren't either both pointers or references to a class type.
  12716. if (NewClassTy.isNull()) {
  12717. Diag(New->getLocation(),
  12718. diag::err_different_return_type_for_overriding_virtual_function)
  12719. << New->getDeclName() << NewTy << OldTy
  12720. << New->getReturnTypeSourceRange();
  12721. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12722. << Old->getReturnTypeSourceRange();
  12723. return true;
  12724. }
  12725. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  12726. // C++14 [class.virtual]p8:
  12727. // If the class type in the covariant return type of D::f differs from
  12728. // that of B::f, the class type in the return type of D::f shall be
  12729. // complete at the point of declaration of D::f or shall be the class
  12730. // type D.
  12731. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  12732. if (!RT->isBeingDefined() &&
  12733. RequireCompleteType(New->getLocation(), NewClassTy,
  12734. diag::err_covariant_return_incomplete,
  12735. New->getDeclName()))
  12736. return true;
  12737. }
  12738. // Check if the new class derives from the old class.
  12739. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  12740. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  12741. << New->getDeclName() << NewTy << OldTy
  12742. << New->getReturnTypeSourceRange();
  12743. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12744. << Old->getReturnTypeSourceRange();
  12745. return true;
  12746. }
  12747. // Check if we the conversion from derived to base is valid.
  12748. if (CheckDerivedToBaseConversion(
  12749. NewClassTy, OldClassTy,
  12750. diag::err_covariant_return_inaccessible_base,
  12751. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  12752. New->getLocation(), New->getReturnTypeSourceRange(),
  12753. New->getDeclName(), nullptr)) {
  12754. // FIXME: this note won't trigger for delayed access control
  12755. // diagnostics, and it's impossible to get an undelayed error
  12756. // here from access control during the original parse because
  12757. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  12758. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12759. << Old->getReturnTypeSourceRange();
  12760. return true;
  12761. }
  12762. }
  12763. // The qualifiers of the return types must be the same.
  12764. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  12765. Diag(New->getLocation(),
  12766. diag::err_covariant_return_type_different_qualifications)
  12767. << New->getDeclName() << NewTy << OldTy
  12768. << New->getReturnTypeSourceRange();
  12769. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12770. << Old->getReturnTypeSourceRange();
  12771. return true;
  12772. }
  12773. // The new class type must have the same or less qualifiers as the old type.
  12774. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  12775. Diag(New->getLocation(),
  12776. diag::err_covariant_return_type_class_type_more_qualified)
  12777. << New->getDeclName() << NewTy << OldTy
  12778. << New->getReturnTypeSourceRange();
  12779. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12780. << Old->getReturnTypeSourceRange();
  12781. return true;
  12782. }
  12783. return false;
  12784. }
  12785. /// Mark the given method pure.
  12786. ///
  12787. /// \param Method the method to be marked pure.
  12788. ///
  12789. /// \param InitRange the source range that covers the "0" initializer.
  12790. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  12791. SourceLocation EndLoc = InitRange.getEnd();
  12792. if (EndLoc.isValid())
  12793. Method->setRangeEnd(EndLoc);
  12794. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  12795. Method->setPure();
  12796. return false;
  12797. }
  12798. if (!Method->isInvalidDecl())
  12799. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  12800. << Method->getDeclName() << InitRange;
  12801. return true;
  12802. }
  12803. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  12804. if (D->getFriendObjectKind())
  12805. Diag(D->getLocation(), diag::err_pure_friend);
  12806. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  12807. CheckPureMethod(M, ZeroLoc);
  12808. else
  12809. Diag(D->getLocation(), diag::err_illegal_initializer);
  12810. }
  12811. /// Determine whether the given declaration is a global variable or
  12812. /// static data member.
  12813. static bool isNonlocalVariable(const Decl *D) {
  12814. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  12815. return Var->hasGlobalStorage();
  12816. return false;
  12817. }
  12818. /// Invoked when we are about to parse an initializer for the declaration
  12819. /// 'Dcl'.
  12820. ///
  12821. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  12822. /// static data member of class X, names should be looked up in the scope of
  12823. /// class X. If the declaration had a scope specifier, a scope will have
  12824. /// been created and passed in for this purpose. Otherwise, S will be null.
  12825. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  12826. // If there is no declaration, there was an error parsing it.
  12827. if (!D || D->isInvalidDecl())
  12828. return;
  12829. // We will always have a nested name specifier here, but this declaration
  12830. // might not be out of line if the specifier names the current namespace:
  12831. // extern int n;
  12832. // int ::n = 0;
  12833. if (S && D->isOutOfLine())
  12834. EnterDeclaratorContext(S, D->getDeclContext());
  12835. // If we are parsing the initializer for a static data member, push a
  12836. // new expression evaluation context that is associated with this static
  12837. // data member.
  12838. if (isNonlocalVariable(D))
  12839. PushExpressionEvaluationContext(
  12840. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  12841. }
  12842. /// Invoked after we are finished parsing an initializer for the declaration D.
  12843. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  12844. // If there is no declaration, there was an error parsing it.
  12845. if (!D || D->isInvalidDecl())
  12846. return;
  12847. if (isNonlocalVariable(D))
  12848. PopExpressionEvaluationContext();
  12849. if (S && D->isOutOfLine())
  12850. ExitDeclaratorContext(S);
  12851. }
  12852. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  12853. /// C++ if/switch/while/for statement.
  12854. /// e.g: "if (int x = f()) {...}"
  12855. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  12856. // C++ 6.4p2:
  12857. // The declarator shall not specify a function or an array.
  12858. // The type-specifier-seq shall not contain typedef and shall not declare a
  12859. // new class or enumeration.
  12860. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  12861. "Parser allowed 'typedef' as storage class of condition decl.");
  12862. Decl *Dcl = ActOnDeclarator(S, D);
  12863. if (!Dcl)
  12864. return true;
  12865. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  12866. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  12867. << D.getSourceRange();
  12868. return true;
  12869. }
  12870. return Dcl;
  12871. }
  12872. void Sema::LoadExternalVTableUses() {
  12873. if (!ExternalSource)
  12874. return;
  12875. SmallVector<ExternalVTableUse, 4> VTables;
  12876. ExternalSource->ReadUsedVTables(VTables);
  12877. SmallVector<VTableUse, 4> NewUses;
  12878. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  12879. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  12880. = VTablesUsed.find(VTables[I].Record);
  12881. // Even if a definition wasn't required before, it may be required now.
  12882. if (Pos != VTablesUsed.end()) {
  12883. if (!Pos->second && VTables[I].DefinitionRequired)
  12884. Pos->second = true;
  12885. continue;
  12886. }
  12887. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  12888. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  12889. }
  12890. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  12891. }
  12892. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  12893. bool DefinitionRequired) {
  12894. // Ignore any vtable uses in unevaluated operands or for classes that do
  12895. // not have a vtable.
  12896. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  12897. CurContext->isDependentContext() || isUnevaluatedContext())
  12898. return;
  12899. // Do not mark as used if compiling for the device outside of the target
  12900. // region.
  12901. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  12902. !isInOpenMPDeclareTargetContext() &&
  12903. !isInOpenMPTargetExecutionDirective())
  12904. return;
  12905. // Try to insert this class into the map.
  12906. LoadExternalVTableUses();
  12907. Class = Class->getCanonicalDecl();
  12908. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  12909. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  12910. if (!Pos.second) {
  12911. // If we already had an entry, check to see if we are promoting this vtable
  12912. // to require a definition. If so, we need to reappend to the VTableUses
  12913. // list, since we may have already processed the first entry.
  12914. if (DefinitionRequired && !Pos.first->second) {
  12915. Pos.first->second = true;
  12916. } else {
  12917. // Otherwise, we can early exit.
  12918. return;
  12919. }
  12920. } else {
  12921. // The Microsoft ABI requires that we perform the destructor body
  12922. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  12923. // the deleting destructor is emitted with the vtable, not with the
  12924. // destructor definition as in the Itanium ABI.
  12925. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12926. CXXDestructorDecl *DD = Class->getDestructor();
  12927. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  12928. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  12929. // If this is an out-of-line declaration, marking it referenced will
  12930. // not do anything. Manually call CheckDestructor to look up operator
  12931. // delete().
  12932. ContextRAII SavedContext(*this, DD);
  12933. CheckDestructor(DD);
  12934. } else {
  12935. MarkFunctionReferenced(Loc, Class->getDestructor());
  12936. }
  12937. }
  12938. }
  12939. }
  12940. // Local classes need to have their virtual members marked
  12941. // immediately. For all other classes, we mark their virtual members
  12942. // at the end of the translation unit.
  12943. if (Class->isLocalClass())
  12944. MarkVirtualMembersReferenced(Loc, Class);
  12945. else
  12946. VTableUses.push_back(std::make_pair(Class, Loc));
  12947. }
  12948. bool Sema::DefineUsedVTables() {
  12949. LoadExternalVTableUses();
  12950. if (VTableUses.empty())
  12951. return false;
  12952. // Note: The VTableUses vector could grow as a result of marking
  12953. // the members of a class as "used", so we check the size each
  12954. // time through the loop and prefer indices (which are stable) to
  12955. // iterators (which are not).
  12956. bool DefinedAnything = false;
  12957. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  12958. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  12959. if (!Class)
  12960. continue;
  12961. TemplateSpecializationKind ClassTSK =
  12962. Class->getTemplateSpecializationKind();
  12963. SourceLocation Loc = VTableUses[I].second;
  12964. bool DefineVTable = true;
  12965. // If this class has a key function, but that key function is
  12966. // defined in another translation unit, we don't need to emit the
  12967. // vtable even though we're using it.
  12968. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  12969. if (KeyFunction && !KeyFunction->hasBody()) {
  12970. // The key function is in another translation unit.
  12971. DefineVTable = false;
  12972. TemplateSpecializationKind TSK =
  12973. KeyFunction->getTemplateSpecializationKind();
  12974. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  12975. TSK != TSK_ImplicitInstantiation &&
  12976. "Instantiations don't have key functions");
  12977. (void)TSK;
  12978. } else if (!KeyFunction) {
  12979. // If we have a class with no key function that is the subject
  12980. // of an explicit instantiation declaration, suppress the
  12981. // vtable; it will live with the explicit instantiation
  12982. // definition.
  12983. bool IsExplicitInstantiationDeclaration =
  12984. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  12985. for (auto R : Class->redecls()) {
  12986. TemplateSpecializationKind TSK
  12987. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  12988. if (TSK == TSK_ExplicitInstantiationDeclaration)
  12989. IsExplicitInstantiationDeclaration = true;
  12990. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  12991. IsExplicitInstantiationDeclaration = false;
  12992. break;
  12993. }
  12994. }
  12995. if (IsExplicitInstantiationDeclaration)
  12996. DefineVTable = false;
  12997. }
  12998. // The exception specifications for all virtual members may be needed even
  12999. // if we are not providing an authoritative form of the vtable in this TU.
  13000. // We may choose to emit it available_externally anyway.
  13001. if (!DefineVTable) {
  13002. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13003. continue;
  13004. }
  13005. // Mark all of the virtual members of this class as referenced, so
  13006. // that we can build a vtable. Then, tell the AST consumer that a
  13007. // vtable for this class is required.
  13008. DefinedAnything = true;
  13009. MarkVirtualMembersReferenced(Loc, Class);
  13010. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13011. if (VTablesUsed[Canonical])
  13012. Consumer.HandleVTable(Class);
  13013. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13014. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13015. // that lack key functions, since the user won't be able to make one.
  13016. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13017. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13018. const FunctionDecl *KeyFunctionDef = nullptr;
  13019. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13020. KeyFunctionDef->isInlined())) {
  13021. Diag(Class->getLocation(),
  13022. ClassTSK == TSK_ExplicitInstantiationDefinition
  13023. ? diag::warn_weak_template_vtable
  13024. : diag::warn_weak_vtable)
  13025. << Class;
  13026. }
  13027. }
  13028. }
  13029. VTableUses.clear();
  13030. return DefinedAnything;
  13031. }
  13032. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13033. const CXXRecordDecl *RD) {
  13034. for (const auto *I : RD->methods())
  13035. if (I->isVirtual() && !I->isPure())
  13036. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13037. }
  13038. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13039. const CXXRecordDecl *RD) {
  13040. // Mark all functions which will appear in RD's vtable as used.
  13041. CXXFinalOverriderMap FinalOverriders;
  13042. RD->getFinalOverriders(FinalOverriders);
  13043. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13044. E = FinalOverriders.end();
  13045. I != E; ++I) {
  13046. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13047. OE = I->second.end();
  13048. OI != OE; ++OI) {
  13049. assert(OI->second.size() > 0 && "no final overrider");
  13050. CXXMethodDecl *Overrider = OI->second.front().Method;
  13051. // C++ [basic.def.odr]p2:
  13052. // [...] A virtual member function is used if it is not pure. [...]
  13053. if (!Overrider->isPure())
  13054. MarkFunctionReferenced(Loc, Overrider);
  13055. }
  13056. }
  13057. // Only classes that have virtual bases need a VTT.
  13058. if (RD->getNumVBases() == 0)
  13059. return;
  13060. for (const auto &I : RD->bases()) {
  13061. const CXXRecordDecl *Base =
  13062. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  13063. if (Base->getNumVBases() == 0)
  13064. continue;
  13065. MarkVirtualMembersReferenced(Loc, Base);
  13066. }
  13067. }
  13068. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13069. /// Objective-C implementation whose ivars need be initialized.
  13070. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13071. if (!getLangOpts().CPlusPlus)
  13072. return;
  13073. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13074. SmallVector<ObjCIvarDecl*, 8> ivars;
  13075. CollectIvarsToConstructOrDestruct(OID, ivars);
  13076. if (ivars.empty())
  13077. return;
  13078. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13079. for (unsigned i = 0; i < ivars.size(); i++) {
  13080. FieldDecl *Field = ivars[i];
  13081. if (Field->isInvalidDecl())
  13082. continue;
  13083. CXXCtorInitializer *Member;
  13084. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13085. InitializationKind InitKind =
  13086. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13087. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13088. ExprResult MemberInit =
  13089. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13090. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13091. // Note, MemberInit could actually come back empty if no initialization
  13092. // is required (e.g., because it would call a trivial default constructor)
  13093. if (!MemberInit.get() || MemberInit.isInvalid())
  13094. continue;
  13095. Member =
  13096. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13097. SourceLocation(),
  13098. MemberInit.getAs<Expr>(),
  13099. SourceLocation());
  13100. AllToInit.push_back(Member);
  13101. // Be sure that the destructor is accessible and is marked as referenced.
  13102. if (const RecordType *RecordTy =
  13103. Context.getBaseElementType(Field->getType())
  13104. ->getAs<RecordType>()) {
  13105. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13106. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13107. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13108. CheckDestructorAccess(Field->getLocation(), Destructor,
  13109. PDiag(diag::err_access_dtor_ivar)
  13110. << Context.getBaseElementType(Field->getType()));
  13111. }
  13112. }
  13113. }
  13114. ObjCImplementation->setIvarInitializers(Context,
  13115. AllToInit.data(), AllToInit.size());
  13116. }
  13117. }
  13118. static
  13119. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13120. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13121. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13122. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13123. Sema &S) {
  13124. if (Ctor->isInvalidDecl())
  13125. return;
  13126. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13127. // Target may not be determinable yet, for instance if this is a dependent
  13128. // call in an uninstantiated template.
  13129. if (Target) {
  13130. const FunctionDecl *FNTarget = nullptr;
  13131. (void)Target->hasBody(FNTarget);
  13132. Target = const_cast<CXXConstructorDecl*>(
  13133. cast_or_null<CXXConstructorDecl>(FNTarget));
  13134. }
  13135. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13136. // Avoid dereferencing a null pointer here.
  13137. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13138. if (!Current.insert(Canonical).second)
  13139. return;
  13140. // We know that beyond here, we aren't chaining into a cycle.
  13141. if (!Target || !Target->isDelegatingConstructor() ||
  13142. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13143. Valid.insert(Current.begin(), Current.end());
  13144. Current.clear();
  13145. // We've hit a cycle.
  13146. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13147. Current.count(TCanonical)) {
  13148. // If we haven't diagnosed this cycle yet, do so now.
  13149. if (!Invalid.count(TCanonical)) {
  13150. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13151. diag::warn_delegating_ctor_cycle)
  13152. << Ctor;
  13153. // Don't add a note for a function delegating directly to itself.
  13154. if (TCanonical != Canonical)
  13155. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13156. CXXConstructorDecl *C = Target;
  13157. while (C->getCanonicalDecl() != Canonical) {
  13158. const FunctionDecl *FNTarget = nullptr;
  13159. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13160. assert(FNTarget && "Ctor cycle through bodiless function");
  13161. C = const_cast<CXXConstructorDecl*>(
  13162. cast<CXXConstructorDecl>(FNTarget));
  13163. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13164. }
  13165. }
  13166. Invalid.insert(Current.begin(), Current.end());
  13167. Current.clear();
  13168. } else {
  13169. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13170. }
  13171. }
  13172. void Sema::CheckDelegatingCtorCycles() {
  13173. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13174. for (DelegatingCtorDeclsType::iterator
  13175. I = DelegatingCtorDecls.begin(ExternalSource),
  13176. E = DelegatingCtorDecls.end();
  13177. I != E; ++I)
  13178. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13179. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13180. (*CI)->setInvalidDecl();
  13181. }
  13182. namespace {
  13183. /// AST visitor that finds references to the 'this' expression.
  13184. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13185. Sema &S;
  13186. public:
  13187. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13188. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13189. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13190. << E->isImplicit();
  13191. return false;
  13192. }
  13193. };
  13194. }
  13195. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13196. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13197. if (!TSInfo)
  13198. return false;
  13199. TypeLoc TL = TSInfo->getTypeLoc();
  13200. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13201. if (!ProtoTL)
  13202. return false;
  13203. // C++11 [expr.prim.general]p3:
  13204. // [The expression this] shall not appear before the optional
  13205. // cv-qualifier-seq and it shall not appear within the declaration of a
  13206. // static member function (although its type and value category are defined
  13207. // within a static member function as they are within a non-static member
  13208. // function). [ Note: this is because declaration matching does not occur
  13209. // until the complete declarator is known. - end note ]
  13210. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13211. FindCXXThisExpr Finder(*this);
  13212. // If the return type came after the cv-qualifier-seq, check it now.
  13213. if (Proto->hasTrailingReturn() &&
  13214. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13215. return true;
  13216. // Check the exception specification.
  13217. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13218. return true;
  13219. return checkThisInStaticMemberFunctionAttributes(Method);
  13220. }
  13221. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13222. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13223. if (!TSInfo)
  13224. return false;
  13225. TypeLoc TL = TSInfo->getTypeLoc();
  13226. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13227. if (!ProtoTL)
  13228. return false;
  13229. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13230. FindCXXThisExpr Finder(*this);
  13231. switch (Proto->getExceptionSpecType()) {
  13232. case EST_Unparsed:
  13233. case EST_Uninstantiated:
  13234. case EST_Unevaluated:
  13235. case EST_BasicNoexcept:
  13236. case EST_DynamicNone:
  13237. case EST_MSAny:
  13238. case EST_None:
  13239. break;
  13240. case EST_DependentNoexcept:
  13241. case EST_NoexceptFalse:
  13242. case EST_NoexceptTrue:
  13243. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13244. return true;
  13245. LLVM_FALLTHROUGH;
  13246. case EST_Dynamic:
  13247. for (const auto &E : Proto->exceptions()) {
  13248. if (!Finder.TraverseType(E))
  13249. return true;
  13250. }
  13251. break;
  13252. }
  13253. return false;
  13254. }
  13255. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13256. FindCXXThisExpr Finder(*this);
  13257. // Check attributes.
  13258. for (const auto *A : Method->attrs()) {
  13259. // FIXME: This should be emitted by tblgen.
  13260. Expr *Arg = nullptr;
  13261. ArrayRef<Expr *> Args;
  13262. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13263. Arg = G->getArg();
  13264. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13265. Arg = G->getArg();
  13266. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13267. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13268. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13269. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13270. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13271. Arg = ETLF->getSuccessValue();
  13272. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13273. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13274. Arg = STLF->getSuccessValue();
  13275. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13276. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13277. Arg = LR->getArg();
  13278. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13279. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13280. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13281. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13282. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13283. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13284. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13285. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13286. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13287. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13288. if (Arg && !Finder.TraverseStmt(Arg))
  13289. return true;
  13290. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13291. if (!Finder.TraverseStmt(Args[I]))
  13292. return true;
  13293. }
  13294. }
  13295. return false;
  13296. }
  13297. void Sema::checkExceptionSpecification(
  13298. bool IsTopLevel, ExceptionSpecificationType EST,
  13299. ArrayRef<ParsedType> DynamicExceptions,
  13300. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13301. SmallVectorImpl<QualType> &Exceptions,
  13302. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13303. Exceptions.clear();
  13304. ESI.Type = EST;
  13305. if (EST == EST_Dynamic) {
  13306. Exceptions.reserve(DynamicExceptions.size());
  13307. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13308. // FIXME: Preserve type source info.
  13309. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13310. if (IsTopLevel) {
  13311. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13312. collectUnexpandedParameterPacks(ET, Unexpanded);
  13313. if (!Unexpanded.empty()) {
  13314. DiagnoseUnexpandedParameterPacks(
  13315. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13316. Unexpanded);
  13317. continue;
  13318. }
  13319. }
  13320. // Check that the type is valid for an exception spec, and
  13321. // drop it if not.
  13322. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13323. Exceptions.push_back(ET);
  13324. }
  13325. ESI.Exceptions = Exceptions;
  13326. return;
  13327. }
  13328. if (isComputedNoexcept(EST)) {
  13329. assert((NoexceptExpr->isTypeDependent() ||
  13330. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13331. Context.BoolTy) &&
  13332. "Parser should have made sure that the expression is boolean");
  13333. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13334. ESI.Type = EST_BasicNoexcept;
  13335. return;
  13336. }
  13337. ESI.NoexceptExpr = NoexceptExpr;
  13338. return;
  13339. }
  13340. }
  13341. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13342. ExceptionSpecificationType EST,
  13343. SourceRange SpecificationRange,
  13344. ArrayRef<ParsedType> DynamicExceptions,
  13345. ArrayRef<SourceRange> DynamicExceptionRanges,
  13346. Expr *NoexceptExpr) {
  13347. if (!MethodD)
  13348. return;
  13349. // Dig out the method we're referring to.
  13350. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13351. MethodD = FunTmpl->getTemplatedDecl();
  13352. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13353. if (!Method)
  13354. return;
  13355. // Check the exception specification.
  13356. llvm::SmallVector<QualType, 4> Exceptions;
  13357. FunctionProtoType::ExceptionSpecInfo ESI;
  13358. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13359. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13360. ESI);
  13361. // Update the exception specification on the function type.
  13362. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13363. if (Method->isStatic())
  13364. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13365. if (Method->isVirtual()) {
  13366. // Check overrides, which we previously had to delay.
  13367. for (const CXXMethodDecl *O : Method->overridden_methods())
  13368. CheckOverridingFunctionExceptionSpec(Method, O);
  13369. }
  13370. }
  13371. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13372. ///
  13373. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13374. SourceLocation DeclStart, Declarator &D,
  13375. Expr *BitWidth,
  13376. InClassInitStyle InitStyle,
  13377. AccessSpecifier AS,
  13378. const ParsedAttr &MSPropertyAttr) {
  13379. IdentifierInfo *II = D.getIdentifier();
  13380. if (!II) {
  13381. Diag(DeclStart, diag::err_anonymous_property);
  13382. return nullptr;
  13383. }
  13384. SourceLocation Loc = D.getIdentifierLoc();
  13385. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13386. QualType T = TInfo->getType();
  13387. if (getLangOpts().CPlusPlus) {
  13388. CheckExtraCXXDefaultArguments(D);
  13389. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13390. UPPC_DataMemberType)) {
  13391. D.setInvalidType();
  13392. T = Context.IntTy;
  13393. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13394. }
  13395. }
  13396. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13397. if (D.getDeclSpec().isInlineSpecified())
  13398. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13399. << getLangOpts().CPlusPlus17;
  13400. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13401. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13402. diag::err_invalid_thread)
  13403. << DeclSpec::getSpecifierName(TSCS);
  13404. // Check to see if this name was declared as a member previously
  13405. NamedDecl *PrevDecl = nullptr;
  13406. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13407. ForVisibleRedeclaration);
  13408. LookupName(Previous, S);
  13409. switch (Previous.getResultKind()) {
  13410. case LookupResult::Found:
  13411. case LookupResult::FoundUnresolvedValue:
  13412. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13413. break;
  13414. case LookupResult::FoundOverloaded:
  13415. PrevDecl = Previous.getRepresentativeDecl();
  13416. break;
  13417. case LookupResult::NotFound:
  13418. case LookupResult::NotFoundInCurrentInstantiation:
  13419. case LookupResult::Ambiguous:
  13420. break;
  13421. }
  13422. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13423. // Maybe we will complain about the shadowed template parameter.
  13424. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13425. // Just pretend that we didn't see the previous declaration.
  13426. PrevDecl = nullptr;
  13427. }
  13428. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13429. PrevDecl = nullptr;
  13430. SourceLocation TSSL = D.getBeginLoc();
  13431. MSPropertyDecl *NewPD =
  13432. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13433. MSPropertyAttr.getPropertyDataGetter(),
  13434. MSPropertyAttr.getPropertyDataSetter());
  13435. ProcessDeclAttributes(TUScope, NewPD, D);
  13436. NewPD->setAccess(AS);
  13437. if (NewPD->isInvalidDecl())
  13438. Record->setInvalidDecl();
  13439. if (D.getDeclSpec().isModulePrivateSpecified())
  13440. NewPD->setModulePrivate();
  13441. if (NewPD->isInvalidDecl() && PrevDecl) {
  13442. // Don't introduce NewFD into scope; there's already something
  13443. // with the same name in the same scope.
  13444. } else if (II) {
  13445. PushOnScopeChains(NewPD, S);
  13446. } else
  13447. Record->addDecl(NewPD);
  13448. return NewPD;
  13449. }