SemaDeclCXX.cpp 606 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for C++ declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ComparisonCategories.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/AST/TypeLoc.h"
  25. #include "clang/AST/TypeOrdering.h"
  26. #include "clang/Basic/AttributeCommonInfo.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. case EST_NoThrow:
  175. return;
  176. // If we're still at noexcept(true) and there's a throw() callee,
  177. // change to that specification.
  178. case EST_DynamicNone:
  179. if (ComputedEST == EST_BasicNoexcept)
  180. ComputedEST = EST_DynamicNone;
  181. return;
  182. case EST_DependentNoexcept:
  183. llvm_unreachable(
  184. "should not generate implicit declarations for dependent cases");
  185. case EST_Dynamic:
  186. break;
  187. }
  188. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  189. assert(ComputedEST != EST_None &&
  190. "Shouldn't collect exceptions when throw-all is guaranteed.");
  191. ComputedEST = EST_Dynamic;
  192. // Record the exceptions in this function's exception specification.
  193. for (const auto &E : Proto->exceptions())
  194. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  195. Exceptions.push_back(E);
  196. }
  197. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  198. if (!E || ComputedEST == EST_MSAny)
  199. return;
  200. // FIXME:
  201. //
  202. // C++0x [except.spec]p14:
  203. // [An] implicit exception-specification specifies the type-id T if and
  204. // only if T is allowed by the exception-specification of a function directly
  205. // invoked by f's implicit definition; f shall allow all exceptions if any
  206. // function it directly invokes allows all exceptions, and f shall allow no
  207. // exceptions if every function it directly invokes allows no exceptions.
  208. //
  209. // Note in particular that if an implicit exception-specification is generated
  210. // for a function containing a throw-expression, that specification can still
  211. // be noexcept(true).
  212. //
  213. // Note also that 'directly invoked' is not defined in the standard, and there
  214. // is no indication that we should only consider potentially-evaluated calls.
  215. //
  216. // Ultimately we should implement the intent of the standard: the exception
  217. // specification should be the set of exceptions which can be thrown by the
  218. // implicit definition. For now, we assume that any non-nothrow expression can
  219. // throw any exception.
  220. if (Self->canThrow(E))
  221. ComputedEST = EST_None;
  222. }
  223. bool
  224. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  225. SourceLocation EqualLoc) {
  226. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  227. diag::err_typecheck_decl_incomplete_type)) {
  228. Param->setInvalidDecl();
  229. return true;
  230. }
  231. // C++ [dcl.fct.default]p5
  232. // A default argument expression is implicitly converted (clause
  233. // 4) to the parameter type. The default argument expression has
  234. // the same semantic constraints as the initializer expression in
  235. // a declaration of a variable of the parameter type, using the
  236. // copy-initialization semantics (8.5).
  237. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  238. Param);
  239. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  240. EqualLoc);
  241. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  242. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  243. if (Result.isInvalid())
  244. return true;
  245. Arg = Result.getAs<Expr>();
  246. CheckCompletedExpr(Arg, EqualLoc);
  247. Arg = MaybeCreateExprWithCleanups(Arg);
  248. // Okay: add the default argument to the parameter
  249. Param->setDefaultArg(Arg);
  250. // We have already instantiated this parameter; provide each of the
  251. // instantiations with the uninstantiated default argument.
  252. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  253. = UnparsedDefaultArgInstantiations.find(Param);
  254. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  255. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  256. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  257. // We're done tracking this parameter's instantiations.
  258. UnparsedDefaultArgInstantiations.erase(InstPos);
  259. }
  260. return false;
  261. }
  262. /// ActOnParamDefaultArgument - Check whether the default argument
  263. /// provided for a function parameter is well-formed. If so, attach it
  264. /// to the parameter declaration.
  265. void
  266. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  267. Expr *DefaultArg) {
  268. if (!param || !DefaultArg)
  269. return;
  270. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  271. UnparsedDefaultArgLocs.erase(Param);
  272. // Default arguments are only permitted in C++
  273. if (!getLangOpts().CPlusPlus) {
  274. Diag(EqualLoc, diag::err_param_default_argument)
  275. << DefaultArg->getSourceRange();
  276. Param->setInvalidDecl();
  277. return;
  278. }
  279. // Check for unexpanded parameter packs.
  280. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  281. Param->setInvalidDecl();
  282. return;
  283. }
  284. // C++11 [dcl.fct.default]p3
  285. // A default argument expression [...] shall not be specified for a
  286. // parameter pack.
  287. if (Param->isParameterPack()) {
  288. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  289. << DefaultArg->getSourceRange();
  290. return;
  291. }
  292. // Check that the default argument is well-formed
  293. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  294. if (DefaultArgChecker.Visit(DefaultArg)) {
  295. Param->setInvalidDecl();
  296. return;
  297. }
  298. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  299. }
  300. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  301. /// argument for a function parameter, but we can't parse it yet
  302. /// because we're inside a class definition. Note that this default
  303. /// argument will be parsed later.
  304. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  305. SourceLocation EqualLoc,
  306. SourceLocation ArgLoc) {
  307. if (!param)
  308. return;
  309. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  310. Param->setUnparsedDefaultArg();
  311. UnparsedDefaultArgLocs[Param] = ArgLoc;
  312. }
  313. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  314. /// the default argument for the parameter param failed.
  315. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  316. SourceLocation EqualLoc) {
  317. if (!param)
  318. return;
  319. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  320. Param->setInvalidDecl();
  321. UnparsedDefaultArgLocs.erase(Param);
  322. Param->setDefaultArg(new(Context)
  323. OpaqueValueExpr(EqualLoc,
  324. Param->getType().getNonReferenceType(),
  325. VK_RValue));
  326. }
  327. /// CheckExtraCXXDefaultArguments - Check for any extra default
  328. /// arguments in the declarator, which is not a function declaration
  329. /// or definition and therefore is not permitted to have default
  330. /// arguments. This routine should be invoked for every declarator
  331. /// that is not a function declaration or definition.
  332. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  333. // C++ [dcl.fct.default]p3
  334. // A default argument expression shall be specified only in the
  335. // parameter-declaration-clause of a function declaration or in a
  336. // template-parameter (14.1). It shall not be specified for a
  337. // parameter pack. If it is specified in a
  338. // parameter-declaration-clause, it shall not occur within a
  339. // declarator or abstract-declarator of a parameter-declaration.
  340. bool MightBeFunction = D.isFunctionDeclarationContext();
  341. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  342. DeclaratorChunk &chunk = D.getTypeObject(i);
  343. if (chunk.Kind == DeclaratorChunk::Function) {
  344. if (MightBeFunction) {
  345. // This is a function declaration. It can have default arguments, but
  346. // keep looking in case its return type is a function type with default
  347. // arguments.
  348. MightBeFunction = false;
  349. continue;
  350. }
  351. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  352. ++argIdx) {
  353. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  354. if (Param->hasUnparsedDefaultArg()) {
  355. std::unique_ptr<CachedTokens> Toks =
  356. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  357. SourceRange SR;
  358. if (Toks->size() > 1)
  359. SR = SourceRange((*Toks)[1].getLocation(),
  360. Toks->back().getLocation());
  361. else
  362. SR = UnparsedDefaultArgLocs[Param];
  363. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  364. << SR;
  365. } else if (Param->getDefaultArg()) {
  366. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  367. << Param->getDefaultArg()->getSourceRange();
  368. Param->setDefaultArg(nullptr);
  369. }
  370. }
  371. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  372. MightBeFunction = false;
  373. }
  374. }
  375. }
  376. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  377. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  378. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  379. if (!PVD->hasDefaultArg())
  380. return false;
  381. if (!PVD->hasInheritedDefaultArg())
  382. return true;
  383. }
  384. return false;
  385. }
  386. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  387. /// function, once we already know that they have the same
  388. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  389. /// error, false otherwise.
  390. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  391. Scope *S) {
  392. bool Invalid = false;
  393. // The declaration context corresponding to the scope is the semantic
  394. // parent, unless this is a local function declaration, in which case
  395. // it is that surrounding function.
  396. DeclContext *ScopeDC = New->isLocalExternDecl()
  397. ? New->getLexicalDeclContext()
  398. : New->getDeclContext();
  399. // Find the previous declaration for the purpose of default arguments.
  400. FunctionDecl *PrevForDefaultArgs = Old;
  401. for (/**/; PrevForDefaultArgs;
  402. // Don't bother looking back past the latest decl if this is a local
  403. // extern declaration; nothing else could work.
  404. PrevForDefaultArgs = New->isLocalExternDecl()
  405. ? nullptr
  406. : PrevForDefaultArgs->getPreviousDecl()) {
  407. // Ignore hidden declarations.
  408. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  409. continue;
  410. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  411. !New->isCXXClassMember()) {
  412. // Ignore default arguments of old decl if they are not in
  413. // the same scope and this is not an out-of-line definition of
  414. // a member function.
  415. continue;
  416. }
  417. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  418. // If only one of these is a local function declaration, then they are
  419. // declared in different scopes, even though isDeclInScope may think
  420. // they're in the same scope. (If both are local, the scope check is
  421. // sufficient, and if neither is local, then they are in the same scope.)
  422. continue;
  423. }
  424. // We found the right previous declaration.
  425. break;
  426. }
  427. // C++ [dcl.fct.default]p4:
  428. // For non-template functions, default arguments can be added in
  429. // later declarations of a function in the same
  430. // scope. Declarations in different scopes have completely
  431. // distinct sets of default arguments. That is, declarations in
  432. // inner scopes do not acquire default arguments from
  433. // declarations in outer scopes, and vice versa. In a given
  434. // function declaration, all parameters subsequent to a
  435. // parameter with a default argument shall have default
  436. // arguments supplied in this or previous declarations. A
  437. // default argument shall not be redefined by a later
  438. // declaration (not even to the same value).
  439. //
  440. // C++ [dcl.fct.default]p6:
  441. // Except for member functions of class templates, the default arguments
  442. // in a member function definition that appears outside of the class
  443. // definition are added to the set of default arguments provided by the
  444. // member function declaration in the class definition.
  445. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  446. ? PrevForDefaultArgs->getNumParams()
  447. : 0;
  448. p < NumParams; ++p) {
  449. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  450. ParmVarDecl *NewParam = New->getParamDecl(p);
  451. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  452. bool NewParamHasDfl = NewParam->hasDefaultArg();
  453. if (OldParamHasDfl && NewParamHasDfl) {
  454. unsigned DiagDefaultParamID =
  455. diag::err_param_default_argument_redefinition;
  456. // MSVC accepts that default parameters be redefined for member functions
  457. // of template class. The new default parameter's value is ignored.
  458. Invalid = true;
  459. if (getLangOpts().MicrosoftExt) {
  460. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  461. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  462. // Merge the old default argument into the new parameter.
  463. NewParam->setHasInheritedDefaultArg();
  464. if (OldParam->hasUninstantiatedDefaultArg())
  465. NewParam->setUninstantiatedDefaultArg(
  466. OldParam->getUninstantiatedDefaultArg());
  467. else
  468. NewParam->setDefaultArg(OldParam->getInit());
  469. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  470. Invalid = false;
  471. }
  472. }
  473. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  474. // hint here. Alternatively, we could walk the type-source information
  475. // for NewParam to find the last source location in the type... but it
  476. // isn't worth the effort right now. This is the kind of test case that
  477. // is hard to get right:
  478. // int f(int);
  479. // void g(int (*fp)(int) = f);
  480. // void g(int (*fp)(int) = &f);
  481. Diag(NewParam->getLocation(), DiagDefaultParamID)
  482. << NewParam->getDefaultArgRange();
  483. // Look for the function declaration where the default argument was
  484. // actually written, which may be a declaration prior to Old.
  485. for (auto Older = PrevForDefaultArgs;
  486. OldParam->hasInheritedDefaultArg(); /**/) {
  487. Older = Older->getPreviousDecl();
  488. OldParam = Older->getParamDecl(p);
  489. }
  490. Diag(OldParam->getLocation(), diag::note_previous_definition)
  491. << OldParam->getDefaultArgRange();
  492. } else if (OldParamHasDfl) {
  493. // Merge the old default argument into the new parameter unless the new
  494. // function is a friend declaration in a template class. In the latter
  495. // case the default arguments will be inherited when the friend
  496. // declaration will be instantiated.
  497. if (New->getFriendObjectKind() == Decl::FOK_None ||
  498. !New->getLexicalDeclContext()->isDependentContext()) {
  499. // It's important to use getInit() here; getDefaultArg()
  500. // strips off any top-level ExprWithCleanups.
  501. NewParam->setHasInheritedDefaultArg();
  502. if (OldParam->hasUnparsedDefaultArg())
  503. NewParam->setUnparsedDefaultArg();
  504. else if (OldParam->hasUninstantiatedDefaultArg())
  505. NewParam->setUninstantiatedDefaultArg(
  506. OldParam->getUninstantiatedDefaultArg());
  507. else
  508. NewParam->setDefaultArg(OldParam->getInit());
  509. }
  510. } else if (NewParamHasDfl) {
  511. if (New->getDescribedFunctionTemplate()) {
  512. // Paragraph 4, quoted above, only applies to non-template functions.
  513. Diag(NewParam->getLocation(),
  514. diag::err_param_default_argument_template_redecl)
  515. << NewParam->getDefaultArgRange();
  516. Diag(PrevForDefaultArgs->getLocation(),
  517. diag::note_template_prev_declaration)
  518. << false;
  519. } else if (New->getTemplateSpecializationKind()
  520. != TSK_ImplicitInstantiation &&
  521. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  522. // C++ [temp.expr.spec]p21:
  523. // Default function arguments shall not be specified in a declaration
  524. // or a definition for one of the following explicit specializations:
  525. // - the explicit specialization of a function template;
  526. // - the explicit specialization of a member function template;
  527. // - the explicit specialization of a member function of a class
  528. // template where the class template specialization to which the
  529. // member function specialization belongs is implicitly
  530. // instantiated.
  531. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  532. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  533. << New->getDeclName()
  534. << NewParam->getDefaultArgRange();
  535. } else if (New->getDeclContext()->isDependentContext()) {
  536. // C++ [dcl.fct.default]p6 (DR217):
  537. // Default arguments for a member function of a class template shall
  538. // be specified on the initial declaration of the member function
  539. // within the class template.
  540. //
  541. // Reading the tea leaves a bit in DR217 and its reference to DR205
  542. // leads me to the conclusion that one cannot add default function
  543. // arguments for an out-of-line definition of a member function of a
  544. // dependent type.
  545. int WhichKind = 2;
  546. if (CXXRecordDecl *Record
  547. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  548. if (Record->getDescribedClassTemplate())
  549. WhichKind = 0;
  550. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  551. WhichKind = 1;
  552. else
  553. WhichKind = 2;
  554. }
  555. Diag(NewParam->getLocation(),
  556. diag::err_param_default_argument_member_template_redecl)
  557. << WhichKind
  558. << NewParam->getDefaultArgRange();
  559. }
  560. }
  561. }
  562. // DR1344: If a default argument is added outside a class definition and that
  563. // default argument makes the function a special member function, the program
  564. // is ill-formed. This can only happen for constructors.
  565. if (isa<CXXConstructorDecl>(New) &&
  566. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  567. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  568. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  569. if (NewSM != OldSM) {
  570. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  571. assert(NewParam->hasDefaultArg());
  572. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  573. << NewParam->getDefaultArgRange() << NewSM;
  574. Diag(Old->getLocation(), diag::note_previous_declaration);
  575. }
  576. }
  577. const FunctionDecl *Def;
  578. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  579. // template has a constexpr specifier then all its declarations shall
  580. // contain the constexpr specifier.
  581. if (New->getConstexprKind() != Old->getConstexprKind()) {
  582. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  583. << New << New->getConstexprKind() << Old->getConstexprKind();
  584. Diag(Old->getLocation(), diag::note_previous_declaration);
  585. Invalid = true;
  586. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  587. Old->isDefined(Def) &&
  588. // If a friend function is inlined but does not have 'inline'
  589. // specifier, it is a definition. Do not report attribute conflict
  590. // in this case, redefinition will be diagnosed later.
  591. (New->isInlineSpecified() ||
  592. New->getFriendObjectKind() == Decl::FOK_None)) {
  593. // C++11 [dcl.fcn.spec]p4:
  594. // If the definition of a function appears in a translation unit before its
  595. // first declaration as inline, the program is ill-formed.
  596. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  597. Diag(Def->getLocation(), diag::note_previous_definition);
  598. Invalid = true;
  599. }
  600. // C++17 [temp.deduct.guide]p3:
  601. // Two deduction guide declarations in the same translation unit
  602. // for the same class template shall not have equivalent
  603. // parameter-declaration-clauses.
  604. if (isa<CXXDeductionGuideDecl>(New) &&
  605. !New->isFunctionTemplateSpecialization()) {
  606. Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
  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++17 [dcl.dcl]/8:
  651. // The decl-specifier-seq shall contain only the type-specifier auto
  652. // and cv-qualifiers.
  653. // C++2a [dcl.dcl]/8:
  654. // If decl-specifier-seq contains any decl-specifier other than static,
  655. // thread_local, auto, or cv-qualifiers, the program is ill-formed.
  656. auto &DS = D.getDeclSpec();
  657. {
  658. SmallVector<StringRef, 8> BadSpecifiers;
  659. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  660. SmallVector<StringRef, 8> CPlusPlus20Specifiers;
  661. SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
  662. if (auto SCS = DS.getStorageClassSpec()) {
  663. if (SCS == DeclSpec::SCS_static) {
  664. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
  665. CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  666. } else {
  667. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  668. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  669. }
  670. }
  671. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  672. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  673. CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  674. }
  675. if (DS.hasConstexprSpecifier()) {
  676. BadSpecifiers.push_back(
  677. DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
  678. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  679. }
  680. if (DS.isInlineSpecified()) {
  681. BadSpecifiers.push_back("inline");
  682. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  683. }
  684. if (!BadSpecifiers.empty()) {
  685. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  686. Err << (int)BadSpecifiers.size()
  687. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  688. // Don't add FixItHints to remove the specifiers; we do still respect
  689. // them when building the underlying variable.
  690. for (auto Loc : BadSpecifierLocs)
  691. Err << SourceRange(Loc, Loc);
  692. } else if (!CPlusPlus20Specifiers.empty()) {
  693. auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
  694. getLangOpts().CPlusPlus2a
  695. ? diag::warn_cxx17_compat_decomp_decl_spec
  696. : diag::ext_decomp_decl_spec);
  697. Warn << (int)CPlusPlus20Specifiers.size()
  698. << llvm::join(CPlusPlus20Specifiers.begin(),
  699. CPlusPlus20Specifiers.end(), " ");
  700. for (auto Loc : CPlusPlus20SpecifierLocs)
  701. Warn << SourceRange(Loc, Loc);
  702. }
  703. // We can't recover from it being declared as a typedef.
  704. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  705. return nullptr;
  706. }
  707. // C++2a [dcl.struct.bind]p1:
  708. // A cv that includes volatile is deprecated
  709. if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
  710. getLangOpts().CPlusPlus2a)
  711. Diag(DS.getVolatileSpecLoc(),
  712. diag::warn_deprecated_volatile_structured_binding);
  713. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  714. QualType R = TInfo->getType();
  715. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  716. UPPC_DeclarationType))
  717. D.setInvalidType();
  718. // The syntax only allows a single ref-qualifier prior to the decomposition
  719. // declarator. No other declarator chunks are permitted. Also check the type
  720. // specifier here.
  721. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  722. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  723. (D.getNumTypeObjects() == 1 &&
  724. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  725. Diag(Decomp.getLSquareLoc(),
  726. (D.hasGroupingParens() ||
  727. (D.getNumTypeObjects() &&
  728. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  729. ? diag::err_decomp_decl_parens
  730. : diag::err_decomp_decl_type)
  731. << R;
  732. // In most cases, there's no actual problem with an explicitly-specified
  733. // type, but a function type won't work here, and ActOnVariableDeclarator
  734. // shouldn't be called for such a type.
  735. if (R->isFunctionType())
  736. D.setInvalidType();
  737. }
  738. // Build the BindingDecls.
  739. SmallVector<BindingDecl*, 8> Bindings;
  740. // Build the BindingDecls.
  741. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  742. // Check for name conflicts.
  743. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  744. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  745. ForVisibleRedeclaration);
  746. LookupName(Previous, S,
  747. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  748. // It's not permitted to shadow a template parameter name.
  749. if (Previous.isSingleResult() &&
  750. Previous.getFoundDecl()->isTemplateParameter()) {
  751. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  752. Previous.getFoundDecl());
  753. Previous.clear();
  754. }
  755. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  756. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  757. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  758. /*AllowInlineNamespace*/false);
  759. if (!Previous.empty()) {
  760. auto *Old = Previous.getRepresentativeDecl();
  761. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  762. Diag(Old->getLocation(), diag::note_previous_definition);
  763. }
  764. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  765. PushOnScopeChains(BD, S, true);
  766. Bindings.push_back(BD);
  767. ParsingInitForAutoVars.insert(BD);
  768. }
  769. // There are no prior lookup results for the variable itself, because it
  770. // is unnamed.
  771. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  772. Decomp.getLSquareLoc());
  773. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  774. ForVisibleRedeclaration);
  775. // Build the variable that holds the non-decomposed object.
  776. bool AddToScope = true;
  777. NamedDecl *New =
  778. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  779. MultiTemplateParamsArg(), AddToScope, Bindings);
  780. if (AddToScope) {
  781. S->AddDecl(New);
  782. CurContext->addHiddenDecl(New);
  783. }
  784. if (isInOpenMPDeclareTargetContext())
  785. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  786. return New;
  787. }
  788. static bool checkSimpleDecomposition(
  789. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  790. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  791. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  792. if ((int64_t)Bindings.size() != NumElems) {
  793. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  794. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  795. << (NumElems < Bindings.size());
  796. return true;
  797. }
  798. unsigned I = 0;
  799. for (auto *B : Bindings) {
  800. SourceLocation Loc = B->getLocation();
  801. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  802. if (E.isInvalid())
  803. return true;
  804. E = GetInit(Loc, E.get(), I++);
  805. if (E.isInvalid())
  806. return true;
  807. B->setBinding(ElemType, E.get());
  808. }
  809. return false;
  810. }
  811. static bool checkArrayLikeDecomposition(Sema &S,
  812. ArrayRef<BindingDecl *> Bindings,
  813. ValueDecl *Src, QualType DecompType,
  814. const llvm::APSInt &NumElems,
  815. QualType ElemType) {
  816. return checkSimpleDecomposition(
  817. S, Bindings, Src, DecompType, NumElems, ElemType,
  818. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  819. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  820. if (E.isInvalid())
  821. return ExprError();
  822. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  823. });
  824. }
  825. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  826. ValueDecl *Src, QualType DecompType,
  827. const ConstantArrayType *CAT) {
  828. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  829. llvm::APSInt(CAT->getSize()),
  830. CAT->getElementType());
  831. }
  832. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  833. ValueDecl *Src, QualType DecompType,
  834. const VectorType *VT) {
  835. return checkArrayLikeDecomposition(
  836. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  837. S.Context.getQualifiedType(VT->getElementType(),
  838. DecompType.getQualifiers()));
  839. }
  840. static bool checkComplexDecomposition(Sema &S,
  841. ArrayRef<BindingDecl *> Bindings,
  842. ValueDecl *Src, QualType DecompType,
  843. const ComplexType *CT) {
  844. return checkSimpleDecomposition(
  845. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  846. S.Context.getQualifiedType(CT->getElementType(),
  847. DecompType.getQualifiers()),
  848. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  849. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  850. });
  851. }
  852. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  853. TemplateArgumentListInfo &Args) {
  854. SmallString<128> SS;
  855. llvm::raw_svector_ostream OS(SS);
  856. bool First = true;
  857. for (auto &Arg : Args.arguments()) {
  858. if (!First)
  859. OS << ", ";
  860. Arg.getArgument().print(PrintingPolicy, OS);
  861. First = false;
  862. }
  863. return OS.str();
  864. }
  865. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  866. SourceLocation Loc, StringRef Trait,
  867. TemplateArgumentListInfo &Args,
  868. unsigned DiagID) {
  869. auto DiagnoseMissing = [&] {
  870. if (DiagID)
  871. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  872. Args);
  873. return true;
  874. };
  875. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  876. NamespaceDecl *Std = S.getStdNamespace();
  877. if (!Std)
  878. return DiagnoseMissing();
  879. // Look up the trait itself, within namespace std. We can diagnose various
  880. // problems with this lookup even if we've been asked to not diagnose a
  881. // missing specialization, because this can only fail if the user has been
  882. // declaring their own names in namespace std or we don't support the
  883. // standard library implementation in use.
  884. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  885. Loc, Sema::LookupOrdinaryName);
  886. if (!S.LookupQualifiedName(Result, Std))
  887. return DiagnoseMissing();
  888. if (Result.isAmbiguous())
  889. return true;
  890. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  891. if (!TraitTD) {
  892. Result.suppressDiagnostics();
  893. NamedDecl *Found = *Result.begin();
  894. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  895. S.Diag(Found->getLocation(), diag::note_declared_at);
  896. return true;
  897. }
  898. // Build the template-id.
  899. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  900. if (TraitTy.isNull())
  901. return true;
  902. if (!S.isCompleteType(Loc, TraitTy)) {
  903. if (DiagID)
  904. S.RequireCompleteType(
  905. Loc, TraitTy, DiagID,
  906. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  907. return true;
  908. }
  909. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  910. assert(RD && "specialization of class template is not a class?");
  911. // Look up the member of the trait type.
  912. S.LookupQualifiedName(TraitMemberLookup, RD);
  913. return TraitMemberLookup.isAmbiguous();
  914. }
  915. static TemplateArgumentLoc
  916. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  917. uint64_t I) {
  918. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  919. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  920. }
  921. static TemplateArgumentLoc
  922. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  923. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  924. }
  925. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  926. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  927. llvm::APSInt &Size) {
  928. EnterExpressionEvaluationContext ContextRAII(
  929. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  930. DeclarationName Value = S.PP.getIdentifierInfo("value");
  931. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  932. // Form template argument list for tuple_size<T>.
  933. TemplateArgumentListInfo Args(Loc, Loc);
  934. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  935. // If there's no tuple_size specialization or the lookup of 'value' is empty,
  936. // it's not tuple-like.
  937. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
  938. R.empty())
  939. return IsTupleLike::NotTupleLike;
  940. // If we get this far, we've committed to the tuple interpretation, but
  941. // we can still fail if there actually isn't a usable ::value.
  942. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  943. LookupResult &R;
  944. TemplateArgumentListInfo &Args;
  945. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  946. : R(R), Args(Args) {}
  947. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  948. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  949. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  950. }
  951. } Diagnoser(R, Args);
  952. ExprResult E =
  953. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  954. if (E.isInvalid())
  955. return IsTupleLike::Error;
  956. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  957. if (E.isInvalid())
  958. return IsTupleLike::Error;
  959. return IsTupleLike::TupleLike;
  960. }
  961. /// \return std::tuple_element<I, T>::type.
  962. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  963. unsigned I, QualType T) {
  964. // Form template argument list for tuple_element<I, T>.
  965. TemplateArgumentListInfo Args(Loc, Loc);
  966. Args.addArgument(
  967. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  968. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  969. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  970. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  971. if (lookupStdTypeTraitMember(
  972. S, R, Loc, "tuple_element", Args,
  973. diag::err_decomp_decl_std_tuple_element_not_specialized))
  974. return QualType();
  975. auto *TD = R.getAsSingle<TypeDecl>();
  976. if (!TD) {
  977. R.suppressDiagnostics();
  978. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  979. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  980. if (!R.empty())
  981. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  982. return QualType();
  983. }
  984. return S.Context.getTypeDeclType(TD);
  985. }
  986. namespace {
  987. struct BindingDiagnosticTrap {
  988. Sema &S;
  989. DiagnosticErrorTrap Trap;
  990. BindingDecl *BD;
  991. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  992. : S(S), Trap(S.Diags), BD(BD) {}
  993. ~BindingDiagnosticTrap() {
  994. if (Trap.hasErrorOccurred())
  995. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  996. }
  997. };
  998. }
  999. static bool checkTupleLikeDecomposition(Sema &S,
  1000. ArrayRef<BindingDecl *> Bindings,
  1001. VarDecl *Src, QualType DecompType,
  1002. const llvm::APSInt &TupleSize) {
  1003. if ((int64_t)Bindings.size() != TupleSize) {
  1004. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1005. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  1006. << (TupleSize < Bindings.size());
  1007. return true;
  1008. }
  1009. if (Bindings.empty())
  1010. return false;
  1011. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  1012. // [dcl.decomp]p3:
  1013. // The unqualified-id get is looked up in the scope of E by class member
  1014. // access lookup ...
  1015. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  1016. bool UseMemberGet = false;
  1017. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  1018. if (auto *RD = DecompType->getAsCXXRecordDecl())
  1019. S.LookupQualifiedName(MemberGet, RD);
  1020. if (MemberGet.isAmbiguous())
  1021. return true;
  1022. // ... and if that finds at least one declaration that is a function
  1023. // template whose first template parameter is a non-type parameter ...
  1024. for (NamedDecl *D : MemberGet) {
  1025. if (FunctionTemplateDecl *FTD =
  1026. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1027. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1028. if (TPL->size() != 0 &&
  1029. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1030. // ... the initializer is e.get<i>().
  1031. UseMemberGet = true;
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. unsigned I = 0;
  1038. for (auto *B : Bindings) {
  1039. BindingDiagnosticTrap Trap(S, B);
  1040. SourceLocation Loc = B->getLocation();
  1041. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1042. if (E.isInvalid())
  1043. return true;
  1044. // e is an lvalue if the type of the entity is an lvalue reference and
  1045. // an xvalue otherwise
  1046. if (!Src->getType()->isLValueReferenceType())
  1047. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1048. E.get(), nullptr, VK_XValue);
  1049. TemplateArgumentListInfo Args(Loc, Loc);
  1050. Args.addArgument(
  1051. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1052. if (UseMemberGet) {
  1053. // if [lookup of member get] finds at least one declaration, the
  1054. // initializer is e.get<i-1>().
  1055. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1056. CXXScopeSpec(), SourceLocation(), nullptr,
  1057. MemberGet, &Args, nullptr);
  1058. if (E.isInvalid())
  1059. return true;
  1060. E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
  1061. } else {
  1062. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1063. // in the associated namespaces.
  1064. Expr *Get = UnresolvedLookupExpr::Create(
  1065. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1066. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1067. UnresolvedSetIterator(), UnresolvedSetIterator());
  1068. Expr *Arg = E.get();
  1069. E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
  1070. }
  1071. if (E.isInvalid())
  1072. return true;
  1073. Expr *Init = E.get();
  1074. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1075. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1076. if (T.isNull())
  1077. return true;
  1078. // each vi is a variable of type "reference to T" initialized with the
  1079. // initializer, where the reference is an lvalue reference if the
  1080. // initializer is an lvalue and an rvalue reference otherwise
  1081. QualType RefType =
  1082. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1083. if (RefType.isNull())
  1084. return true;
  1085. auto *RefVD = VarDecl::Create(
  1086. S.Context, Src->getDeclContext(), Loc, Loc,
  1087. B->getDeclName().getAsIdentifierInfo(), RefType,
  1088. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1089. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1090. RefVD->setTSCSpec(Src->getTSCSpec());
  1091. RefVD->setImplicit();
  1092. if (Src->isInlineSpecified())
  1093. RefVD->setInlineSpecified();
  1094. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1095. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1096. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1097. InitializationSequence Seq(S, Entity, Kind, Init);
  1098. E = Seq.Perform(S, Entity, Kind, Init);
  1099. if (E.isInvalid())
  1100. return true;
  1101. E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
  1102. if (E.isInvalid())
  1103. return true;
  1104. RefVD->setInit(E.get());
  1105. if (!E.get()->isValueDependent())
  1106. RefVD->checkInitIsICE();
  1107. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1108. DeclarationNameInfo(B->getDeclName(), Loc),
  1109. RefVD);
  1110. if (E.isInvalid())
  1111. return true;
  1112. B->setBinding(T, E.get());
  1113. I++;
  1114. }
  1115. return false;
  1116. }
  1117. /// Find the base class to decompose in a built-in decomposition of a class type.
  1118. /// This base class search is, unfortunately, not quite like any other that we
  1119. /// perform anywhere else in C++.
  1120. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1121. const CXXRecordDecl *RD,
  1122. CXXCastPath &BasePath) {
  1123. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1124. CXXBasePath &Path) {
  1125. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1126. };
  1127. const CXXRecordDecl *ClassWithFields = nullptr;
  1128. AccessSpecifier AS = AS_public;
  1129. if (RD->hasDirectFields())
  1130. // [dcl.decomp]p4:
  1131. // Otherwise, all of E's non-static data members shall be public direct
  1132. // members of E ...
  1133. ClassWithFields = RD;
  1134. else {
  1135. // ... or of ...
  1136. CXXBasePaths Paths;
  1137. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1138. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1139. // If no classes have fields, just decompose RD itself. (This will work
  1140. // if and only if zero bindings were provided.)
  1141. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1142. }
  1143. CXXBasePath *BestPath = nullptr;
  1144. for (auto &P : Paths) {
  1145. if (!BestPath)
  1146. BestPath = &P;
  1147. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1148. BestPath->back().Base->getType())) {
  1149. // ... the same ...
  1150. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1151. << false << RD << BestPath->back().Base->getType()
  1152. << P.back().Base->getType();
  1153. return DeclAccessPair();
  1154. } else if (P.Access < BestPath->Access) {
  1155. BestPath = &P;
  1156. }
  1157. }
  1158. // ... unambiguous ...
  1159. QualType BaseType = BestPath->back().Base->getType();
  1160. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1161. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1162. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1163. return DeclAccessPair();
  1164. }
  1165. // ... [accessible, implied by other rules] base class of E.
  1166. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1167. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1168. AS = BestPath->Access;
  1169. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1170. S.BuildBasePathArray(Paths, BasePath);
  1171. }
  1172. // The above search did not check whether the selected class itself has base
  1173. // classes with fields, so check that now.
  1174. CXXBasePaths Paths;
  1175. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1176. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1177. << (ClassWithFields == RD) << RD << ClassWithFields
  1178. << Paths.front().back().Base->getType();
  1179. return DeclAccessPair();
  1180. }
  1181. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1182. }
  1183. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1184. ValueDecl *Src, QualType DecompType,
  1185. const CXXRecordDecl *OrigRD) {
  1186. if (S.RequireCompleteType(Src->getLocation(), DecompType,
  1187. diag::err_incomplete_type))
  1188. return true;
  1189. CXXCastPath BasePath;
  1190. DeclAccessPair BasePair =
  1191. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1192. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1193. if (!RD)
  1194. return true;
  1195. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1196. DecompType.getQualifiers());
  1197. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1198. unsigned NumFields =
  1199. std::count_if(RD->field_begin(), RD->field_end(),
  1200. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1201. assert(Bindings.size() != NumFields);
  1202. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1203. << DecompType << (unsigned)Bindings.size() << NumFields
  1204. << (NumFields < Bindings.size());
  1205. return true;
  1206. };
  1207. // all of E's non-static data members shall be [...] well-formed
  1208. // when named as e.name in the context of the structured binding,
  1209. // E shall not have an anonymous union member, ...
  1210. unsigned I = 0;
  1211. for (auto *FD : RD->fields()) {
  1212. if (FD->isUnnamedBitfield())
  1213. continue;
  1214. if (FD->isAnonymousStructOrUnion()) {
  1215. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1216. << DecompType << FD->getType()->isUnionType();
  1217. S.Diag(FD->getLocation(), diag::note_declared_at);
  1218. return true;
  1219. }
  1220. // We have a real field to bind.
  1221. if (I >= Bindings.size())
  1222. return DiagnoseBadNumberOfBindings();
  1223. auto *B = Bindings[I++];
  1224. SourceLocation Loc = B->getLocation();
  1225. // The field must be accessible in the context of the structured binding.
  1226. // We already checked that the base class is accessible.
  1227. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1228. // const_cast here.
  1229. S.CheckStructuredBindingMemberAccess(
  1230. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1231. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1232. BasePair.getAccess(), FD->getAccess())));
  1233. // Initialize the binding to Src.FD.
  1234. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1235. if (E.isInvalid())
  1236. return true;
  1237. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1238. VK_LValue, &BasePath);
  1239. if (E.isInvalid())
  1240. return true;
  1241. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1242. CXXScopeSpec(), FD,
  1243. DeclAccessPair::make(FD, FD->getAccess()),
  1244. DeclarationNameInfo(FD->getDeclName(), Loc));
  1245. if (E.isInvalid())
  1246. return true;
  1247. // If the type of the member is T, the referenced type is cv T, where cv is
  1248. // the cv-qualification of the decomposition expression.
  1249. //
  1250. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1251. // 'const' to the type of the field.
  1252. Qualifiers Q = DecompType.getQualifiers();
  1253. if (FD->isMutable())
  1254. Q.removeConst();
  1255. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1256. }
  1257. if (I != Bindings.size())
  1258. return DiagnoseBadNumberOfBindings();
  1259. return false;
  1260. }
  1261. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1262. QualType DecompType = DD->getType();
  1263. // If the type of the decomposition is dependent, then so is the type of
  1264. // each binding.
  1265. if (DecompType->isDependentType()) {
  1266. for (auto *B : DD->bindings())
  1267. B->setType(Context.DependentTy);
  1268. return;
  1269. }
  1270. DecompType = DecompType.getNonReferenceType();
  1271. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1272. // C++1z [dcl.decomp]/2:
  1273. // If E is an array type [...]
  1274. // As an extension, we also support decomposition of built-in complex and
  1275. // vector types.
  1276. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1277. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1278. DD->setInvalidDecl();
  1279. return;
  1280. }
  1281. if (auto *VT = DecompType->getAs<VectorType>()) {
  1282. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1283. DD->setInvalidDecl();
  1284. return;
  1285. }
  1286. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1287. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1288. DD->setInvalidDecl();
  1289. return;
  1290. }
  1291. // C++1z [dcl.decomp]/3:
  1292. // if the expression std::tuple_size<E>::value is a well-formed integral
  1293. // constant expression, [...]
  1294. llvm::APSInt TupleSize(32);
  1295. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1296. case IsTupleLike::Error:
  1297. DD->setInvalidDecl();
  1298. return;
  1299. case IsTupleLike::TupleLike:
  1300. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1301. DD->setInvalidDecl();
  1302. return;
  1303. case IsTupleLike::NotTupleLike:
  1304. break;
  1305. }
  1306. // C++1z [dcl.dcl]/8:
  1307. // [E shall be of array or non-union class type]
  1308. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1309. if (!RD || RD->isUnion()) {
  1310. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1311. << DD << !RD << DecompType;
  1312. DD->setInvalidDecl();
  1313. return;
  1314. }
  1315. // C++1z [dcl.decomp]/4:
  1316. // all of E's non-static data members shall be [...] direct members of
  1317. // E or of the same unambiguous public base class of E, ...
  1318. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1319. DD->setInvalidDecl();
  1320. }
  1321. /// Merge the exception specifications of two variable declarations.
  1322. ///
  1323. /// This is called when there's a redeclaration of a VarDecl. The function
  1324. /// checks if the redeclaration might have an exception specification and
  1325. /// validates compatibility and merges the specs if necessary.
  1326. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1327. // Shortcut if exceptions are disabled.
  1328. if (!getLangOpts().CXXExceptions)
  1329. return;
  1330. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1331. "Should only be called if types are otherwise the same.");
  1332. QualType NewType = New->getType();
  1333. QualType OldType = Old->getType();
  1334. // We're only interested in pointers and references to functions, as well
  1335. // as pointers to member functions.
  1336. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1337. NewType = R->getPointeeType();
  1338. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1339. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1340. NewType = P->getPointeeType();
  1341. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1342. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1343. NewType = M->getPointeeType();
  1344. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1345. }
  1346. if (!NewType->isFunctionProtoType())
  1347. return;
  1348. // There's lots of special cases for functions. For function pointers, system
  1349. // libraries are hopefully not as broken so that we don't need these
  1350. // workarounds.
  1351. if (CheckEquivalentExceptionSpec(
  1352. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1353. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1354. New->setInvalidDecl();
  1355. }
  1356. }
  1357. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1358. /// function declaration are well-formed according to C++
  1359. /// [dcl.fct.default].
  1360. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1361. unsigned NumParams = FD->getNumParams();
  1362. unsigned p;
  1363. // Find first parameter with a default argument
  1364. for (p = 0; p < NumParams; ++p) {
  1365. ParmVarDecl *Param = FD->getParamDecl(p);
  1366. if (Param->hasDefaultArg())
  1367. break;
  1368. }
  1369. // C++11 [dcl.fct.default]p4:
  1370. // In a given function declaration, each parameter subsequent to a parameter
  1371. // with a default argument shall have a default argument supplied in this or
  1372. // a previous declaration or shall be a function parameter pack. A default
  1373. // argument shall not be redefined by a later declaration (not even to the
  1374. // same value).
  1375. unsigned LastMissingDefaultArg = 0;
  1376. for (; p < NumParams; ++p) {
  1377. ParmVarDecl *Param = FD->getParamDecl(p);
  1378. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1379. if (Param->isInvalidDecl())
  1380. /* We already complained about this parameter. */;
  1381. else if (Param->getIdentifier())
  1382. Diag(Param->getLocation(),
  1383. diag::err_param_default_argument_missing_name)
  1384. << Param->getIdentifier();
  1385. else
  1386. Diag(Param->getLocation(),
  1387. diag::err_param_default_argument_missing);
  1388. LastMissingDefaultArg = p;
  1389. }
  1390. }
  1391. if (LastMissingDefaultArg > 0) {
  1392. // Some default arguments were missing. Clear out all of the
  1393. // default arguments up to (and including) the last missing
  1394. // default argument, so that we leave the function parameters
  1395. // in a semantically valid state.
  1396. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1397. ParmVarDecl *Param = FD->getParamDecl(p);
  1398. if (Param->hasDefaultArg()) {
  1399. Param->setDefaultArg(nullptr);
  1400. }
  1401. }
  1402. }
  1403. }
  1404. /// Check that the given type is a literal type. Issue a diagnostic if not,
  1405. /// if Kind is Diagnose.
  1406. /// \return \c true if a problem has been found (and optionally diagnosed).
  1407. template <typename... Ts>
  1408. static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
  1409. SourceLocation Loc, QualType T, unsigned DiagID,
  1410. Ts &&...DiagArgs) {
  1411. if (T->isDependentType())
  1412. return false;
  1413. switch (Kind) {
  1414. case Sema::CheckConstexprKind::Diagnose:
  1415. return SemaRef.RequireLiteralType(Loc, T, DiagID,
  1416. std::forward<Ts>(DiagArgs)...);
  1417. case Sema::CheckConstexprKind::CheckValid:
  1418. return !T->isLiteralType(SemaRef.Context);
  1419. }
  1420. llvm_unreachable("unknown CheckConstexprKind");
  1421. }
  1422. /// Determine whether a destructor cannot be constexpr due to
  1423. static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
  1424. const CXXDestructorDecl *DD,
  1425. Sema::CheckConstexprKind Kind) {
  1426. auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
  1427. const CXXRecordDecl *RD =
  1428. T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1429. if (!RD || RD->hasConstexprDestructor())
  1430. return true;
  1431. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1432. SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
  1433. << DD->getConstexprKind() << !FD
  1434. << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1435. SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
  1436. << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1437. }
  1438. return false;
  1439. };
  1440. const CXXRecordDecl *RD = DD->getParent();
  1441. for (const CXXBaseSpecifier &B : RD->bases())
  1442. if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
  1443. return false;
  1444. for (const FieldDecl *FD : RD->fields())
  1445. if (!Check(FD->getLocation(), FD->getType(), FD))
  1446. return false;
  1447. return true;
  1448. }
  1449. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1450. // are all literal types. If so, return true. If not, produce a suitable
  1451. // diagnostic and return false.
  1452. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1453. const FunctionDecl *FD,
  1454. Sema::CheckConstexprKind Kind) {
  1455. unsigned ArgIndex = 0;
  1456. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1457. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1458. e = FT->param_type_end();
  1459. i != e; ++i, ++ArgIndex) {
  1460. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1461. SourceLocation ParamLoc = PD->getLocation();
  1462. if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
  1463. diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1464. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1465. FD->isConsteval()))
  1466. return false;
  1467. }
  1468. return true;
  1469. }
  1470. /// Get diagnostic %select index for tag kind for
  1471. /// record diagnostic message.
  1472. /// WARNING: Indexes apply to particular diagnostics only!
  1473. ///
  1474. /// \returns diagnostic %select index.
  1475. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1476. switch (Tag) {
  1477. case TTK_Struct: return 0;
  1478. case TTK_Interface: return 1;
  1479. case TTK_Class: return 2;
  1480. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1481. }
  1482. }
  1483. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1484. Stmt *Body,
  1485. Sema::CheckConstexprKind Kind);
  1486. // Check whether a function declaration satisfies the requirements of a
  1487. // constexpr function definition or a constexpr constructor definition. If so,
  1488. // return true. If not, produce appropriate diagnostics (unless asked not to by
  1489. // Kind) and return false.
  1490. //
  1491. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1492. bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
  1493. CheckConstexprKind Kind) {
  1494. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1495. if (MD && MD->isInstance()) {
  1496. // C++11 [dcl.constexpr]p4:
  1497. // The definition of a constexpr constructor shall satisfy the following
  1498. // constraints:
  1499. // - the class shall not have any virtual base classes;
  1500. //
  1501. // FIXME: This only applies to constructors and destructors, not arbitrary
  1502. // member functions.
  1503. const CXXRecordDecl *RD = MD->getParent();
  1504. if (RD->getNumVBases()) {
  1505. if (Kind == CheckConstexprKind::CheckValid)
  1506. return false;
  1507. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1508. << isa<CXXConstructorDecl>(NewFD)
  1509. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1510. for (const auto &I : RD->vbases())
  1511. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1512. << I.getSourceRange();
  1513. return false;
  1514. }
  1515. }
  1516. if (!isa<CXXConstructorDecl>(NewFD)) {
  1517. // C++11 [dcl.constexpr]p3:
  1518. // The definition of a constexpr function shall satisfy the following
  1519. // constraints:
  1520. // - it shall not be virtual; (removed in C++20)
  1521. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1522. if (Method && Method->isVirtual()) {
  1523. if (getLangOpts().CPlusPlus2a) {
  1524. if (Kind == CheckConstexprKind::Diagnose)
  1525. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1526. } else {
  1527. if (Kind == CheckConstexprKind::CheckValid)
  1528. return false;
  1529. Method = Method->getCanonicalDecl();
  1530. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1531. // If it's not obvious why this function is virtual, find an overridden
  1532. // function which uses the 'virtual' keyword.
  1533. const CXXMethodDecl *WrittenVirtual = Method;
  1534. while (!WrittenVirtual->isVirtualAsWritten())
  1535. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1536. if (WrittenVirtual != Method)
  1537. Diag(WrittenVirtual->getLocation(),
  1538. diag::note_overridden_virtual_function);
  1539. return false;
  1540. }
  1541. }
  1542. // - its return type shall be a literal type;
  1543. QualType RT = NewFD->getReturnType();
  1544. if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
  1545. diag::err_constexpr_non_literal_return,
  1546. NewFD->isConsteval()))
  1547. return false;
  1548. }
  1549. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
  1550. // A destructor can be constexpr only if the defaulted destructor could be;
  1551. // we don't need to check the members and bases if we already know they all
  1552. // have constexpr destructors.
  1553. if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
  1554. if (Kind == CheckConstexprKind::CheckValid)
  1555. return false;
  1556. if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
  1557. return false;
  1558. }
  1559. }
  1560. // - each of its parameter types shall be a literal type;
  1561. if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
  1562. return false;
  1563. Stmt *Body = NewFD->getBody();
  1564. assert(Body &&
  1565. "CheckConstexprFunctionDefinition called on function with no body");
  1566. return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
  1567. }
  1568. /// Check the given declaration statement is legal within a constexpr function
  1569. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1570. ///
  1571. /// \return true if the body is OK (maybe only as an extension), false if we
  1572. /// have diagnosed a problem.
  1573. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1574. DeclStmt *DS, SourceLocation &Cxx1yLoc,
  1575. Sema::CheckConstexprKind Kind) {
  1576. // C++11 [dcl.constexpr]p3 and p4:
  1577. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1578. // contain only
  1579. for (const auto *DclIt : DS->decls()) {
  1580. switch (DclIt->getKind()) {
  1581. case Decl::StaticAssert:
  1582. case Decl::Using:
  1583. case Decl::UsingShadow:
  1584. case Decl::UsingDirective:
  1585. case Decl::UnresolvedUsingTypename:
  1586. case Decl::UnresolvedUsingValue:
  1587. // - static_assert-declarations
  1588. // - using-declarations,
  1589. // - using-directives,
  1590. continue;
  1591. case Decl::Typedef:
  1592. case Decl::TypeAlias: {
  1593. // - typedef declarations and alias-declarations that do not define
  1594. // classes or enumerations,
  1595. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1596. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1597. // Don't allow variably-modified types in constexpr functions.
  1598. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1599. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1600. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1601. << TL.getSourceRange() << TL.getType()
  1602. << isa<CXXConstructorDecl>(Dcl);
  1603. }
  1604. return false;
  1605. }
  1606. continue;
  1607. }
  1608. case Decl::Enum:
  1609. case Decl::CXXRecord:
  1610. // C++1y allows types to be defined, not just declared.
  1611. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
  1612. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1613. SemaRef.Diag(DS->getBeginLoc(),
  1614. SemaRef.getLangOpts().CPlusPlus14
  1615. ? diag::warn_cxx11_compat_constexpr_type_definition
  1616. : diag::ext_constexpr_type_definition)
  1617. << isa<CXXConstructorDecl>(Dcl);
  1618. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1619. return false;
  1620. }
  1621. }
  1622. continue;
  1623. case Decl::EnumConstant:
  1624. case Decl::IndirectField:
  1625. case Decl::ParmVar:
  1626. // These can only appear with other declarations which are banned in
  1627. // C++11 and permitted in C++1y, so ignore them.
  1628. continue;
  1629. case Decl::Var:
  1630. case Decl::Decomposition: {
  1631. // C++1y [dcl.constexpr]p3 allows anything except:
  1632. // a definition of a variable of non-literal type or of static or
  1633. // thread storage duration or [before C++2a] for which no
  1634. // initialization is performed.
  1635. const auto *VD = cast<VarDecl>(DclIt);
  1636. if (VD->isThisDeclarationADefinition()) {
  1637. if (VD->isStaticLocal()) {
  1638. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1639. SemaRef.Diag(VD->getLocation(),
  1640. diag::err_constexpr_local_var_static)
  1641. << isa<CXXConstructorDecl>(Dcl)
  1642. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1643. }
  1644. return false;
  1645. }
  1646. if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
  1647. diag::err_constexpr_local_var_non_literal_type,
  1648. isa<CXXConstructorDecl>(Dcl)))
  1649. return false;
  1650. if (!VD->getType()->isDependentType() &&
  1651. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1652. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1653. SemaRef.Diag(
  1654. VD->getLocation(),
  1655. SemaRef.getLangOpts().CPlusPlus2a
  1656. ? diag::warn_cxx17_compat_constexpr_local_var_no_init
  1657. : diag::ext_constexpr_local_var_no_init)
  1658. << isa<CXXConstructorDecl>(Dcl);
  1659. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1660. return false;
  1661. }
  1662. continue;
  1663. }
  1664. }
  1665. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1666. SemaRef.Diag(VD->getLocation(),
  1667. SemaRef.getLangOpts().CPlusPlus14
  1668. ? diag::warn_cxx11_compat_constexpr_local_var
  1669. : diag::ext_constexpr_local_var)
  1670. << isa<CXXConstructorDecl>(Dcl);
  1671. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1672. return false;
  1673. }
  1674. continue;
  1675. }
  1676. case Decl::NamespaceAlias:
  1677. case Decl::Function:
  1678. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1679. // everywhere as an extension.
  1680. if (!Cxx1yLoc.isValid())
  1681. Cxx1yLoc = DS->getBeginLoc();
  1682. continue;
  1683. default:
  1684. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1685. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1686. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1687. }
  1688. return false;
  1689. }
  1690. }
  1691. return true;
  1692. }
  1693. /// Check that the given field is initialized within a constexpr constructor.
  1694. ///
  1695. /// \param Dcl The constexpr constructor being checked.
  1696. /// \param Field The field being checked. This may be a member of an anonymous
  1697. /// struct or union nested within the class being checked.
  1698. /// \param Inits All declarations, including anonymous struct/union members and
  1699. /// indirect members, for which any initialization was provided.
  1700. /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
  1701. /// multiple notes for different members to the same error.
  1702. /// \param Kind Whether we're diagnosing a constructor as written or determining
  1703. /// whether the formal requirements are satisfied.
  1704. /// \return \c false if we're checking for validity and the constructor does
  1705. /// not satisfy the requirements on a constexpr constructor.
  1706. static bool CheckConstexprCtorInitializer(Sema &SemaRef,
  1707. const FunctionDecl *Dcl,
  1708. FieldDecl *Field,
  1709. llvm::SmallSet<Decl*, 16> &Inits,
  1710. bool &Diagnosed,
  1711. Sema::CheckConstexprKind Kind) {
  1712. // In C++20 onwards, there's nothing to check for validity.
  1713. if (Kind == Sema::CheckConstexprKind::CheckValid &&
  1714. SemaRef.getLangOpts().CPlusPlus2a)
  1715. return true;
  1716. if (Field->isInvalidDecl())
  1717. return true;
  1718. if (Field->isUnnamedBitfield())
  1719. return true;
  1720. // Anonymous unions with no variant members and empty anonymous structs do not
  1721. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1722. // indirect fields don't need initializing.
  1723. if (Field->isAnonymousStructOrUnion() &&
  1724. (Field->getType()->isUnionType()
  1725. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1726. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1727. return true;
  1728. if (!Inits.count(Field)) {
  1729. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1730. if (!Diagnosed) {
  1731. SemaRef.Diag(Dcl->getLocation(),
  1732. SemaRef.getLangOpts().CPlusPlus2a
  1733. ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
  1734. : diag::ext_constexpr_ctor_missing_init);
  1735. Diagnosed = true;
  1736. }
  1737. SemaRef.Diag(Field->getLocation(),
  1738. diag::note_constexpr_ctor_missing_init);
  1739. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1740. return false;
  1741. }
  1742. } else if (Field->isAnonymousStructOrUnion()) {
  1743. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1744. for (auto *I : RD->fields())
  1745. // If an anonymous union contains an anonymous struct of which any member
  1746. // is initialized, all members must be initialized.
  1747. if (!RD->isUnion() || Inits.count(I))
  1748. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1749. Kind))
  1750. return false;
  1751. }
  1752. return true;
  1753. }
  1754. /// Check the provided statement is allowed in a constexpr function
  1755. /// definition.
  1756. static bool
  1757. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1758. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1759. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
  1760. Sema::CheckConstexprKind Kind) {
  1761. // - its function-body shall be [...] a compound-statement that contains only
  1762. switch (S->getStmtClass()) {
  1763. case Stmt::NullStmtClass:
  1764. // - null statements,
  1765. return true;
  1766. case Stmt::DeclStmtClass:
  1767. // - static_assert-declarations
  1768. // - using-declarations,
  1769. // - using-directives,
  1770. // - typedef declarations and alias-declarations that do not define
  1771. // classes or enumerations,
  1772. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
  1773. return false;
  1774. return true;
  1775. case Stmt::ReturnStmtClass:
  1776. // - and exactly one return statement;
  1777. if (isa<CXXConstructorDecl>(Dcl)) {
  1778. // C++1y allows return statements in constexpr constructors.
  1779. if (!Cxx1yLoc.isValid())
  1780. Cxx1yLoc = S->getBeginLoc();
  1781. return true;
  1782. }
  1783. ReturnStmts.push_back(S->getBeginLoc());
  1784. return true;
  1785. case Stmt::CompoundStmtClass: {
  1786. // C++1y allows compound-statements.
  1787. if (!Cxx1yLoc.isValid())
  1788. Cxx1yLoc = S->getBeginLoc();
  1789. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1790. for (auto *BodyIt : CompStmt->body()) {
  1791. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1792. Cxx1yLoc, Cxx2aLoc, Kind))
  1793. return false;
  1794. }
  1795. return true;
  1796. }
  1797. case Stmt::AttributedStmtClass:
  1798. if (!Cxx1yLoc.isValid())
  1799. Cxx1yLoc = S->getBeginLoc();
  1800. return true;
  1801. case Stmt::IfStmtClass: {
  1802. // C++1y allows if-statements.
  1803. if (!Cxx1yLoc.isValid())
  1804. Cxx1yLoc = S->getBeginLoc();
  1805. IfStmt *If = cast<IfStmt>(S);
  1806. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1807. Cxx1yLoc, Cxx2aLoc, Kind))
  1808. return false;
  1809. if (If->getElse() &&
  1810. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1811. Cxx1yLoc, Cxx2aLoc, Kind))
  1812. return false;
  1813. return true;
  1814. }
  1815. case Stmt::WhileStmtClass:
  1816. case Stmt::DoStmtClass:
  1817. case Stmt::ForStmtClass:
  1818. case Stmt::CXXForRangeStmtClass:
  1819. case Stmt::ContinueStmtClass:
  1820. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1821. // because they don't make sense without variable mutation.
  1822. if (!SemaRef.getLangOpts().CPlusPlus14)
  1823. break;
  1824. if (!Cxx1yLoc.isValid())
  1825. Cxx1yLoc = S->getBeginLoc();
  1826. for (Stmt *SubStmt : S->children())
  1827. if (SubStmt &&
  1828. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1829. Cxx1yLoc, Cxx2aLoc, Kind))
  1830. return false;
  1831. return true;
  1832. case Stmt::SwitchStmtClass:
  1833. case Stmt::CaseStmtClass:
  1834. case Stmt::DefaultStmtClass:
  1835. case Stmt::BreakStmtClass:
  1836. // C++1y allows switch-statements, and since they don't need variable
  1837. // mutation, we can reasonably allow them in C++11 as an extension.
  1838. if (!Cxx1yLoc.isValid())
  1839. Cxx1yLoc = S->getBeginLoc();
  1840. for (Stmt *SubStmt : S->children())
  1841. if (SubStmt &&
  1842. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1843. Cxx1yLoc, Cxx2aLoc, Kind))
  1844. return false;
  1845. return true;
  1846. case Stmt::GCCAsmStmtClass:
  1847. case Stmt::MSAsmStmtClass:
  1848. // C++2a allows inline assembly statements.
  1849. case Stmt::CXXTryStmtClass:
  1850. if (Cxx2aLoc.isInvalid())
  1851. Cxx2aLoc = S->getBeginLoc();
  1852. for (Stmt *SubStmt : S->children()) {
  1853. if (SubStmt &&
  1854. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1855. Cxx1yLoc, Cxx2aLoc, Kind))
  1856. return false;
  1857. }
  1858. return true;
  1859. case Stmt::CXXCatchStmtClass:
  1860. // Do not bother checking the language mode (already covered by the
  1861. // try block check).
  1862. if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
  1863. cast<CXXCatchStmt>(S)->getHandlerBlock(),
  1864. ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
  1865. return false;
  1866. return true;
  1867. default:
  1868. if (!isa<Expr>(S))
  1869. break;
  1870. // C++1y allows expression-statements.
  1871. if (!Cxx1yLoc.isValid())
  1872. Cxx1yLoc = S->getBeginLoc();
  1873. return true;
  1874. }
  1875. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1876. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1877. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1878. }
  1879. return false;
  1880. }
  1881. /// Check the body for the given constexpr function declaration only contains
  1882. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1883. ///
  1884. /// \return true if the body is OK, false if we have found or diagnosed a
  1885. /// problem.
  1886. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1887. Stmt *Body,
  1888. Sema::CheckConstexprKind Kind) {
  1889. SmallVector<SourceLocation, 4> ReturnStmts;
  1890. if (isa<CXXTryStmt>(Body)) {
  1891. // C++11 [dcl.constexpr]p3:
  1892. // The definition of a constexpr function shall satisfy the following
  1893. // constraints: [...]
  1894. // - its function-body shall be = delete, = default, or a
  1895. // compound-statement
  1896. //
  1897. // C++11 [dcl.constexpr]p4:
  1898. // In the definition of a constexpr constructor, [...]
  1899. // - its function-body shall not be a function-try-block;
  1900. //
  1901. // This restriction is lifted in C++2a, as long as inner statements also
  1902. // apply the general constexpr rules.
  1903. switch (Kind) {
  1904. case Sema::CheckConstexprKind::CheckValid:
  1905. if (!SemaRef.getLangOpts().CPlusPlus2a)
  1906. return false;
  1907. break;
  1908. case Sema::CheckConstexprKind::Diagnose:
  1909. SemaRef.Diag(Body->getBeginLoc(),
  1910. !SemaRef.getLangOpts().CPlusPlus2a
  1911. ? diag::ext_constexpr_function_try_block_cxx2a
  1912. : diag::warn_cxx17_compat_constexpr_function_try_block)
  1913. << isa<CXXConstructorDecl>(Dcl);
  1914. break;
  1915. }
  1916. }
  1917. // - its function-body shall be [...] a compound-statement that contains only
  1918. // [... list of cases ...]
  1919. //
  1920. // Note that walking the children here is enough to properly check for
  1921. // CompoundStmt and CXXTryStmt body.
  1922. SourceLocation Cxx1yLoc, Cxx2aLoc;
  1923. for (Stmt *SubStmt : Body->children()) {
  1924. if (SubStmt &&
  1925. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1926. Cxx1yLoc, Cxx2aLoc, Kind))
  1927. return false;
  1928. }
  1929. if (Kind == Sema::CheckConstexprKind::CheckValid) {
  1930. // If this is only valid as an extension, report that we don't satisfy the
  1931. // constraints of the current language.
  1932. if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
  1933. (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
  1934. return false;
  1935. } else if (Cxx2aLoc.isValid()) {
  1936. SemaRef.Diag(Cxx2aLoc,
  1937. SemaRef.getLangOpts().CPlusPlus2a
  1938. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  1939. : diag::ext_constexpr_body_invalid_stmt_cxx2a)
  1940. << isa<CXXConstructorDecl>(Dcl);
  1941. } else if (Cxx1yLoc.isValid()) {
  1942. SemaRef.Diag(Cxx1yLoc,
  1943. SemaRef.getLangOpts().CPlusPlus14
  1944. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1945. : diag::ext_constexpr_body_invalid_stmt)
  1946. << isa<CXXConstructorDecl>(Dcl);
  1947. }
  1948. if (const CXXConstructorDecl *Constructor
  1949. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1950. const CXXRecordDecl *RD = Constructor->getParent();
  1951. // DR1359:
  1952. // - every non-variant non-static data member and base class sub-object
  1953. // shall be initialized;
  1954. // DR1460:
  1955. // - if the class is a union having variant members, exactly one of them
  1956. // shall be initialized;
  1957. if (RD->isUnion()) {
  1958. if (Constructor->getNumCtorInitializers() == 0 &&
  1959. RD->hasVariantMembers()) {
  1960. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1961. SemaRef.Diag(
  1962. Dcl->getLocation(),
  1963. SemaRef.getLangOpts().CPlusPlus2a
  1964. ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
  1965. : diag::ext_constexpr_union_ctor_no_init);
  1966. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1967. return false;
  1968. }
  1969. }
  1970. } else if (!Constructor->isDependentContext() &&
  1971. !Constructor->isDelegatingConstructor()) {
  1972. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1973. // Skip detailed checking if we have enough initializers, and we would
  1974. // allow at most one initializer per member.
  1975. bool AnyAnonStructUnionMembers = false;
  1976. unsigned Fields = 0;
  1977. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1978. E = RD->field_end(); I != E; ++I, ++Fields) {
  1979. if (I->isAnonymousStructOrUnion()) {
  1980. AnyAnonStructUnionMembers = true;
  1981. break;
  1982. }
  1983. }
  1984. // DR1460:
  1985. // - if the class is a union-like class, but is not a union, for each of
  1986. // its anonymous union members having variant members, exactly one of
  1987. // them shall be initialized;
  1988. if (AnyAnonStructUnionMembers ||
  1989. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1990. // Check initialization of non-static data members. Base classes are
  1991. // always initialized so do not need to be checked. Dependent bases
  1992. // might not have initializers in the member initializer list.
  1993. llvm::SmallSet<Decl*, 16> Inits;
  1994. for (const auto *I: Constructor->inits()) {
  1995. if (FieldDecl *FD = I->getMember())
  1996. Inits.insert(FD);
  1997. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1998. Inits.insert(ID->chain_begin(), ID->chain_end());
  1999. }
  2000. bool Diagnosed = false;
  2001. for (auto *I : RD->fields())
  2002. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  2003. Kind))
  2004. return false;
  2005. }
  2006. }
  2007. } else {
  2008. if (ReturnStmts.empty()) {
  2009. // C++1y doesn't require constexpr functions to contain a 'return'
  2010. // statement. We still do, unless the return type might be void, because
  2011. // otherwise if there's no return statement, the function cannot
  2012. // be used in a core constant expression.
  2013. bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
  2014. (Dcl->getReturnType()->isVoidType() ||
  2015. Dcl->getReturnType()->isDependentType());
  2016. switch (Kind) {
  2017. case Sema::CheckConstexprKind::Diagnose:
  2018. SemaRef.Diag(Dcl->getLocation(),
  2019. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  2020. : diag::err_constexpr_body_no_return)
  2021. << Dcl->isConsteval();
  2022. if (!OK)
  2023. return false;
  2024. break;
  2025. case Sema::CheckConstexprKind::CheckValid:
  2026. // The formal requirements don't include this rule in C++14, even
  2027. // though the "must be able to produce a constant expression" rules
  2028. // still imply it in some cases.
  2029. if (!SemaRef.getLangOpts().CPlusPlus14)
  2030. return false;
  2031. break;
  2032. }
  2033. } else if (ReturnStmts.size() > 1) {
  2034. switch (Kind) {
  2035. case Sema::CheckConstexprKind::Diagnose:
  2036. SemaRef.Diag(
  2037. ReturnStmts.back(),
  2038. SemaRef.getLangOpts().CPlusPlus14
  2039. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  2040. : diag::ext_constexpr_body_multiple_return);
  2041. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  2042. SemaRef.Diag(ReturnStmts[I],
  2043. diag::note_constexpr_body_previous_return);
  2044. break;
  2045. case Sema::CheckConstexprKind::CheckValid:
  2046. if (!SemaRef.getLangOpts().CPlusPlus14)
  2047. return false;
  2048. break;
  2049. }
  2050. }
  2051. }
  2052. // C++11 [dcl.constexpr]p5:
  2053. // if no function argument values exist such that the function invocation
  2054. // substitution would produce a constant expression, the program is
  2055. // ill-formed; no diagnostic required.
  2056. // C++11 [dcl.constexpr]p3:
  2057. // - every constructor call and implicit conversion used in initializing the
  2058. // return value shall be one of those allowed in a constant expression.
  2059. // C++11 [dcl.constexpr]p4:
  2060. // - every constructor involved in initializing non-static data members and
  2061. // base class sub-objects shall be a constexpr constructor.
  2062. //
  2063. // Note that this rule is distinct from the "requirements for a constexpr
  2064. // function", so is not checked in CheckValid mode.
  2065. SmallVector<PartialDiagnosticAt, 8> Diags;
  2066. if (Kind == Sema::CheckConstexprKind::Diagnose &&
  2067. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  2068. SemaRef.Diag(Dcl->getLocation(),
  2069. diag::ext_constexpr_function_never_constant_expr)
  2070. << isa<CXXConstructorDecl>(Dcl);
  2071. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  2072. SemaRef.Diag(Diags[I].first, Diags[I].second);
  2073. // Don't return false here: we allow this for compatibility in
  2074. // system headers.
  2075. }
  2076. return true;
  2077. }
  2078. /// Get the class that is directly named by the current context. This is the
  2079. /// class for which an unqualified-id in this scope could name a constructor
  2080. /// or destructor.
  2081. ///
  2082. /// If the scope specifier denotes a class, this will be that class.
  2083. /// If the scope specifier is empty, this will be the class whose
  2084. /// member-specification we are currently within. Otherwise, there
  2085. /// is no such class.
  2086. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  2087. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2088. if (SS && SS->isInvalid())
  2089. return nullptr;
  2090. if (SS && SS->isNotEmpty()) {
  2091. DeclContext *DC = computeDeclContext(*SS, true);
  2092. return dyn_cast_or_null<CXXRecordDecl>(DC);
  2093. }
  2094. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2095. }
  2096. /// isCurrentClassName - Determine whether the identifier II is the
  2097. /// name of the class type currently being defined. In the case of
  2098. /// nested classes, this will only return true if II is the name of
  2099. /// the innermost class.
  2100. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  2101. const CXXScopeSpec *SS) {
  2102. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  2103. return CurDecl && &II == CurDecl->getIdentifier();
  2104. }
  2105. /// Determine whether the identifier II is a typo for the name of
  2106. /// the class type currently being defined. If so, update it to the identifier
  2107. /// that should have been used.
  2108. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  2109. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2110. if (!getLangOpts().SpellChecking)
  2111. return false;
  2112. CXXRecordDecl *CurDecl;
  2113. if (SS && SS->isSet() && !SS->isInvalid()) {
  2114. DeclContext *DC = computeDeclContext(*SS, true);
  2115. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  2116. } else
  2117. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2118. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  2119. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  2120. < II->getLength()) {
  2121. II = CurDecl->getIdentifier();
  2122. return true;
  2123. }
  2124. return false;
  2125. }
  2126. /// Determine whether the given class is a base class of the given
  2127. /// class, including looking at dependent bases.
  2128. static bool findCircularInheritance(const CXXRecordDecl *Class,
  2129. const CXXRecordDecl *Current) {
  2130. SmallVector<const CXXRecordDecl*, 8> Queue;
  2131. Class = Class->getCanonicalDecl();
  2132. while (true) {
  2133. for (const auto &I : Current->bases()) {
  2134. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  2135. if (!Base)
  2136. continue;
  2137. Base = Base->getDefinition();
  2138. if (!Base)
  2139. continue;
  2140. if (Base->getCanonicalDecl() == Class)
  2141. return true;
  2142. Queue.push_back(Base);
  2143. }
  2144. if (Queue.empty())
  2145. return false;
  2146. Current = Queue.pop_back_val();
  2147. }
  2148. return false;
  2149. }
  2150. /// Check the validity of a C++ base class specifier.
  2151. ///
  2152. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  2153. /// and returns NULL otherwise.
  2154. CXXBaseSpecifier *
  2155. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  2156. SourceRange SpecifierRange,
  2157. bool Virtual, AccessSpecifier Access,
  2158. TypeSourceInfo *TInfo,
  2159. SourceLocation EllipsisLoc) {
  2160. QualType BaseType = TInfo->getType();
  2161. // C++ [class.union]p1:
  2162. // A union shall not have base classes.
  2163. if (Class->isUnion()) {
  2164. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  2165. << SpecifierRange;
  2166. return nullptr;
  2167. }
  2168. if (EllipsisLoc.isValid() &&
  2169. !TInfo->getType()->containsUnexpandedParameterPack()) {
  2170. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2171. << TInfo->getTypeLoc().getSourceRange();
  2172. EllipsisLoc = SourceLocation();
  2173. }
  2174. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2175. if (BaseType->isDependentType()) {
  2176. // Make sure that we don't have circular inheritance among our dependent
  2177. // bases. For non-dependent bases, the check for completeness below handles
  2178. // this.
  2179. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2180. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2181. ((BaseDecl = BaseDecl->getDefinition()) &&
  2182. findCircularInheritance(Class, BaseDecl))) {
  2183. Diag(BaseLoc, diag::err_circular_inheritance)
  2184. << BaseType << Context.getTypeDeclType(Class);
  2185. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2186. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2187. << BaseType;
  2188. return nullptr;
  2189. }
  2190. }
  2191. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2192. Class->getTagKind() == TTK_Class,
  2193. Access, TInfo, EllipsisLoc);
  2194. }
  2195. // Base specifiers must be record types.
  2196. if (!BaseType->isRecordType()) {
  2197. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2198. return nullptr;
  2199. }
  2200. // C++ [class.union]p1:
  2201. // A union shall not be used as a base class.
  2202. if (BaseType->isUnionType()) {
  2203. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2204. return nullptr;
  2205. }
  2206. // For the MS ABI, propagate DLL attributes to base class templates.
  2207. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2208. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2209. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2210. BaseType->getAsCXXRecordDecl())) {
  2211. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2212. BaseLoc);
  2213. }
  2214. }
  2215. }
  2216. // C++ [class.derived]p2:
  2217. // The class-name in a base-specifier shall not be an incompletely
  2218. // defined class.
  2219. if (RequireCompleteType(BaseLoc, BaseType,
  2220. diag::err_incomplete_base_class, SpecifierRange)) {
  2221. Class->setInvalidDecl();
  2222. return nullptr;
  2223. }
  2224. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2225. RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
  2226. assert(BaseDecl && "Record type has no declaration");
  2227. BaseDecl = BaseDecl->getDefinition();
  2228. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2229. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2230. assert(CXXBaseDecl && "Base type is not a C++ type");
  2231. // Microsoft docs say:
  2232. // "If a base-class has a code_seg attribute, derived classes must have the
  2233. // same attribute."
  2234. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2235. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2236. if ((DerivedCSA || BaseCSA) &&
  2237. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2238. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2239. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2240. << CXXBaseDecl;
  2241. return nullptr;
  2242. }
  2243. // A class which contains a flexible array member is not suitable for use as a
  2244. // base class:
  2245. // - If the layout determines that a base comes before another base,
  2246. // the flexible array member would index into the subsequent base.
  2247. // - If the layout determines that base comes before the derived class,
  2248. // the flexible array member would index into the derived class.
  2249. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2250. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2251. << CXXBaseDecl->getDeclName();
  2252. return nullptr;
  2253. }
  2254. // C++ [class]p3:
  2255. // If a class is marked final and it appears as a base-type-specifier in
  2256. // base-clause, the program is ill-formed.
  2257. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2258. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2259. << CXXBaseDecl->getDeclName()
  2260. << FA->isSpelledAsSealed();
  2261. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2262. << CXXBaseDecl->getDeclName() << FA->getRange();
  2263. return nullptr;
  2264. }
  2265. if (BaseDecl->isInvalidDecl())
  2266. Class->setInvalidDecl();
  2267. // Create the base specifier.
  2268. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2269. Class->getTagKind() == TTK_Class,
  2270. Access, TInfo, EllipsisLoc);
  2271. }
  2272. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2273. /// one entry in the base class list of a class specifier, for
  2274. /// example:
  2275. /// class foo : public bar, virtual private baz {
  2276. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2277. BaseResult
  2278. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2279. ParsedAttributes &Attributes,
  2280. bool Virtual, AccessSpecifier Access,
  2281. ParsedType basetype, SourceLocation BaseLoc,
  2282. SourceLocation EllipsisLoc) {
  2283. if (!classdecl)
  2284. return true;
  2285. AdjustDeclIfTemplate(classdecl);
  2286. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2287. if (!Class)
  2288. return true;
  2289. // We haven't yet attached the base specifiers.
  2290. Class->setIsParsingBaseSpecifiers();
  2291. // We do not support any C++11 attributes on base-specifiers yet.
  2292. // Diagnose any attributes we see.
  2293. for (const ParsedAttr &AL : Attributes) {
  2294. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2295. continue;
  2296. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2297. ? (unsigned)diag::warn_unknown_attribute_ignored
  2298. : (unsigned)diag::err_base_specifier_attribute)
  2299. << AL;
  2300. }
  2301. TypeSourceInfo *TInfo = nullptr;
  2302. GetTypeFromParser(basetype, &TInfo);
  2303. if (EllipsisLoc.isInvalid() &&
  2304. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2305. UPPC_BaseType))
  2306. return true;
  2307. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2308. Virtual, Access, TInfo,
  2309. EllipsisLoc))
  2310. return BaseSpec;
  2311. else
  2312. Class->setInvalidDecl();
  2313. return true;
  2314. }
  2315. /// Use small set to collect indirect bases. As this is only used
  2316. /// locally, there's no need to abstract the small size parameter.
  2317. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2318. /// Recursively add the bases of Type. Don't add Type itself.
  2319. static void
  2320. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2321. const QualType &Type)
  2322. {
  2323. // Even though the incoming type is a base, it might not be
  2324. // a class -- it could be a template parm, for instance.
  2325. if (auto Rec = Type->getAs<RecordType>()) {
  2326. auto Decl = Rec->getAsCXXRecordDecl();
  2327. // Iterate over its bases.
  2328. for (const auto &BaseSpec : Decl->bases()) {
  2329. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2330. .getUnqualifiedType();
  2331. if (Set.insert(Base).second)
  2332. // If we've not already seen it, recurse.
  2333. NoteIndirectBases(Context, Set, Base);
  2334. }
  2335. }
  2336. }
  2337. /// Performs the actual work of attaching the given base class
  2338. /// specifiers to a C++ class.
  2339. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2340. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2341. if (Bases.empty())
  2342. return false;
  2343. // Used to keep track of which base types we have already seen, so
  2344. // that we can properly diagnose redundant direct base types. Note
  2345. // that the key is always the unqualified canonical type of the base
  2346. // class.
  2347. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2348. // Used to track indirect bases so we can see if a direct base is
  2349. // ambiguous.
  2350. IndirectBaseSet IndirectBaseTypes;
  2351. // Copy non-redundant base specifiers into permanent storage.
  2352. unsigned NumGoodBases = 0;
  2353. bool Invalid = false;
  2354. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2355. QualType NewBaseType
  2356. = Context.getCanonicalType(Bases[idx]->getType());
  2357. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2358. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2359. if (KnownBase) {
  2360. // C++ [class.mi]p3:
  2361. // A class shall not be specified as a direct base class of a
  2362. // derived class more than once.
  2363. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2364. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2365. // Delete the duplicate base class specifier; we're going to
  2366. // overwrite its pointer later.
  2367. Context.Deallocate(Bases[idx]);
  2368. Invalid = true;
  2369. } else {
  2370. // Okay, add this new base class.
  2371. KnownBase = Bases[idx];
  2372. Bases[NumGoodBases++] = Bases[idx];
  2373. // Note this base's direct & indirect bases, if there could be ambiguity.
  2374. if (Bases.size() > 1)
  2375. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2376. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2377. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2378. if (Class->isInterface() &&
  2379. (!RD->isInterfaceLike() ||
  2380. KnownBase->getAccessSpecifier() != AS_public)) {
  2381. // The Microsoft extension __interface does not permit bases that
  2382. // are not themselves public interfaces.
  2383. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2384. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2385. << RD->getSourceRange();
  2386. Invalid = true;
  2387. }
  2388. if (RD->hasAttr<WeakAttr>())
  2389. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2390. }
  2391. }
  2392. }
  2393. // Attach the remaining base class specifiers to the derived class.
  2394. Class->setBases(Bases.data(), NumGoodBases);
  2395. // Check that the only base classes that are duplicate are virtual.
  2396. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2397. // Check whether this direct base is inaccessible due to ambiguity.
  2398. QualType BaseType = Bases[idx]->getType();
  2399. // Skip all dependent types in templates being used as base specifiers.
  2400. // Checks below assume that the base specifier is a CXXRecord.
  2401. if (BaseType->isDependentType())
  2402. continue;
  2403. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2404. .getUnqualifiedType();
  2405. if (IndirectBaseTypes.count(CanonicalBase)) {
  2406. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2407. /*DetectVirtual=*/true);
  2408. bool found
  2409. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2410. assert(found);
  2411. (void)found;
  2412. if (Paths.isAmbiguous(CanonicalBase))
  2413. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2414. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2415. << Bases[idx]->getSourceRange();
  2416. else
  2417. assert(Bases[idx]->isVirtual());
  2418. }
  2419. // Delete the base class specifier, since its data has been copied
  2420. // into the CXXRecordDecl.
  2421. Context.Deallocate(Bases[idx]);
  2422. }
  2423. return Invalid;
  2424. }
  2425. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2426. /// class, after checking whether there are any duplicate base
  2427. /// classes.
  2428. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2429. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2430. if (!ClassDecl || Bases.empty())
  2431. return;
  2432. AdjustDeclIfTemplate(ClassDecl);
  2433. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2434. }
  2435. /// Determine whether the type \p Derived is a C++ class that is
  2436. /// derived from the type \p Base.
  2437. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2438. if (!getLangOpts().CPlusPlus)
  2439. return false;
  2440. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2441. if (!DerivedRD)
  2442. return false;
  2443. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2444. if (!BaseRD)
  2445. return false;
  2446. // If either the base or the derived type is invalid, don't try to
  2447. // check whether one is derived from the other.
  2448. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2449. return false;
  2450. // FIXME: In a modules build, do we need the entire path to be visible for us
  2451. // to be able to use the inheritance relationship?
  2452. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2453. return false;
  2454. return DerivedRD->isDerivedFrom(BaseRD);
  2455. }
  2456. /// Determine whether the type \p Derived is a C++ class that is
  2457. /// derived from the type \p Base.
  2458. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2459. CXXBasePaths &Paths) {
  2460. if (!getLangOpts().CPlusPlus)
  2461. return false;
  2462. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2463. if (!DerivedRD)
  2464. return false;
  2465. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2466. if (!BaseRD)
  2467. return false;
  2468. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2469. return false;
  2470. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2471. }
  2472. static void BuildBasePathArray(const CXXBasePath &Path,
  2473. CXXCastPath &BasePathArray) {
  2474. // We first go backward and check if we have a virtual base.
  2475. // FIXME: It would be better if CXXBasePath had the base specifier for
  2476. // the nearest virtual base.
  2477. unsigned Start = 0;
  2478. for (unsigned I = Path.size(); I != 0; --I) {
  2479. if (Path[I - 1].Base->isVirtual()) {
  2480. Start = I - 1;
  2481. break;
  2482. }
  2483. }
  2484. // Now add all bases.
  2485. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2486. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2487. }
  2488. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2489. CXXCastPath &BasePathArray) {
  2490. assert(BasePathArray.empty() && "Base path array must be empty!");
  2491. assert(Paths.isRecordingPaths() && "Must record paths!");
  2492. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2493. }
  2494. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2495. /// conversion (where Derived and Base are class types) is
  2496. /// well-formed, meaning that the conversion is unambiguous (and
  2497. /// that all of the base classes are accessible). Returns true
  2498. /// and emits a diagnostic if the code is ill-formed, returns false
  2499. /// otherwise. Loc is the location where this routine should point to
  2500. /// if there is an error, and Range is the source range to highlight
  2501. /// if there is an error.
  2502. ///
  2503. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2504. /// diagnostic for the respective type of error will be suppressed, but the
  2505. /// check for ill-formed code will still be performed.
  2506. bool
  2507. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2508. unsigned InaccessibleBaseID,
  2509. unsigned AmbigiousBaseConvID,
  2510. SourceLocation Loc, SourceRange Range,
  2511. DeclarationName Name,
  2512. CXXCastPath *BasePath,
  2513. bool IgnoreAccess) {
  2514. // First, determine whether the path from Derived to Base is
  2515. // ambiguous. This is slightly more expensive than checking whether
  2516. // the Derived to Base conversion exists, because here we need to
  2517. // explore multiple paths to determine if there is an ambiguity.
  2518. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2519. /*DetectVirtual=*/false);
  2520. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2521. if (!DerivationOkay)
  2522. return true;
  2523. const CXXBasePath *Path = nullptr;
  2524. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2525. Path = &Paths.front();
  2526. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2527. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2528. // user to access such bases.
  2529. if (!Path && getLangOpts().MSVCCompat) {
  2530. for (const CXXBasePath &PossiblePath : Paths) {
  2531. if (PossiblePath.size() == 1) {
  2532. Path = &PossiblePath;
  2533. if (AmbigiousBaseConvID)
  2534. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2535. << Base << Derived << Range;
  2536. break;
  2537. }
  2538. }
  2539. }
  2540. if (Path) {
  2541. if (!IgnoreAccess) {
  2542. // Check that the base class can be accessed.
  2543. switch (
  2544. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2545. case AR_inaccessible:
  2546. return true;
  2547. case AR_accessible:
  2548. case AR_dependent:
  2549. case AR_delayed:
  2550. break;
  2551. }
  2552. }
  2553. // Build a base path if necessary.
  2554. if (BasePath)
  2555. ::BuildBasePathArray(*Path, *BasePath);
  2556. return false;
  2557. }
  2558. if (AmbigiousBaseConvID) {
  2559. // We know that the derived-to-base conversion is ambiguous, and
  2560. // we're going to produce a diagnostic. Perform the derived-to-base
  2561. // search just one more time to compute all of the possible paths so
  2562. // that we can print them out. This is more expensive than any of
  2563. // the previous derived-to-base checks we've done, but at this point
  2564. // performance isn't as much of an issue.
  2565. Paths.clear();
  2566. Paths.setRecordingPaths(true);
  2567. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2568. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2569. (void)StillOkay;
  2570. // Build up a textual representation of the ambiguous paths, e.g.,
  2571. // D -> B -> A, that will be used to illustrate the ambiguous
  2572. // conversions in the diagnostic. We only print one of the paths
  2573. // to each base class subobject.
  2574. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2575. Diag(Loc, AmbigiousBaseConvID)
  2576. << Derived << Base << PathDisplayStr << Range << Name;
  2577. }
  2578. return true;
  2579. }
  2580. bool
  2581. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2582. SourceLocation Loc, SourceRange Range,
  2583. CXXCastPath *BasePath,
  2584. bool IgnoreAccess) {
  2585. return CheckDerivedToBaseConversion(
  2586. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2587. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2588. BasePath, IgnoreAccess);
  2589. }
  2590. /// Builds a string representing ambiguous paths from a
  2591. /// specific derived class to different subobjects of the same base
  2592. /// class.
  2593. ///
  2594. /// This function builds a string that can be used in error messages
  2595. /// to show the different paths that one can take through the
  2596. /// inheritance hierarchy to go from the derived class to different
  2597. /// subobjects of a base class. The result looks something like this:
  2598. /// @code
  2599. /// struct D -> struct B -> struct A
  2600. /// struct D -> struct C -> struct A
  2601. /// @endcode
  2602. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2603. std::string PathDisplayStr;
  2604. std::set<unsigned> DisplayedPaths;
  2605. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2606. Path != Paths.end(); ++Path) {
  2607. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2608. // We haven't displayed a path to this particular base
  2609. // class subobject yet.
  2610. PathDisplayStr += "\n ";
  2611. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2612. for (CXXBasePath::const_iterator Element = Path->begin();
  2613. Element != Path->end(); ++Element)
  2614. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2615. }
  2616. }
  2617. return PathDisplayStr;
  2618. }
  2619. //===----------------------------------------------------------------------===//
  2620. // C++ class member Handling
  2621. //===----------------------------------------------------------------------===//
  2622. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2623. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2624. SourceLocation ColonLoc,
  2625. const ParsedAttributesView &Attrs) {
  2626. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2627. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2628. ASLoc, ColonLoc);
  2629. CurContext->addHiddenDecl(ASDecl);
  2630. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2631. }
  2632. /// CheckOverrideControl - Check C++11 override control semantics.
  2633. void Sema::CheckOverrideControl(NamedDecl *D) {
  2634. if (D->isInvalidDecl())
  2635. return;
  2636. // We only care about "override" and "final" declarations.
  2637. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2638. return;
  2639. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2640. // We can't check dependent instance methods.
  2641. if (MD && MD->isInstance() &&
  2642. (MD->getParent()->hasAnyDependentBases() ||
  2643. MD->getType()->isDependentType()))
  2644. return;
  2645. if (MD && !MD->isVirtual()) {
  2646. // If we have a non-virtual method, check if if hides a virtual method.
  2647. // (In that case, it's most likely the method has the wrong type.)
  2648. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2649. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2650. if (!OverloadedMethods.empty()) {
  2651. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2652. Diag(OA->getLocation(),
  2653. diag::override_keyword_hides_virtual_member_function)
  2654. << "override" << (OverloadedMethods.size() > 1);
  2655. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2656. Diag(FA->getLocation(),
  2657. diag::override_keyword_hides_virtual_member_function)
  2658. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2659. << (OverloadedMethods.size() > 1);
  2660. }
  2661. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2662. MD->setInvalidDecl();
  2663. return;
  2664. }
  2665. // Fall through into the general case diagnostic.
  2666. // FIXME: We might want to attempt typo correction here.
  2667. }
  2668. if (!MD || !MD->isVirtual()) {
  2669. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2670. Diag(OA->getLocation(),
  2671. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2672. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2673. D->dropAttr<OverrideAttr>();
  2674. }
  2675. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2676. Diag(FA->getLocation(),
  2677. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2678. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2679. << FixItHint::CreateRemoval(FA->getLocation());
  2680. D->dropAttr<FinalAttr>();
  2681. }
  2682. return;
  2683. }
  2684. // C++11 [class.virtual]p5:
  2685. // If a function is marked with the virt-specifier override and
  2686. // does not override a member function of a base class, the program is
  2687. // ill-formed.
  2688. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2689. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2690. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2691. << MD->getDeclName();
  2692. }
  2693. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2694. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2695. return;
  2696. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2697. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2698. return;
  2699. SourceLocation Loc = MD->getLocation();
  2700. SourceLocation SpellingLoc = Loc;
  2701. if (getSourceManager().isMacroArgExpansion(Loc))
  2702. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2703. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2704. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2705. return;
  2706. if (MD->size_overridden_methods() > 0) {
  2707. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2708. ? diag::warn_destructor_marked_not_override_overriding
  2709. : diag::warn_function_marked_not_override_overriding;
  2710. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2711. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2712. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2713. }
  2714. }
  2715. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2716. /// function overrides a virtual member function marked 'final', according to
  2717. /// C++11 [class.virtual]p4.
  2718. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2719. const CXXMethodDecl *Old) {
  2720. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2721. if (!FA)
  2722. return false;
  2723. Diag(New->getLocation(), diag::err_final_function_overridden)
  2724. << New->getDeclName()
  2725. << FA->isSpelledAsSealed();
  2726. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2727. return true;
  2728. }
  2729. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2730. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2731. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2732. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2733. return !RD->isCompleteDefinition() ||
  2734. !RD->hasTrivialDefaultConstructor() ||
  2735. !RD->hasTrivialDestructor();
  2736. return false;
  2737. }
  2738. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2739. ParsedAttributesView::const_iterator Itr =
  2740. llvm::find_if(list, [](const ParsedAttr &AL) {
  2741. return AL.isDeclspecPropertyAttribute();
  2742. });
  2743. if (Itr != list.end())
  2744. return &*Itr;
  2745. return nullptr;
  2746. }
  2747. // Check if there is a field shadowing.
  2748. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2749. DeclarationName FieldName,
  2750. const CXXRecordDecl *RD,
  2751. bool DeclIsField) {
  2752. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2753. return;
  2754. // To record a shadowed field in a base
  2755. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2756. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2757. CXXBasePath &Path) {
  2758. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2759. // Record an ambiguous path directly
  2760. if (Bases.find(Base) != Bases.end())
  2761. return true;
  2762. for (const auto Field : Base->lookup(FieldName)) {
  2763. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2764. Field->getAccess() != AS_private) {
  2765. assert(Field->getAccess() != AS_none);
  2766. assert(Bases.find(Base) == Bases.end());
  2767. Bases[Base] = Field;
  2768. return true;
  2769. }
  2770. }
  2771. return false;
  2772. };
  2773. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2774. /*DetectVirtual=*/true);
  2775. if (!RD->lookupInBases(FieldShadowed, Paths))
  2776. return;
  2777. for (const auto &P : Paths) {
  2778. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2779. auto It = Bases.find(Base);
  2780. // Skip duplicated bases
  2781. if (It == Bases.end())
  2782. continue;
  2783. auto BaseField = It->second;
  2784. assert(BaseField->getAccess() != AS_private);
  2785. if (AS_none !=
  2786. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2787. Diag(Loc, diag::warn_shadow_field)
  2788. << FieldName << RD << Base << DeclIsField;
  2789. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2790. Bases.erase(It);
  2791. }
  2792. }
  2793. }
  2794. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2795. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2796. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2797. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2798. /// present (but parsing it has been deferred).
  2799. NamedDecl *
  2800. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2801. MultiTemplateParamsArg TemplateParameterLists,
  2802. Expr *BW, const VirtSpecifiers &VS,
  2803. InClassInitStyle InitStyle) {
  2804. const DeclSpec &DS = D.getDeclSpec();
  2805. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2806. DeclarationName Name = NameInfo.getName();
  2807. SourceLocation Loc = NameInfo.getLoc();
  2808. // For anonymous bitfields, the location should point to the type.
  2809. if (Loc.isInvalid())
  2810. Loc = D.getBeginLoc();
  2811. Expr *BitWidth = static_cast<Expr*>(BW);
  2812. assert(isa<CXXRecordDecl>(CurContext));
  2813. assert(!DS.isFriendSpecified());
  2814. bool isFunc = D.isDeclarationOfFunction();
  2815. const ParsedAttr *MSPropertyAttr =
  2816. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2817. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2818. // The Microsoft extension __interface only permits public member functions
  2819. // and prohibits constructors, destructors, operators, non-public member
  2820. // functions, static methods and data members.
  2821. unsigned InvalidDecl;
  2822. bool ShowDeclName = true;
  2823. if (!isFunc &&
  2824. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2825. InvalidDecl = 0;
  2826. else if (!isFunc)
  2827. InvalidDecl = 1;
  2828. else if (AS != AS_public)
  2829. InvalidDecl = 2;
  2830. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2831. InvalidDecl = 3;
  2832. else switch (Name.getNameKind()) {
  2833. case DeclarationName::CXXConstructorName:
  2834. InvalidDecl = 4;
  2835. ShowDeclName = false;
  2836. break;
  2837. case DeclarationName::CXXDestructorName:
  2838. InvalidDecl = 5;
  2839. ShowDeclName = false;
  2840. break;
  2841. case DeclarationName::CXXOperatorName:
  2842. case DeclarationName::CXXConversionFunctionName:
  2843. InvalidDecl = 6;
  2844. break;
  2845. default:
  2846. InvalidDecl = 0;
  2847. break;
  2848. }
  2849. if (InvalidDecl) {
  2850. if (ShowDeclName)
  2851. Diag(Loc, diag::err_invalid_member_in_interface)
  2852. << (InvalidDecl-1) << Name;
  2853. else
  2854. Diag(Loc, diag::err_invalid_member_in_interface)
  2855. << (InvalidDecl-1) << "";
  2856. return nullptr;
  2857. }
  2858. }
  2859. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2860. // duration (auto, register) or with the extern storage-class-specifier.
  2861. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2862. // data members and cannot be applied to names declared const or static,
  2863. // and cannot be applied to reference members.
  2864. switch (DS.getStorageClassSpec()) {
  2865. case DeclSpec::SCS_unspecified:
  2866. case DeclSpec::SCS_typedef:
  2867. case DeclSpec::SCS_static:
  2868. break;
  2869. case DeclSpec::SCS_mutable:
  2870. if (isFunc) {
  2871. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2872. // FIXME: It would be nicer if the keyword was ignored only for this
  2873. // declarator. Otherwise we could get follow-up errors.
  2874. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2875. }
  2876. break;
  2877. default:
  2878. Diag(DS.getStorageClassSpecLoc(),
  2879. diag::err_storageclass_invalid_for_member);
  2880. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2881. break;
  2882. }
  2883. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2884. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2885. !isFunc);
  2886. if (DS.hasConstexprSpecifier() && isInstField) {
  2887. SemaDiagnosticBuilder B =
  2888. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2889. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2890. if (InitStyle == ICIS_NoInit) {
  2891. B << 0 << 0;
  2892. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2893. B << FixItHint::CreateRemoval(ConstexprLoc);
  2894. else {
  2895. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2896. D.getMutableDeclSpec().ClearConstexprSpec();
  2897. const char *PrevSpec;
  2898. unsigned DiagID;
  2899. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2900. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2901. (void)Failed;
  2902. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2903. }
  2904. } else {
  2905. B << 1;
  2906. const char *PrevSpec;
  2907. unsigned DiagID;
  2908. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2909. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2910. Context.getPrintingPolicy())) {
  2911. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2912. "This is the only DeclSpec that should fail to be applied");
  2913. B << 1;
  2914. } else {
  2915. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2916. isInstField = false;
  2917. }
  2918. }
  2919. }
  2920. NamedDecl *Member;
  2921. if (isInstField) {
  2922. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2923. // Data members must have identifiers for names.
  2924. if (!Name.isIdentifier()) {
  2925. Diag(Loc, diag::err_bad_variable_name)
  2926. << Name;
  2927. return nullptr;
  2928. }
  2929. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2930. // Member field could not be with "template" keyword.
  2931. // So TemplateParameterLists should be empty in this case.
  2932. if (TemplateParameterLists.size()) {
  2933. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2934. if (TemplateParams->size()) {
  2935. // There is no such thing as a member field template.
  2936. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2937. << II
  2938. << SourceRange(TemplateParams->getTemplateLoc(),
  2939. TemplateParams->getRAngleLoc());
  2940. } else {
  2941. // There is an extraneous 'template<>' for this member.
  2942. Diag(TemplateParams->getTemplateLoc(),
  2943. diag::err_template_member_noparams)
  2944. << II
  2945. << SourceRange(TemplateParams->getTemplateLoc(),
  2946. TemplateParams->getRAngleLoc());
  2947. }
  2948. return nullptr;
  2949. }
  2950. if (SS.isSet() && !SS.isInvalid()) {
  2951. // The user provided a superfluous scope specifier inside a class
  2952. // definition:
  2953. //
  2954. // class X {
  2955. // int X::member;
  2956. // };
  2957. if (DeclContext *DC = computeDeclContext(SS, false))
  2958. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2959. D.getName().getKind() ==
  2960. UnqualifiedIdKind::IK_TemplateId);
  2961. else
  2962. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2963. << Name << SS.getRange();
  2964. SS.clear();
  2965. }
  2966. if (MSPropertyAttr) {
  2967. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2968. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2969. if (!Member)
  2970. return nullptr;
  2971. isInstField = false;
  2972. } else {
  2973. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2974. BitWidth, InitStyle, AS);
  2975. if (!Member)
  2976. return nullptr;
  2977. }
  2978. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2979. } else {
  2980. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2981. if (!Member)
  2982. return nullptr;
  2983. // Non-instance-fields can't have a bitfield.
  2984. if (BitWidth) {
  2985. if (Member->isInvalidDecl()) {
  2986. // don't emit another diagnostic.
  2987. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2988. // C++ 9.6p3: A bit-field shall not be a static member.
  2989. // "static member 'A' cannot be a bit-field"
  2990. Diag(Loc, diag::err_static_not_bitfield)
  2991. << Name << BitWidth->getSourceRange();
  2992. } else if (isa<TypedefDecl>(Member)) {
  2993. // "typedef member 'x' cannot be a bit-field"
  2994. Diag(Loc, diag::err_typedef_not_bitfield)
  2995. << Name << BitWidth->getSourceRange();
  2996. } else {
  2997. // A function typedef ("typedef int f(); f a;").
  2998. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2999. Diag(Loc, diag::err_not_integral_type_bitfield)
  3000. << Name << cast<ValueDecl>(Member)->getType()
  3001. << BitWidth->getSourceRange();
  3002. }
  3003. BitWidth = nullptr;
  3004. Member->setInvalidDecl();
  3005. }
  3006. NamedDecl *NonTemplateMember = Member;
  3007. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  3008. NonTemplateMember = FunTmpl->getTemplatedDecl();
  3009. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  3010. NonTemplateMember = VarTmpl->getTemplatedDecl();
  3011. Member->setAccess(AS);
  3012. // If we have declared a member function template or static data member
  3013. // template, set the access of the templated declaration as well.
  3014. if (NonTemplateMember != Member)
  3015. NonTemplateMember->setAccess(AS);
  3016. // C++ [temp.deduct.guide]p3:
  3017. // A deduction guide [...] for a member class template [shall be
  3018. // declared] with the same access [as the template].
  3019. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  3020. auto *TD = DG->getDeducedTemplate();
  3021. // Access specifiers are only meaningful if both the template and the
  3022. // deduction guide are from the same scope.
  3023. if (AS != TD->getAccess() &&
  3024. TD->getDeclContext()->getRedeclContext()->Equals(
  3025. DG->getDeclContext()->getRedeclContext())) {
  3026. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  3027. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  3028. << TD->getAccess();
  3029. const AccessSpecDecl *LastAccessSpec = nullptr;
  3030. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  3031. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  3032. LastAccessSpec = AccessSpec;
  3033. }
  3034. assert(LastAccessSpec && "differing access with no access specifier");
  3035. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  3036. << AS;
  3037. }
  3038. }
  3039. }
  3040. if (VS.isOverrideSpecified())
  3041. Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
  3042. AttributeCommonInfo::AS_Keyword));
  3043. if (VS.isFinalSpecified())
  3044. Member->addAttr(FinalAttr::Create(
  3045. Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
  3046. static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
  3047. if (VS.getLastLocation().isValid()) {
  3048. // Update the end location of a method that has a virt-specifiers.
  3049. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  3050. MD->setRangeEnd(VS.getLastLocation());
  3051. }
  3052. CheckOverrideControl(Member);
  3053. assert((Name || isInstField) && "No identifier for non-field ?");
  3054. if (isInstField) {
  3055. FieldDecl *FD = cast<FieldDecl>(Member);
  3056. FieldCollector->Add(FD);
  3057. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  3058. // Remember all explicit private FieldDecls that have a name, no side
  3059. // effects and are not part of a dependent type declaration.
  3060. if (!FD->isImplicit() && FD->getDeclName() &&
  3061. FD->getAccess() == AS_private &&
  3062. !FD->hasAttr<UnusedAttr>() &&
  3063. !FD->getParent()->isDependentContext() &&
  3064. !InitializationHasSideEffects(*FD))
  3065. UnusedPrivateFields.insert(FD);
  3066. }
  3067. }
  3068. return Member;
  3069. }
  3070. namespace {
  3071. class UninitializedFieldVisitor
  3072. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  3073. Sema &S;
  3074. // List of Decls to generate a warning on. Also remove Decls that become
  3075. // initialized.
  3076. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  3077. // List of base classes of the record. Classes are removed after their
  3078. // initializers.
  3079. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  3080. // Vector of decls to be removed from the Decl set prior to visiting the
  3081. // nodes. These Decls may have been initialized in the prior initializer.
  3082. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  3083. // If non-null, add a note to the warning pointing back to the constructor.
  3084. const CXXConstructorDecl *Constructor;
  3085. // Variables to hold state when processing an initializer list. When
  3086. // InitList is true, special case initialization of FieldDecls matching
  3087. // InitListFieldDecl.
  3088. bool InitList;
  3089. FieldDecl *InitListFieldDecl;
  3090. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  3091. public:
  3092. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  3093. UninitializedFieldVisitor(Sema &S,
  3094. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  3095. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  3096. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  3097. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  3098. // Returns true if the use of ME is not an uninitialized use.
  3099. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  3100. bool CheckReferenceOnly) {
  3101. llvm::SmallVector<FieldDecl*, 4> Fields;
  3102. bool ReferenceField = false;
  3103. while (ME) {
  3104. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  3105. if (!FD)
  3106. return false;
  3107. Fields.push_back(FD);
  3108. if (FD->getType()->isReferenceType())
  3109. ReferenceField = true;
  3110. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  3111. }
  3112. // Binding a reference to an uninitialized field is not an
  3113. // uninitialized use.
  3114. if (CheckReferenceOnly && !ReferenceField)
  3115. return true;
  3116. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  3117. // Discard the first field since it is the field decl that is being
  3118. // initialized.
  3119. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  3120. UsedFieldIndex.push_back((*I)->getFieldIndex());
  3121. }
  3122. for (auto UsedIter = UsedFieldIndex.begin(),
  3123. UsedEnd = UsedFieldIndex.end(),
  3124. OrigIter = InitFieldIndex.begin(),
  3125. OrigEnd = InitFieldIndex.end();
  3126. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  3127. if (*UsedIter < *OrigIter)
  3128. return true;
  3129. if (*UsedIter > *OrigIter)
  3130. break;
  3131. }
  3132. return false;
  3133. }
  3134. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  3135. bool AddressOf) {
  3136. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  3137. return;
  3138. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  3139. // or union.
  3140. MemberExpr *FieldME = ME;
  3141. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  3142. Expr *Base = ME;
  3143. while (MemberExpr *SubME =
  3144. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  3145. if (isa<VarDecl>(SubME->getMemberDecl()))
  3146. return;
  3147. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  3148. if (!FD->isAnonymousStructOrUnion())
  3149. FieldME = SubME;
  3150. if (!FieldME->getType().isPODType(S.Context))
  3151. AllPODFields = false;
  3152. Base = SubME->getBase();
  3153. }
  3154. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  3155. return;
  3156. if (AddressOf && AllPODFields)
  3157. return;
  3158. ValueDecl* FoundVD = FieldME->getMemberDecl();
  3159. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  3160. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  3161. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  3162. }
  3163. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  3164. QualType T = BaseCast->getType();
  3165. if (T->isPointerType() &&
  3166. BaseClasses.count(T->getPointeeType())) {
  3167. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  3168. << T->getPointeeType() << FoundVD;
  3169. }
  3170. }
  3171. }
  3172. if (!Decls.count(FoundVD))
  3173. return;
  3174. const bool IsReference = FoundVD->getType()->isReferenceType();
  3175. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3176. // Special checking for initializer lists.
  3177. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3178. return;
  3179. }
  3180. } else {
  3181. // Prevent double warnings on use of unbounded references.
  3182. if (CheckReferenceOnly && !IsReference)
  3183. return;
  3184. }
  3185. unsigned diag = IsReference
  3186. ? diag::warn_reference_field_is_uninit
  3187. : diag::warn_field_is_uninit;
  3188. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3189. if (Constructor)
  3190. S.Diag(Constructor->getLocation(),
  3191. diag::note_uninit_in_this_constructor)
  3192. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3193. }
  3194. void HandleValue(Expr *E, bool AddressOf) {
  3195. E = E->IgnoreParens();
  3196. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3197. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3198. AddressOf /*AddressOf*/);
  3199. return;
  3200. }
  3201. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3202. Visit(CO->getCond());
  3203. HandleValue(CO->getTrueExpr(), AddressOf);
  3204. HandleValue(CO->getFalseExpr(), AddressOf);
  3205. return;
  3206. }
  3207. if (BinaryConditionalOperator *BCO =
  3208. dyn_cast<BinaryConditionalOperator>(E)) {
  3209. Visit(BCO->getCond());
  3210. HandleValue(BCO->getFalseExpr(), AddressOf);
  3211. return;
  3212. }
  3213. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3214. HandleValue(OVE->getSourceExpr(), AddressOf);
  3215. return;
  3216. }
  3217. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3218. switch (BO->getOpcode()) {
  3219. default:
  3220. break;
  3221. case(BO_PtrMemD):
  3222. case(BO_PtrMemI):
  3223. HandleValue(BO->getLHS(), AddressOf);
  3224. Visit(BO->getRHS());
  3225. return;
  3226. case(BO_Comma):
  3227. Visit(BO->getLHS());
  3228. HandleValue(BO->getRHS(), AddressOf);
  3229. return;
  3230. }
  3231. }
  3232. Visit(E);
  3233. }
  3234. void CheckInitListExpr(InitListExpr *ILE) {
  3235. InitFieldIndex.push_back(0);
  3236. for (auto Child : ILE->children()) {
  3237. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3238. CheckInitListExpr(SubList);
  3239. } else {
  3240. Visit(Child);
  3241. }
  3242. ++InitFieldIndex.back();
  3243. }
  3244. InitFieldIndex.pop_back();
  3245. }
  3246. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3247. FieldDecl *Field, const Type *BaseClass) {
  3248. // Remove Decls that may have been initialized in the previous
  3249. // initializer.
  3250. for (ValueDecl* VD : DeclsToRemove)
  3251. Decls.erase(VD);
  3252. DeclsToRemove.clear();
  3253. Constructor = FieldConstructor;
  3254. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3255. if (ILE && Field) {
  3256. InitList = true;
  3257. InitListFieldDecl = Field;
  3258. InitFieldIndex.clear();
  3259. CheckInitListExpr(ILE);
  3260. } else {
  3261. InitList = false;
  3262. Visit(E);
  3263. }
  3264. if (Field)
  3265. Decls.erase(Field);
  3266. if (BaseClass)
  3267. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3268. }
  3269. void VisitMemberExpr(MemberExpr *ME) {
  3270. // All uses of unbounded reference fields will warn.
  3271. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3272. }
  3273. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3274. if (E->getCastKind() == CK_LValueToRValue) {
  3275. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3276. return;
  3277. }
  3278. Inherited::VisitImplicitCastExpr(E);
  3279. }
  3280. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3281. if (E->getConstructor()->isCopyConstructor()) {
  3282. Expr *ArgExpr = E->getArg(0);
  3283. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3284. if (ILE->getNumInits() == 1)
  3285. ArgExpr = ILE->getInit(0);
  3286. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3287. if (ICE->getCastKind() == CK_NoOp)
  3288. ArgExpr = ICE->getSubExpr();
  3289. HandleValue(ArgExpr, false /*AddressOf*/);
  3290. return;
  3291. }
  3292. Inherited::VisitCXXConstructExpr(E);
  3293. }
  3294. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3295. Expr *Callee = E->getCallee();
  3296. if (isa<MemberExpr>(Callee)) {
  3297. HandleValue(Callee, false /*AddressOf*/);
  3298. for (auto Arg : E->arguments())
  3299. Visit(Arg);
  3300. return;
  3301. }
  3302. Inherited::VisitCXXMemberCallExpr(E);
  3303. }
  3304. void VisitCallExpr(CallExpr *E) {
  3305. // Treat std::move as a use.
  3306. if (E->isCallToStdMove()) {
  3307. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3308. return;
  3309. }
  3310. Inherited::VisitCallExpr(E);
  3311. }
  3312. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3313. Expr *Callee = E->getCallee();
  3314. if (isa<UnresolvedLookupExpr>(Callee))
  3315. return Inherited::VisitCXXOperatorCallExpr(E);
  3316. Visit(Callee);
  3317. for (auto Arg : E->arguments())
  3318. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3319. }
  3320. void VisitBinaryOperator(BinaryOperator *E) {
  3321. // If a field assignment is detected, remove the field from the
  3322. // uninitiailized field set.
  3323. if (E->getOpcode() == BO_Assign)
  3324. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3325. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3326. if (!FD->getType()->isReferenceType())
  3327. DeclsToRemove.push_back(FD);
  3328. if (E->isCompoundAssignmentOp()) {
  3329. HandleValue(E->getLHS(), false /*AddressOf*/);
  3330. Visit(E->getRHS());
  3331. return;
  3332. }
  3333. Inherited::VisitBinaryOperator(E);
  3334. }
  3335. void VisitUnaryOperator(UnaryOperator *E) {
  3336. if (E->isIncrementDecrementOp()) {
  3337. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3338. return;
  3339. }
  3340. if (E->getOpcode() == UO_AddrOf) {
  3341. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3342. HandleValue(ME->getBase(), true /*AddressOf*/);
  3343. return;
  3344. }
  3345. }
  3346. Inherited::VisitUnaryOperator(E);
  3347. }
  3348. };
  3349. // Diagnose value-uses of fields to initialize themselves, e.g.
  3350. // foo(foo)
  3351. // where foo is not also a parameter to the constructor.
  3352. // Also diagnose across field uninitialized use such as
  3353. // x(y), y(x)
  3354. // TODO: implement -Wuninitialized and fold this into that framework.
  3355. static void DiagnoseUninitializedFields(
  3356. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3357. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3358. Constructor->getLocation())) {
  3359. return;
  3360. }
  3361. if (Constructor->isInvalidDecl())
  3362. return;
  3363. const CXXRecordDecl *RD = Constructor->getParent();
  3364. if (RD->getDescribedClassTemplate())
  3365. return;
  3366. // Holds fields that are uninitialized.
  3367. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3368. // At the beginning, all fields are uninitialized.
  3369. for (auto *I : RD->decls()) {
  3370. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3371. UninitializedFields.insert(FD);
  3372. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3373. UninitializedFields.insert(IFD->getAnonField());
  3374. }
  3375. }
  3376. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3377. for (auto I : RD->bases())
  3378. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3379. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3380. return;
  3381. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3382. UninitializedFields,
  3383. UninitializedBaseClasses);
  3384. for (const auto *FieldInit : Constructor->inits()) {
  3385. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3386. break;
  3387. Expr *InitExpr = FieldInit->getInit();
  3388. if (!InitExpr)
  3389. continue;
  3390. if (CXXDefaultInitExpr *Default =
  3391. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3392. InitExpr = Default->getExpr();
  3393. if (!InitExpr)
  3394. continue;
  3395. // In class initializers will point to the constructor.
  3396. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3397. FieldInit->getAnyMember(),
  3398. FieldInit->getBaseClass());
  3399. } else {
  3400. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3401. FieldInit->getAnyMember(),
  3402. FieldInit->getBaseClass());
  3403. }
  3404. }
  3405. }
  3406. } // namespace
  3407. /// Enter a new C++ default initializer scope. After calling this, the
  3408. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3409. /// parsing or instantiating the initializer failed.
  3410. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3411. // Create a synthetic function scope to represent the call to the constructor
  3412. // that notionally surrounds a use of this initializer.
  3413. PushFunctionScope();
  3414. }
  3415. /// This is invoked after parsing an in-class initializer for a
  3416. /// non-static C++ class member, and after instantiating an in-class initializer
  3417. /// in a class template. Such actions are deferred until the class is complete.
  3418. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3419. SourceLocation InitLoc,
  3420. Expr *InitExpr) {
  3421. // Pop the notional constructor scope we created earlier.
  3422. PopFunctionScopeInfo(nullptr, D);
  3423. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3424. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3425. "must set init style when field is created");
  3426. if (!InitExpr) {
  3427. D->setInvalidDecl();
  3428. if (FD)
  3429. FD->removeInClassInitializer();
  3430. return;
  3431. }
  3432. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3433. FD->setInvalidDecl();
  3434. FD->removeInClassInitializer();
  3435. return;
  3436. }
  3437. ExprResult Init = InitExpr;
  3438. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3439. InitializedEntity Entity =
  3440. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3441. InitializationKind Kind =
  3442. FD->getInClassInitStyle() == ICIS_ListInit
  3443. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3444. InitExpr->getBeginLoc(),
  3445. InitExpr->getEndLoc())
  3446. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3447. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3448. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3449. if (Init.isInvalid()) {
  3450. FD->setInvalidDecl();
  3451. return;
  3452. }
  3453. }
  3454. // C++11 [class.base.init]p7:
  3455. // The initialization of each base and member constitutes a
  3456. // full-expression.
  3457. Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
  3458. if (Init.isInvalid()) {
  3459. FD->setInvalidDecl();
  3460. return;
  3461. }
  3462. InitExpr = Init.get();
  3463. FD->setInClassInitializer(InitExpr);
  3464. }
  3465. /// Find the direct and/or virtual base specifiers that
  3466. /// correspond to the given base type, for use in base initialization
  3467. /// within a constructor.
  3468. static bool FindBaseInitializer(Sema &SemaRef,
  3469. CXXRecordDecl *ClassDecl,
  3470. QualType BaseType,
  3471. const CXXBaseSpecifier *&DirectBaseSpec,
  3472. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3473. // First, check for a direct base class.
  3474. DirectBaseSpec = nullptr;
  3475. for (const auto &Base : ClassDecl->bases()) {
  3476. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3477. // We found a direct base of this type. That's what we're
  3478. // initializing.
  3479. DirectBaseSpec = &Base;
  3480. break;
  3481. }
  3482. }
  3483. // Check for a virtual base class.
  3484. // FIXME: We might be able to short-circuit this if we know in advance that
  3485. // there are no virtual bases.
  3486. VirtualBaseSpec = nullptr;
  3487. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3488. // We haven't found a base yet; search the class hierarchy for a
  3489. // virtual base class.
  3490. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3491. /*DetectVirtual=*/false);
  3492. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3493. SemaRef.Context.getTypeDeclType(ClassDecl),
  3494. BaseType, Paths)) {
  3495. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3496. Path != Paths.end(); ++Path) {
  3497. if (Path->back().Base->isVirtual()) {
  3498. VirtualBaseSpec = Path->back().Base;
  3499. break;
  3500. }
  3501. }
  3502. }
  3503. }
  3504. return DirectBaseSpec || VirtualBaseSpec;
  3505. }
  3506. /// Handle a C++ member initializer using braced-init-list syntax.
  3507. MemInitResult
  3508. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3509. Scope *S,
  3510. CXXScopeSpec &SS,
  3511. IdentifierInfo *MemberOrBase,
  3512. ParsedType TemplateTypeTy,
  3513. const DeclSpec &DS,
  3514. SourceLocation IdLoc,
  3515. Expr *InitList,
  3516. SourceLocation EllipsisLoc) {
  3517. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3518. DS, IdLoc, InitList,
  3519. EllipsisLoc);
  3520. }
  3521. /// Handle a C++ member initializer using parentheses syntax.
  3522. MemInitResult
  3523. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3524. Scope *S,
  3525. CXXScopeSpec &SS,
  3526. IdentifierInfo *MemberOrBase,
  3527. ParsedType TemplateTypeTy,
  3528. const DeclSpec &DS,
  3529. SourceLocation IdLoc,
  3530. SourceLocation LParenLoc,
  3531. ArrayRef<Expr *> Args,
  3532. SourceLocation RParenLoc,
  3533. SourceLocation EllipsisLoc) {
  3534. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3535. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3536. DS, IdLoc, List, EllipsisLoc);
  3537. }
  3538. namespace {
  3539. // Callback to only accept typo corrections that can be a valid C++ member
  3540. // intializer: either a non-static field member or a base class.
  3541. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3542. public:
  3543. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3544. : ClassDecl(ClassDecl) {}
  3545. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3546. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3547. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3548. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3549. return isa<TypeDecl>(ND);
  3550. }
  3551. return false;
  3552. }
  3553. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3554. return std::make_unique<MemInitializerValidatorCCC>(*this);
  3555. }
  3556. private:
  3557. CXXRecordDecl *ClassDecl;
  3558. };
  3559. }
  3560. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3561. CXXScopeSpec &SS,
  3562. ParsedType TemplateTypeTy,
  3563. IdentifierInfo *MemberOrBase) {
  3564. if (SS.getScopeRep() || TemplateTypeTy)
  3565. return nullptr;
  3566. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3567. if (Result.empty())
  3568. return nullptr;
  3569. ValueDecl *Member;
  3570. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3571. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3572. return Member;
  3573. return nullptr;
  3574. }
  3575. /// Handle a C++ member initializer.
  3576. MemInitResult
  3577. Sema::BuildMemInitializer(Decl *ConstructorD,
  3578. Scope *S,
  3579. CXXScopeSpec &SS,
  3580. IdentifierInfo *MemberOrBase,
  3581. ParsedType TemplateTypeTy,
  3582. const DeclSpec &DS,
  3583. SourceLocation IdLoc,
  3584. Expr *Init,
  3585. SourceLocation EllipsisLoc) {
  3586. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3587. if (!Res.isUsable())
  3588. return true;
  3589. Init = Res.get();
  3590. if (!ConstructorD)
  3591. return true;
  3592. AdjustDeclIfTemplate(ConstructorD);
  3593. CXXConstructorDecl *Constructor
  3594. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3595. if (!Constructor) {
  3596. // The user wrote a constructor initializer on a function that is
  3597. // not a C++ constructor. Ignore the error for now, because we may
  3598. // have more member initializers coming; we'll diagnose it just
  3599. // once in ActOnMemInitializers.
  3600. return true;
  3601. }
  3602. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3603. // C++ [class.base.init]p2:
  3604. // Names in a mem-initializer-id are looked up in the scope of the
  3605. // constructor's class and, if not found in that scope, are looked
  3606. // up in the scope containing the constructor's definition.
  3607. // [Note: if the constructor's class contains a member with the
  3608. // same name as a direct or virtual base class of the class, a
  3609. // mem-initializer-id naming the member or base class and composed
  3610. // of a single identifier refers to the class member. A
  3611. // mem-initializer-id for the hidden base class may be specified
  3612. // using a qualified name. ]
  3613. // Look for a member, first.
  3614. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3615. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3616. if (EllipsisLoc.isValid())
  3617. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3618. << MemberOrBase
  3619. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3620. return BuildMemberInitializer(Member, Init, IdLoc);
  3621. }
  3622. // It didn't name a member, so see if it names a class.
  3623. QualType BaseType;
  3624. TypeSourceInfo *TInfo = nullptr;
  3625. if (TemplateTypeTy) {
  3626. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3627. if (BaseType.isNull())
  3628. return true;
  3629. } else if (DS.getTypeSpecType() == TST_decltype) {
  3630. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3631. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3632. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3633. return true;
  3634. } else {
  3635. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3636. LookupParsedName(R, S, &SS);
  3637. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3638. if (!TyD) {
  3639. if (R.isAmbiguous()) return true;
  3640. // We don't want access-control diagnostics here.
  3641. R.suppressDiagnostics();
  3642. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3643. bool NotUnknownSpecialization = false;
  3644. DeclContext *DC = computeDeclContext(SS, false);
  3645. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3646. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3647. if (!NotUnknownSpecialization) {
  3648. // When the scope specifier can refer to a member of an unknown
  3649. // specialization, we take it as a type name.
  3650. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3651. SS.getWithLocInContext(Context),
  3652. *MemberOrBase, IdLoc);
  3653. if (BaseType.isNull())
  3654. return true;
  3655. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3656. DependentNameTypeLoc TL =
  3657. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3658. if (!TL.isNull()) {
  3659. TL.setNameLoc(IdLoc);
  3660. TL.setElaboratedKeywordLoc(SourceLocation());
  3661. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3662. }
  3663. R.clear();
  3664. R.setLookupName(MemberOrBase);
  3665. }
  3666. }
  3667. // If no results were found, try to correct typos.
  3668. TypoCorrection Corr;
  3669. MemInitializerValidatorCCC CCC(ClassDecl);
  3670. if (R.empty() && BaseType.isNull() &&
  3671. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3672. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3673. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3674. // We have found a non-static data member with a similar
  3675. // name to what was typed; complain and initialize that
  3676. // member.
  3677. diagnoseTypo(Corr,
  3678. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3679. << MemberOrBase << true);
  3680. return BuildMemberInitializer(Member, Init, IdLoc);
  3681. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3682. const CXXBaseSpecifier *DirectBaseSpec;
  3683. const CXXBaseSpecifier *VirtualBaseSpec;
  3684. if (FindBaseInitializer(*this, ClassDecl,
  3685. Context.getTypeDeclType(Type),
  3686. DirectBaseSpec, VirtualBaseSpec)) {
  3687. // We have found a direct or virtual base class with a
  3688. // similar name to what was typed; complain and initialize
  3689. // that base class.
  3690. diagnoseTypo(Corr,
  3691. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3692. << MemberOrBase << false,
  3693. PDiag() /*Suppress note, we provide our own.*/);
  3694. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3695. : VirtualBaseSpec;
  3696. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3697. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3698. TyD = Type;
  3699. }
  3700. }
  3701. }
  3702. if (!TyD && BaseType.isNull()) {
  3703. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3704. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3705. return true;
  3706. }
  3707. }
  3708. if (BaseType.isNull()) {
  3709. BaseType = Context.getTypeDeclType(TyD);
  3710. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3711. if (SS.isSet()) {
  3712. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3713. BaseType);
  3714. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3715. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3716. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3717. TL.setElaboratedKeywordLoc(SourceLocation());
  3718. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3719. }
  3720. }
  3721. }
  3722. if (!TInfo)
  3723. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3724. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3725. }
  3726. MemInitResult
  3727. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3728. SourceLocation IdLoc) {
  3729. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3730. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3731. assert((DirectMember || IndirectMember) &&
  3732. "Member must be a FieldDecl or IndirectFieldDecl");
  3733. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3734. return true;
  3735. if (Member->isInvalidDecl())
  3736. return true;
  3737. MultiExprArg Args;
  3738. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3739. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3740. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3741. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3742. } else {
  3743. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3744. Args = Init;
  3745. }
  3746. SourceRange InitRange = Init->getSourceRange();
  3747. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3748. // Can't check initialization for a member of dependent type or when
  3749. // any of the arguments are type-dependent expressions.
  3750. DiscardCleanupsInEvaluationContext();
  3751. } else {
  3752. bool InitList = false;
  3753. if (isa<InitListExpr>(Init)) {
  3754. InitList = true;
  3755. Args = Init;
  3756. }
  3757. // Initialize the member.
  3758. InitializedEntity MemberEntity =
  3759. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3760. : InitializedEntity::InitializeMember(IndirectMember,
  3761. nullptr);
  3762. InitializationKind Kind =
  3763. InitList ? InitializationKind::CreateDirectList(
  3764. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3765. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3766. InitRange.getEnd());
  3767. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3768. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3769. nullptr);
  3770. if (MemberInit.isInvalid())
  3771. return true;
  3772. // C++11 [class.base.init]p7:
  3773. // The initialization of each base and member constitutes a
  3774. // full-expression.
  3775. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3776. /*DiscardedValue*/ false);
  3777. if (MemberInit.isInvalid())
  3778. return true;
  3779. Init = MemberInit.get();
  3780. }
  3781. if (DirectMember) {
  3782. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3783. InitRange.getBegin(), Init,
  3784. InitRange.getEnd());
  3785. } else {
  3786. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3787. InitRange.getBegin(), Init,
  3788. InitRange.getEnd());
  3789. }
  3790. }
  3791. MemInitResult
  3792. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3793. CXXRecordDecl *ClassDecl) {
  3794. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3795. if (!LangOpts.CPlusPlus11)
  3796. return Diag(NameLoc, diag::err_delegating_ctor)
  3797. << TInfo->getTypeLoc().getLocalSourceRange();
  3798. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3799. bool InitList = true;
  3800. MultiExprArg Args = Init;
  3801. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3802. InitList = false;
  3803. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3804. }
  3805. SourceRange InitRange = Init->getSourceRange();
  3806. // Initialize the object.
  3807. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3808. QualType(ClassDecl->getTypeForDecl(), 0));
  3809. InitializationKind Kind =
  3810. InitList ? InitializationKind::CreateDirectList(
  3811. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3812. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3813. InitRange.getEnd());
  3814. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3815. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3816. Args, nullptr);
  3817. if (DelegationInit.isInvalid())
  3818. return true;
  3819. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3820. "Delegating constructor with no target?");
  3821. // C++11 [class.base.init]p7:
  3822. // The initialization of each base and member constitutes a
  3823. // full-expression.
  3824. DelegationInit = ActOnFinishFullExpr(
  3825. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  3826. if (DelegationInit.isInvalid())
  3827. return true;
  3828. // If we are in a dependent context, template instantiation will
  3829. // perform this type-checking again. Just save the arguments that we
  3830. // received in a ParenListExpr.
  3831. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3832. // of the information that we have about the base
  3833. // initializer. However, deconstructing the ASTs is a dicey process,
  3834. // and this approach is far more likely to get the corner cases right.
  3835. if (CurContext->isDependentContext())
  3836. DelegationInit = Init;
  3837. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3838. DelegationInit.getAs<Expr>(),
  3839. InitRange.getEnd());
  3840. }
  3841. MemInitResult
  3842. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3843. Expr *Init, CXXRecordDecl *ClassDecl,
  3844. SourceLocation EllipsisLoc) {
  3845. SourceLocation BaseLoc
  3846. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3847. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3848. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3849. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3850. // C++ [class.base.init]p2:
  3851. // [...] Unless the mem-initializer-id names a nonstatic data
  3852. // member of the constructor's class or a direct or virtual base
  3853. // of that class, the mem-initializer is ill-formed. A
  3854. // mem-initializer-list can initialize a base class using any
  3855. // name that denotes that base class type.
  3856. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3857. SourceRange InitRange = Init->getSourceRange();
  3858. if (EllipsisLoc.isValid()) {
  3859. // This is a pack expansion.
  3860. if (!BaseType->containsUnexpandedParameterPack()) {
  3861. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3862. << SourceRange(BaseLoc, InitRange.getEnd());
  3863. EllipsisLoc = SourceLocation();
  3864. }
  3865. } else {
  3866. // Check for any unexpanded parameter packs.
  3867. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3868. return true;
  3869. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3870. return true;
  3871. }
  3872. // Check for direct and virtual base classes.
  3873. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3874. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3875. if (!Dependent) {
  3876. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3877. BaseType))
  3878. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3879. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3880. VirtualBaseSpec);
  3881. // C++ [base.class.init]p2:
  3882. // Unless the mem-initializer-id names a nonstatic data member of the
  3883. // constructor's class or a direct or virtual base of that class, the
  3884. // mem-initializer is ill-formed.
  3885. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3886. // If the class has any dependent bases, then it's possible that
  3887. // one of those types will resolve to the same type as
  3888. // BaseType. Therefore, just treat this as a dependent base
  3889. // class initialization. FIXME: Should we try to check the
  3890. // initialization anyway? It seems odd.
  3891. if (ClassDecl->hasAnyDependentBases())
  3892. Dependent = true;
  3893. else
  3894. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3895. << BaseType << Context.getTypeDeclType(ClassDecl)
  3896. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3897. }
  3898. }
  3899. if (Dependent) {
  3900. DiscardCleanupsInEvaluationContext();
  3901. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3902. /*IsVirtual=*/false,
  3903. InitRange.getBegin(), Init,
  3904. InitRange.getEnd(), EllipsisLoc);
  3905. }
  3906. // C++ [base.class.init]p2:
  3907. // If a mem-initializer-id is ambiguous because it designates both
  3908. // a direct non-virtual base class and an inherited virtual base
  3909. // class, the mem-initializer is ill-formed.
  3910. if (DirectBaseSpec && VirtualBaseSpec)
  3911. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3912. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3913. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3914. if (!BaseSpec)
  3915. BaseSpec = VirtualBaseSpec;
  3916. // Initialize the base.
  3917. bool InitList = true;
  3918. MultiExprArg Args = Init;
  3919. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3920. InitList = false;
  3921. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3922. }
  3923. InitializedEntity BaseEntity =
  3924. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3925. InitializationKind Kind =
  3926. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3927. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3928. InitRange.getEnd());
  3929. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3930. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3931. if (BaseInit.isInvalid())
  3932. return true;
  3933. // C++11 [class.base.init]p7:
  3934. // The initialization of each base and member constitutes a
  3935. // full-expression.
  3936. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  3937. /*DiscardedValue*/ false);
  3938. if (BaseInit.isInvalid())
  3939. return true;
  3940. // If we are in a dependent context, template instantiation will
  3941. // perform this type-checking again. Just save the arguments that we
  3942. // received in a ParenListExpr.
  3943. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3944. // of the information that we have about the base
  3945. // initializer. However, deconstructing the ASTs is a dicey process,
  3946. // and this approach is far more likely to get the corner cases right.
  3947. if (CurContext->isDependentContext())
  3948. BaseInit = Init;
  3949. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3950. BaseSpec->isVirtual(),
  3951. InitRange.getBegin(),
  3952. BaseInit.getAs<Expr>(),
  3953. InitRange.getEnd(), EllipsisLoc);
  3954. }
  3955. // Create a static_cast\<T&&>(expr).
  3956. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3957. if (T.isNull()) T = E->getType();
  3958. QualType TargetType = SemaRef.BuildReferenceType(
  3959. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3960. SourceLocation ExprLoc = E->getBeginLoc();
  3961. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3962. TargetType, ExprLoc);
  3963. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3964. SourceRange(ExprLoc, ExprLoc),
  3965. E->getSourceRange()).get();
  3966. }
  3967. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3968. /// initialize its base or member.
  3969. enum ImplicitInitializerKind {
  3970. IIK_Default,
  3971. IIK_Copy,
  3972. IIK_Move,
  3973. IIK_Inherit
  3974. };
  3975. static bool
  3976. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3977. ImplicitInitializerKind ImplicitInitKind,
  3978. CXXBaseSpecifier *BaseSpec,
  3979. bool IsInheritedVirtualBase,
  3980. CXXCtorInitializer *&CXXBaseInit) {
  3981. InitializedEntity InitEntity
  3982. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3983. IsInheritedVirtualBase);
  3984. ExprResult BaseInit;
  3985. switch (ImplicitInitKind) {
  3986. case IIK_Inherit:
  3987. case IIK_Default: {
  3988. InitializationKind InitKind
  3989. = InitializationKind::CreateDefault(Constructor->getLocation());
  3990. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3991. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3992. break;
  3993. }
  3994. case IIK_Move:
  3995. case IIK_Copy: {
  3996. bool Moving = ImplicitInitKind == IIK_Move;
  3997. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3998. QualType ParamType = Param->getType().getNonReferenceType();
  3999. Expr *CopyCtorArg =
  4000. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4001. SourceLocation(), Param, false,
  4002. Constructor->getLocation(), ParamType,
  4003. VK_LValue, nullptr);
  4004. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  4005. // Cast to the base class to avoid ambiguities.
  4006. QualType ArgTy =
  4007. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  4008. ParamType.getQualifiers());
  4009. if (Moving) {
  4010. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  4011. }
  4012. CXXCastPath BasePath;
  4013. BasePath.push_back(BaseSpec);
  4014. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  4015. CK_UncheckedDerivedToBase,
  4016. Moving ? VK_XValue : VK_LValue,
  4017. &BasePath).get();
  4018. InitializationKind InitKind
  4019. = InitializationKind::CreateDirect(Constructor->getLocation(),
  4020. SourceLocation(), SourceLocation());
  4021. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4022. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4023. break;
  4024. }
  4025. }
  4026. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  4027. if (BaseInit.isInvalid())
  4028. return true;
  4029. CXXBaseInit =
  4030. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4031. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  4032. SourceLocation()),
  4033. BaseSpec->isVirtual(),
  4034. SourceLocation(),
  4035. BaseInit.getAs<Expr>(),
  4036. SourceLocation(),
  4037. SourceLocation());
  4038. return false;
  4039. }
  4040. static bool RefersToRValueRef(Expr *MemRef) {
  4041. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  4042. return Referenced->getType()->isRValueReferenceType();
  4043. }
  4044. static bool
  4045. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4046. ImplicitInitializerKind ImplicitInitKind,
  4047. FieldDecl *Field, IndirectFieldDecl *Indirect,
  4048. CXXCtorInitializer *&CXXMemberInit) {
  4049. if (Field->isInvalidDecl())
  4050. return true;
  4051. SourceLocation Loc = Constructor->getLocation();
  4052. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  4053. bool Moving = ImplicitInitKind == IIK_Move;
  4054. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4055. QualType ParamType = Param->getType().getNonReferenceType();
  4056. // Suppress copying zero-width bitfields.
  4057. if (Field->isZeroLengthBitField(SemaRef.Context))
  4058. return false;
  4059. Expr *MemberExprBase =
  4060. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4061. SourceLocation(), Param, false,
  4062. Loc, ParamType, VK_LValue, nullptr);
  4063. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  4064. if (Moving) {
  4065. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  4066. }
  4067. // Build a reference to this field within the parameter.
  4068. CXXScopeSpec SS;
  4069. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  4070. Sema::LookupMemberName);
  4071. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  4072. : cast<ValueDecl>(Field), AS_public);
  4073. MemberLookup.resolveKind();
  4074. ExprResult CtorArg
  4075. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  4076. ParamType, Loc,
  4077. /*IsArrow=*/false,
  4078. SS,
  4079. /*TemplateKWLoc=*/SourceLocation(),
  4080. /*FirstQualifierInScope=*/nullptr,
  4081. MemberLookup,
  4082. /*TemplateArgs=*/nullptr,
  4083. /*S*/nullptr);
  4084. if (CtorArg.isInvalid())
  4085. return true;
  4086. // C++11 [class.copy]p15:
  4087. // - if a member m has rvalue reference type T&&, it is direct-initialized
  4088. // with static_cast<T&&>(x.m);
  4089. if (RefersToRValueRef(CtorArg.get())) {
  4090. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  4091. }
  4092. InitializedEntity Entity =
  4093. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4094. /*Implicit*/ true)
  4095. : InitializedEntity::InitializeMember(Field, nullptr,
  4096. /*Implicit*/ true);
  4097. // Direct-initialize to use the copy constructor.
  4098. InitializationKind InitKind =
  4099. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  4100. Expr *CtorArgE = CtorArg.getAs<Expr>();
  4101. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  4102. ExprResult MemberInit =
  4103. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  4104. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4105. if (MemberInit.isInvalid())
  4106. return true;
  4107. if (Indirect)
  4108. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4109. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4110. else
  4111. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4112. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4113. return false;
  4114. }
  4115. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  4116. "Unhandled implicit init kind!");
  4117. QualType FieldBaseElementType =
  4118. SemaRef.Context.getBaseElementType(Field->getType());
  4119. if (FieldBaseElementType->isRecordType()) {
  4120. InitializedEntity InitEntity =
  4121. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4122. /*Implicit*/ true)
  4123. : InitializedEntity::InitializeMember(Field, nullptr,
  4124. /*Implicit*/ true);
  4125. InitializationKind InitKind =
  4126. InitializationKind::CreateDefault(Loc);
  4127. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  4128. ExprResult MemberInit =
  4129. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  4130. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4131. if (MemberInit.isInvalid())
  4132. return true;
  4133. if (Indirect)
  4134. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4135. Indirect, Loc,
  4136. Loc,
  4137. MemberInit.get(),
  4138. Loc);
  4139. else
  4140. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4141. Field, Loc, Loc,
  4142. MemberInit.get(),
  4143. Loc);
  4144. return false;
  4145. }
  4146. if (!Field->getParent()->isUnion()) {
  4147. if (FieldBaseElementType->isReferenceType()) {
  4148. SemaRef.Diag(Constructor->getLocation(),
  4149. diag::err_uninitialized_member_in_ctor)
  4150. << (int)Constructor->isImplicit()
  4151. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4152. << 0 << Field->getDeclName();
  4153. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4154. return true;
  4155. }
  4156. if (FieldBaseElementType.isConstQualified()) {
  4157. SemaRef.Diag(Constructor->getLocation(),
  4158. diag::err_uninitialized_member_in_ctor)
  4159. << (int)Constructor->isImplicit()
  4160. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4161. << 1 << Field->getDeclName();
  4162. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4163. return true;
  4164. }
  4165. }
  4166. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  4167. // ARC and Weak:
  4168. // Default-initialize Objective-C pointers to NULL.
  4169. CXXMemberInit
  4170. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  4171. Loc, Loc,
  4172. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  4173. Loc);
  4174. return false;
  4175. }
  4176. // Nothing to initialize.
  4177. CXXMemberInit = nullptr;
  4178. return false;
  4179. }
  4180. namespace {
  4181. struct BaseAndFieldInfo {
  4182. Sema &S;
  4183. CXXConstructorDecl *Ctor;
  4184. bool AnyErrorsInInits;
  4185. ImplicitInitializerKind IIK;
  4186. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4187. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4188. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4189. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4190. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4191. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4192. if (Ctor->getInheritedConstructor())
  4193. IIK = IIK_Inherit;
  4194. else if (Generated && Ctor->isCopyConstructor())
  4195. IIK = IIK_Copy;
  4196. else if (Generated && Ctor->isMoveConstructor())
  4197. IIK = IIK_Move;
  4198. else
  4199. IIK = IIK_Default;
  4200. }
  4201. bool isImplicitCopyOrMove() const {
  4202. switch (IIK) {
  4203. case IIK_Copy:
  4204. case IIK_Move:
  4205. return true;
  4206. case IIK_Default:
  4207. case IIK_Inherit:
  4208. return false;
  4209. }
  4210. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4211. }
  4212. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4213. AllToInit.push_back(Init);
  4214. // Check whether this initializer makes the field "used".
  4215. if (Init->getInit()->HasSideEffects(S.Context))
  4216. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4217. return false;
  4218. }
  4219. bool isInactiveUnionMember(FieldDecl *Field) {
  4220. RecordDecl *Record = Field->getParent();
  4221. if (!Record->isUnion())
  4222. return false;
  4223. if (FieldDecl *Active =
  4224. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4225. return Active != Field->getCanonicalDecl();
  4226. // In an implicit copy or move constructor, ignore any in-class initializer.
  4227. if (isImplicitCopyOrMove())
  4228. return true;
  4229. // If there's no explicit initialization, the field is active only if it
  4230. // has an in-class initializer...
  4231. if (Field->hasInClassInitializer())
  4232. return false;
  4233. // ... or it's an anonymous struct or union whose class has an in-class
  4234. // initializer.
  4235. if (!Field->isAnonymousStructOrUnion())
  4236. return true;
  4237. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4238. return !FieldRD->hasInClassInitializer();
  4239. }
  4240. /// Determine whether the given field is, or is within, a union member
  4241. /// that is inactive (because there was an initializer given for a different
  4242. /// member of the union, or because the union was not initialized at all).
  4243. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4244. IndirectFieldDecl *Indirect) {
  4245. if (!Indirect)
  4246. return isInactiveUnionMember(Field);
  4247. for (auto *C : Indirect->chain()) {
  4248. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4249. if (Field && isInactiveUnionMember(Field))
  4250. return true;
  4251. }
  4252. return false;
  4253. }
  4254. };
  4255. }
  4256. /// Determine whether the given type is an incomplete or zero-lenfgth
  4257. /// array type.
  4258. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4259. if (T->isIncompleteArrayType())
  4260. return true;
  4261. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4262. if (!ArrayT->getSize())
  4263. return true;
  4264. T = ArrayT->getElementType();
  4265. }
  4266. return false;
  4267. }
  4268. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4269. FieldDecl *Field,
  4270. IndirectFieldDecl *Indirect = nullptr) {
  4271. if (Field->isInvalidDecl())
  4272. return false;
  4273. // Overwhelmingly common case: we have a direct initializer for this field.
  4274. if (CXXCtorInitializer *Init =
  4275. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4276. return Info.addFieldInitializer(Init);
  4277. // C++11 [class.base.init]p8:
  4278. // if the entity is a non-static data member that has a
  4279. // brace-or-equal-initializer and either
  4280. // -- the constructor's class is a union and no other variant member of that
  4281. // union is designated by a mem-initializer-id or
  4282. // -- the constructor's class is not a union, and, if the entity is a member
  4283. // of an anonymous union, no other member of that union is designated by
  4284. // a mem-initializer-id,
  4285. // the entity is initialized as specified in [dcl.init].
  4286. //
  4287. // We also apply the same rules to handle anonymous structs within anonymous
  4288. // unions.
  4289. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4290. return false;
  4291. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4292. ExprResult DIE =
  4293. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4294. if (DIE.isInvalid())
  4295. return true;
  4296. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4297. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4298. CXXCtorInitializer *Init;
  4299. if (Indirect)
  4300. Init = new (SemaRef.Context)
  4301. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4302. SourceLocation(), DIE.get(), SourceLocation());
  4303. else
  4304. Init = new (SemaRef.Context)
  4305. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4306. SourceLocation(), DIE.get(), SourceLocation());
  4307. return Info.addFieldInitializer(Init);
  4308. }
  4309. // Don't initialize incomplete or zero-length arrays.
  4310. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4311. return false;
  4312. // Don't try to build an implicit initializer if there were semantic
  4313. // errors in any of the initializers (and therefore we might be
  4314. // missing some that the user actually wrote).
  4315. if (Info.AnyErrorsInInits)
  4316. return false;
  4317. CXXCtorInitializer *Init = nullptr;
  4318. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4319. Indirect, Init))
  4320. return true;
  4321. if (!Init)
  4322. return false;
  4323. return Info.addFieldInitializer(Init);
  4324. }
  4325. bool
  4326. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4327. CXXCtorInitializer *Initializer) {
  4328. assert(Initializer->isDelegatingInitializer());
  4329. Constructor->setNumCtorInitializers(1);
  4330. CXXCtorInitializer **initializer =
  4331. new (Context) CXXCtorInitializer*[1];
  4332. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4333. Constructor->setCtorInitializers(initializer);
  4334. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4335. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4336. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4337. }
  4338. DelegatingCtorDecls.push_back(Constructor);
  4339. DiagnoseUninitializedFields(*this, Constructor);
  4340. return false;
  4341. }
  4342. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4343. ArrayRef<CXXCtorInitializer *> Initializers) {
  4344. if (Constructor->isDependentContext()) {
  4345. // Just store the initializers as written, they will be checked during
  4346. // instantiation.
  4347. if (!Initializers.empty()) {
  4348. Constructor->setNumCtorInitializers(Initializers.size());
  4349. CXXCtorInitializer **baseOrMemberInitializers =
  4350. new (Context) CXXCtorInitializer*[Initializers.size()];
  4351. memcpy(baseOrMemberInitializers, Initializers.data(),
  4352. Initializers.size() * sizeof(CXXCtorInitializer*));
  4353. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4354. }
  4355. // Let template instantiation know whether we had errors.
  4356. if (AnyErrors)
  4357. Constructor->setInvalidDecl();
  4358. return false;
  4359. }
  4360. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4361. // We need to build the initializer AST according to order of construction
  4362. // and not what user specified in the Initializers list.
  4363. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4364. if (!ClassDecl)
  4365. return true;
  4366. bool HadError = false;
  4367. for (unsigned i = 0; i < Initializers.size(); i++) {
  4368. CXXCtorInitializer *Member = Initializers[i];
  4369. if (Member->isBaseInitializer())
  4370. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4371. else {
  4372. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4373. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4374. for (auto *C : F->chain()) {
  4375. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4376. if (FD && FD->getParent()->isUnion())
  4377. Info.ActiveUnionMember.insert(std::make_pair(
  4378. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4379. }
  4380. } else if (FieldDecl *FD = Member->getMember()) {
  4381. if (FD->getParent()->isUnion())
  4382. Info.ActiveUnionMember.insert(std::make_pair(
  4383. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4384. }
  4385. }
  4386. }
  4387. // Keep track of the direct virtual bases.
  4388. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4389. for (auto &I : ClassDecl->bases()) {
  4390. if (I.isVirtual())
  4391. DirectVBases.insert(&I);
  4392. }
  4393. // Push virtual bases before others.
  4394. for (auto &VBase : ClassDecl->vbases()) {
  4395. if (CXXCtorInitializer *Value
  4396. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4397. // [class.base.init]p7, per DR257:
  4398. // A mem-initializer where the mem-initializer-id names a virtual base
  4399. // class is ignored during execution of a constructor of any class that
  4400. // is not the most derived class.
  4401. if (ClassDecl->isAbstract()) {
  4402. // FIXME: Provide a fixit to remove the base specifier. This requires
  4403. // tracking the location of the associated comma for a base specifier.
  4404. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4405. << VBase.getType() << ClassDecl;
  4406. DiagnoseAbstractType(ClassDecl);
  4407. }
  4408. Info.AllToInit.push_back(Value);
  4409. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4410. // [class.base.init]p8, per DR257:
  4411. // If a given [...] base class is not named by a mem-initializer-id
  4412. // [...] and the entity is not a virtual base class of an abstract
  4413. // class, then [...] the entity is default-initialized.
  4414. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4415. CXXCtorInitializer *CXXBaseInit;
  4416. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4417. &VBase, IsInheritedVirtualBase,
  4418. CXXBaseInit)) {
  4419. HadError = true;
  4420. continue;
  4421. }
  4422. Info.AllToInit.push_back(CXXBaseInit);
  4423. }
  4424. }
  4425. // Non-virtual bases.
  4426. for (auto &Base : ClassDecl->bases()) {
  4427. // Virtuals are in the virtual base list and already constructed.
  4428. if (Base.isVirtual())
  4429. continue;
  4430. if (CXXCtorInitializer *Value
  4431. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4432. Info.AllToInit.push_back(Value);
  4433. } else if (!AnyErrors) {
  4434. CXXCtorInitializer *CXXBaseInit;
  4435. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4436. &Base, /*IsInheritedVirtualBase=*/false,
  4437. CXXBaseInit)) {
  4438. HadError = true;
  4439. continue;
  4440. }
  4441. Info.AllToInit.push_back(CXXBaseInit);
  4442. }
  4443. }
  4444. // Fields.
  4445. for (auto *Mem : ClassDecl->decls()) {
  4446. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4447. // C++ [class.bit]p2:
  4448. // A declaration for a bit-field that omits the identifier declares an
  4449. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4450. // initialized.
  4451. if (F->isUnnamedBitfield())
  4452. continue;
  4453. // If we're not generating the implicit copy/move constructor, then we'll
  4454. // handle anonymous struct/union fields based on their individual
  4455. // indirect fields.
  4456. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4457. continue;
  4458. if (CollectFieldInitializer(*this, Info, F))
  4459. HadError = true;
  4460. continue;
  4461. }
  4462. // Beyond this point, we only consider default initialization.
  4463. if (Info.isImplicitCopyOrMove())
  4464. continue;
  4465. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4466. if (F->getType()->isIncompleteArrayType()) {
  4467. assert(ClassDecl->hasFlexibleArrayMember() &&
  4468. "Incomplete array type is not valid");
  4469. continue;
  4470. }
  4471. // Initialize each field of an anonymous struct individually.
  4472. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4473. HadError = true;
  4474. continue;
  4475. }
  4476. }
  4477. unsigned NumInitializers = Info.AllToInit.size();
  4478. if (NumInitializers > 0) {
  4479. Constructor->setNumCtorInitializers(NumInitializers);
  4480. CXXCtorInitializer **baseOrMemberInitializers =
  4481. new (Context) CXXCtorInitializer*[NumInitializers];
  4482. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4483. NumInitializers * sizeof(CXXCtorInitializer*));
  4484. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4485. // Constructors implicitly reference the base and member
  4486. // destructors.
  4487. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4488. Constructor->getParent());
  4489. }
  4490. return HadError;
  4491. }
  4492. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4493. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4494. const RecordDecl *RD = RT->getDecl();
  4495. if (RD->isAnonymousStructOrUnion()) {
  4496. for (auto *Field : RD->fields())
  4497. PopulateKeysForFields(Field, IdealInits);
  4498. return;
  4499. }
  4500. }
  4501. IdealInits.push_back(Field->getCanonicalDecl());
  4502. }
  4503. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4504. return Context.getCanonicalType(BaseType).getTypePtr();
  4505. }
  4506. static const void *GetKeyForMember(ASTContext &Context,
  4507. CXXCtorInitializer *Member) {
  4508. if (!Member->isAnyMemberInitializer())
  4509. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4510. return Member->getAnyMember()->getCanonicalDecl();
  4511. }
  4512. static void DiagnoseBaseOrMemInitializerOrder(
  4513. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4514. ArrayRef<CXXCtorInitializer *> Inits) {
  4515. if (Constructor->getDeclContext()->isDependentContext())
  4516. return;
  4517. // Don't check initializers order unless the warning is enabled at the
  4518. // location of at least one initializer.
  4519. bool ShouldCheckOrder = false;
  4520. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4521. CXXCtorInitializer *Init = Inits[InitIndex];
  4522. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4523. Init->getSourceLocation())) {
  4524. ShouldCheckOrder = true;
  4525. break;
  4526. }
  4527. }
  4528. if (!ShouldCheckOrder)
  4529. return;
  4530. // Build the list of bases and members in the order that they'll
  4531. // actually be initialized. The explicit initializers should be in
  4532. // this same order but may be missing things.
  4533. SmallVector<const void*, 32> IdealInitKeys;
  4534. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4535. // 1. Virtual bases.
  4536. for (const auto &VBase : ClassDecl->vbases())
  4537. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4538. // 2. Non-virtual bases.
  4539. for (const auto &Base : ClassDecl->bases()) {
  4540. if (Base.isVirtual())
  4541. continue;
  4542. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4543. }
  4544. // 3. Direct fields.
  4545. for (auto *Field : ClassDecl->fields()) {
  4546. if (Field->isUnnamedBitfield())
  4547. continue;
  4548. PopulateKeysForFields(Field, IdealInitKeys);
  4549. }
  4550. unsigned NumIdealInits = IdealInitKeys.size();
  4551. unsigned IdealIndex = 0;
  4552. CXXCtorInitializer *PrevInit = nullptr;
  4553. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4554. CXXCtorInitializer *Init = Inits[InitIndex];
  4555. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4556. // Scan forward to try to find this initializer in the idealized
  4557. // initializers list.
  4558. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4559. if (InitKey == IdealInitKeys[IdealIndex])
  4560. break;
  4561. // If we didn't find this initializer, it must be because we
  4562. // scanned past it on a previous iteration. That can only
  4563. // happen if we're out of order; emit a warning.
  4564. if (IdealIndex == NumIdealInits && PrevInit) {
  4565. Sema::SemaDiagnosticBuilder D =
  4566. SemaRef.Diag(PrevInit->getSourceLocation(),
  4567. diag::warn_initializer_out_of_order);
  4568. if (PrevInit->isAnyMemberInitializer())
  4569. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4570. else
  4571. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4572. if (Init->isAnyMemberInitializer())
  4573. D << 0 << Init->getAnyMember()->getDeclName();
  4574. else
  4575. D << 1 << Init->getTypeSourceInfo()->getType();
  4576. // Move back to the initializer's location in the ideal list.
  4577. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4578. if (InitKey == IdealInitKeys[IdealIndex])
  4579. break;
  4580. assert(IdealIndex < NumIdealInits &&
  4581. "initializer not found in initializer list");
  4582. }
  4583. PrevInit = Init;
  4584. }
  4585. }
  4586. namespace {
  4587. bool CheckRedundantInit(Sema &S,
  4588. CXXCtorInitializer *Init,
  4589. CXXCtorInitializer *&PrevInit) {
  4590. if (!PrevInit) {
  4591. PrevInit = Init;
  4592. return false;
  4593. }
  4594. if (FieldDecl *Field = Init->getAnyMember())
  4595. S.Diag(Init->getSourceLocation(),
  4596. diag::err_multiple_mem_initialization)
  4597. << Field->getDeclName()
  4598. << Init->getSourceRange();
  4599. else {
  4600. const Type *BaseClass = Init->getBaseClass();
  4601. assert(BaseClass && "neither field nor base");
  4602. S.Diag(Init->getSourceLocation(),
  4603. diag::err_multiple_base_initialization)
  4604. << QualType(BaseClass, 0)
  4605. << Init->getSourceRange();
  4606. }
  4607. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4608. << 0 << PrevInit->getSourceRange();
  4609. return true;
  4610. }
  4611. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4612. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4613. bool CheckRedundantUnionInit(Sema &S,
  4614. CXXCtorInitializer *Init,
  4615. RedundantUnionMap &Unions) {
  4616. FieldDecl *Field = Init->getAnyMember();
  4617. RecordDecl *Parent = Field->getParent();
  4618. NamedDecl *Child = Field;
  4619. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4620. if (Parent->isUnion()) {
  4621. UnionEntry &En = Unions[Parent];
  4622. if (En.first && En.first != Child) {
  4623. S.Diag(Init->getSourceLocation(),
  4624. diag::err_multiple_mem_union_initialization)
  4625. << Field->getDeclName()
  4626. << Init->getSourceRange();
  4627. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4628. << 0 << En.second->getSourceRange();
  4629. return true;
  4630. }
  4631. if (!En.first) {
  4632. En.first = Child;
  4633. En.second = Init;
  4634. }
  4635. if (!Parent->isAnonymousStructOrUnion())
  4636. return false;
  4637. }
  4638. Child = Parent;
  4639. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4640. }
  4641. return false;
  4642. }
  4643. }
  4644. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4645. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4646. SourceLocation ColonLoc,
  4647. ArrayRef<CXXCtorInitializer*> MemInits,
  4648. bool AnyErrors) {
  4649. if (!ConstructorDecl)
  4650. return;
  4651. AdjustDeclIfTemplate(ConstructorDecl);
  4652. CXXConstructorDecl *Constructor
  4653. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4654. if (!Constructor) {
  4655. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4656. return;
  4657. }
  4658. // Mapping for the duplicate initializers check.
  4659. // For member initializers, this is keyed with a FieldDecl*.
  4660. // For base initializers, this is keyed with a Type*.
  4661. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4662. // Mapping for the inconsistent anonymous-union initializers check.
  4663. RedundantUnionMap MemberUnions;
  4664. bool HadError = false;
  4665. for (unsigned i = 0; i < MemInits.size(); i++) {
  4666. CXXCtorInitializer *Init = MemInits[i];
  4667. // Set the source order index.
  4668. Init->setSourceOrder(i);
  4669. if (Init->isAnyMemberInitializer()) {
  4670. const void *Key = GetKeyForMember(Context, Init);
  4671. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4672. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4673. HadError = true;
  4674. } else if (Init->isBaseInitializer()) {
  4675. const void *Key = GetKeyForMember(Context, Init);
  4676. if (CheckRedundantInit(*this, Init, Members[Key]))
  4677. HadError = true;
  4678. } else {
  4679. assert(Init->isDelegatingInitializer());
  4680. // This must be the only initializer
  4681. if (MemInits.size() != 1) {
  4682. Diag(Init->getSourceLocation(),
  4683. diag::err_delegating_initializer_alone)
  4684. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4685. // We will treat this as being the only initializer.
  4686. }
  4687. SetDelegatingInitializer(Constructor, MemInits[i]);
  4688. // Return immediately as the initializer is set.
  4689. return;
  4690. }
  4691. }
  4692. if (HadError)
  4693. return;
  4694. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4695. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4696. DiagnoseUninitializedFields(*this, Constructor);
  4697. }
  4698. void
  4699. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4700. CXXRecordDecl *ClassDecl) {
  4701. // Ignore dependent contexts. Also ignore unions, since their members never
  4702. // have destructors implicitly called.
  4703. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4704. return;
  4705. // FIXME: all the access-control diagnostics are positioned on the
  4706. // field/base declaration. That's probably good; that said, the
  4707. // user might reasonably want to know why the destructor is being
  4708. // emitted, and we currently don't say.
  4709. // Non-static data members.
  4710. for (auto *Field : ClassDecl->fields()) {
  4711. if (Field->isInvalidDecl())
  4712. continue;
  4713. // Don't destroy incomplete or zero-length arrays.
  4714. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4715. continue;
  4716. QualType FieldType = Context.getBaseElementType(Field->getType());
  4717. const RecordType* RT = FieldType->getAs<RecordType>();
  4718. if (!RT)
  4719. continue;
  4720. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4721. if (FieldClassDecl->isInvalidDecl())
  4722. continue;
  4723. if (FieldClassDecl->hasIrrelevantDestructor())
  4724. continue;
  4725. // The destructor for an implicit anonymous union member is never invoked.
  4726. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4727. continue;
  4728. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4729. assert(Dtor && "No dtor found for FieldClassDecl!");
  4730. CheckDestructorAccess(Field->getLocation(), Dtor,
  4731. PDiag(diag::err_access_dtor_field)
  4732. << Field->getDeclName()
  4733. << FieldType);
  4734. MarkFunctionReferenced(Location, Dtor);
  4735. DiagnoseUseOfDecl(Dtor, Location);
  4736. }
  4737. // We only potentially invoke the destructors of potentially constructed
  4738. // subobjects.
  4739. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4740. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4741. // Bases.
  4742. for (const auto &Base : ClassDecl->bases()) {
  4743. // Bases are always records in a well-formed non-dependent class.
  4744. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4745. // Remember direct virtual bases.
  4746. if (Base.isVirtual()) {
  4747. if (!VisitVirtualBases)
  4748. continue;
  4749. DirectVirtualBases.insert(RT);
  4750. }
  4751. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4752. // If our base class is invalid, we probably can't get its dtor anyway.
  4753. if (BaseClassDecl->isInvalidDecl())
  4754. continue;
  4755. if (BaseClassDecl->hasIrrelevantDestructor())
  4756. continue;
  4757. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4758. assert(Dtor && "No dtor found for BaseClassDecl!");
  4759. // FIXME: caret should be on the start of the class name
  4760. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4761. PDiag(diag::err_access_dtor_base)
  4762. << Base.getType() << Base.getSourceRange(),
  4763. Context.getTypeDeclType(ClassDecl));
  4764. MarkFunctionReferenced(Location, Dtor);
  4765. DiagnoseUseOfDecl(Dtor, Location);
  4766. }
  4767. if (!VisitVirtualBases)
  4768. return;
  4769. // Virtual bases.
  4770. for (const auto &VBase : ClassDecl->vbases()) {
  4771. // Bases are always records in a well-formed non-dependent class.
  4772. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4773. // Ignore direct virtual bases.
  4774. if (DirectVirtualBases.count(RT))
  4775. continue;
  4776. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4777. // If our base class is invalid, we probably can't get its dtor anyway.
  4778. if (BaseClassDecl->isInvalidDecl())
  4779. continue;
  4780. if (BaseClassDecl->hasIrrelevantDestructor())
  4781. continue;
  4782. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4783. assert(Dtor && "No dtor found for BaseClassDecl!");
  4784. if (CheckDestructorAccess(
  4785. ClassDecl->getLocation(), Dtor,
  4786. PDiag(diag::err_access_dtor_vbase)
  4787. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4788. Context.getTypeDeclType(ClassDecl)) ==
  4789. AR_accessible) {
  4790. CheckDerivedToBaseConversion(
  4791. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4792. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4793. SourceRange(), DeclarationName(), nullptr);
  4794. }
  4795. MarkFunctionReferenced(Location, Dtor);
  4796. DiagnoseUseOfDecl(Dtor, Location);
  4797. }
  4798. }
  4799. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4800. if (!CDtorDecl)
  4801. return;
  4802. if (CXXConstructorDecl *Constructor
  4803. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4804. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4805. DiagnoseUninitializedFields(*this, Constructor);
  4806. }
  4807. }
  4808. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4809. if (!getLangOpts().CPlusPlus)
  4810. return false;
  4811. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4812. if (!RD)
  4813. return false;
  4814. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4815. // class template specialization here, but doing so breaks a lot of code.
  4816. // We can't answer whether something is abstract until it has a
  4817. // definition. If it's currently being defined, we'll walk back
  4818. // over all the declarations when we have a full definition.
  4819. const CXXRecordDecl *Def = RD->getDefinition();
  4820. if (!Def || Def->isBeingDefined())
  4821. return false;
  4822. return RD->isAbstract();
  4823. }
  4824. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4825. TypeDiagnoser &Diagnoser) {
  4826. if (!isAbstractType(Loc, T))
  4827. return false;
  4828. T = Context.getBaseElementType(T);
  4829. Diagnoser.diagnose(*this, Loc, T);
  4830. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4831. return true;
  4832. }
  4833. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4834. // Check if we've already emitted the list of pure virtual functions
  4835. // for this class.
  4836. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4837. return;
  4838. // If the diagnostic is suppressed, don't emit the notes. We're only
  4839. // going to emit them once, so try to attach them to a diagnostic we're
  4840. // actually going to show.
  4841. if (Diags.isLastDiagnosticIgnored())
  4842. return;
  4843. CXXFinalOverriderMap FinalOverriders;
  4844. RD->getFinalOverriders(FinalOverriders);
  4845. // Keep a set of seen pure methods so we won't diagnose the same method
  4846. // more than once.
  4847. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4848. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4849. MEnd = FinalOverriders.end();
  4850. M != MEnd;
  4851. ++M) {
  4852. for (OverridingMethods::iterator SO = M->second.begin(),
  4853. SOEnd = M->second.end();
  4854. SO != SOEnd; ++SO) {
  4855. // C++ [class.abstract]p4:
  4856. // A class is abstract if it contains or inherits at least one
  4857. // pure virtual function for which the final overrider is pure
  4858. // virtual.
  4859. //
  4860. if (SO->second.size() != 1)
  4861. continue;
  4862. if (!SO->second.front().Method->isPure())
  4863. continue;
  4864. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4865. continue;
  4866. Diag(SO->second.front().Method->getLocation(),
  4867. diag::note_pure_virtual_function)
  4868. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4869. }
  4870. }
  4871. if (!PureVirtualClassDiagSet)
  4872. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4873. PureVirtualClassDiagSet->insert(RD);
  4874. }
  4875. namespace {
  4876. struct AbstractUsageInfo {
  4877. Sema &S;
  4878. CXXRecordDecl *Record;
  4879. CanQualType AbstractType;
  4880. bool Invalid;
  4881. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4882. : S(S), Record(Record),
  4883. AbstractType(S.Context.getCanonicalType(
  4884. S.Context.getTypeDeclType(Record))),
  4885. Invalid(false) {}
  4886. void DiagnoseAbstractType() {
  4887. if (Invalid) return;
  4888. S.DiagnoseAbstractType(Record);
  4889. Invalid = true;
  4890. }
  4891. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4892. };
  4893. struct CheckAbstractUsage {
  4894. AbstractUsageInfo &Info;
  4895. const NamedDecl *Ctx;
  4896. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4897. : Info(Info), Ctx(Ctx) {}
  4898. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4899. switch (TL.getTypeLocClass()) {
  4900. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4901. #define TYPELOC(CLASS, PARENT) \
  4902. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4903. #include "clang/AST/TypeLocNodes.def"
  4904. }
  4905. }
  4906. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4907. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4908. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4909. if (!TL.getParam(I))
  4910. continue;
  4911. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4912. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4913. }
  4914. }
  4915. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4916. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4917. }
  4918. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4919. // Visit the type parameters from a permissive context.
  4920. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4921. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4922. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4923. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4924. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4925. // TODO: other template argument types?
  4926. }
  4927. }
  4928. // Visit pointee types from a permissive context.
  4929. #define CheckPolymorphic(Type) \
  4930. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4931. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4932. }
  4933. CheckPolymorphic(PointerTypeLoc)
  4934. CheckPolymorphic(ReferenceTypeLoc)
  4935. CheckPolymorphic(MemberPointerTypeLoc)
  4936. CheckPolymorphic(BlockPointerTypeLoc)
  4937. CheckPolymorphic(AtomicTypeLoc)
  4938. /// Handle all the types we haven't given a more specific
  4939. /// implementation for above.
  4940. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4941. // Every other kind of type that we haven't called out already
  4942. // that has an inner type is either (1) sugar or (2) contains that
  4943. // inner type in some way as a subobject.
  4944. if (TypeLoc Next = TL.getNextTypeLoc())
  4945. return Visit(Next, Sel);
  4946. // If there's no inner type and we're in a permissive context,
  4947. // don't diagnose.
  4948. if (Sel == Sema::AbstractNone) return;
  4949. // Check whether the type matches the abstract type.
  4950. QualType T = TL.getType();
  4951. if (T->isArrayType()) {
  4952. Sel = Sema::AbstractArrayType;
  4953. T = Info.S.Context.getBaseElementType(T);
  4954. }
  4955. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4956. if (CT != Info.AbstractType) return;
  4957. // It matched; do some magic.
  4958. if (Sel == Sema::AbstractArrayType) {
  4959. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4960. << T << TL.getSourceRange();
  4961. } else {
  4962. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4963. << Sel << T << TL.getSourceRange();
  4964. }
  4965. Info.DiagnoseAbstractType();
  4966. }
  4967. };
  4968. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4969. Sema::AbstractDiagSelID Sel) {
  4970. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4971. }
  4972. }
  4973. /// Check for invalid uses of an abstract type in a method declaration.
  4974. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4975. CXXMethodDecl *MD) {
  4976. // No need to do the check on definitions, which require that
  4977. // the return/param types be complete.
  4978. if (MD->doesThisDeclarationHaveABody())
  4979. return;
  4980. // For safety's sake, just ignore it if we don't have type source
  4981. // information. This should never happen for non-implicit methods,
  4982. // but...
  4983. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4984. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4985. }
  4986. /// Check for invalid uses of an abstract type within a class definition.
  4987. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4988. CXXRecordDecl *RD) {
  4989. for (auto *D : RD->decls()) {
  4990. if (D->isImplicit()) continue;
  4991. // Methods and method templates.
  4992. if (isa<CXXMethodDecl>(D)) {
  4993. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4994. } else if (isa<FunctionTemplateDecl>(D)) {
  4995. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4996. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4997. // Fields and static variables.
  4998. } else if (isa<FieldDecl>(D)) {
  4999. FieldDecl *FD = cast<FieldDecl>(D);
  5000. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  5001. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  5002. } else if (isa<VarDecl>(D)) {
  5003. VarDecl *VD = cast<VarDecl>(D);
  5004. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  5005. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  5006. // Nested classes and class templates.
  5007. } else if (isa<CXXRecordDecl>(D)) {
  5008. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  5009. } else if (isa<ClassTemplateDecl>(D)) {
  5010. CheckAbstractClassUsage(Info,
  5011. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  5012. }
  5013. }
  5014. }
  5015. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  5016. Attr *ClassAttr = getDLLAttr(Class);
  5017. if (!ClassAttr)
  5018. return;
  5019. assert(ClassAttr->getKind() == attr::DLLExport);
  5020. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5021. if (TSK == TSK_ExplicitInstantiationDeclaration)
  5022. // Don't go any further if this is just an explicit instantiation
  5023. // declaration.
  5024. return;
  5025. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  5026. S.MarkVTableUsed(Class->getLocation(), Class, true);
  5027. for (Decl *Member : Class->decls()) {
  5028. // Defined static variables that are members of an exported base
  5029. // class must be marked export too.
  5030. auto *VD = dyn_cast<VarDecl>(Member);
  5031. if (VD && Member->getAttr<DLLExportAttr>() &&
  5032. VD->getStorageClass() == SC_Static &&
  5033. TSK == TSK_ImplicitInstantiation)
  5034. S.MarkVariableReferenced(VD->getLocation(), VD);
  5035. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  5036. if (!MD)
  5037. continue;
  5038. if (Member->getAttr<DLLExportAttr>()) {
  5039. if (MD->isUserProvided()) {
  5040. // Instantiate non-default class member functions ...
  5041. // .. except for certain kinds of template specializations.
  5042. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  5043. continue;
  5044. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5045. // The function will be passed to the consumer when its definition is
  5046. // encountered.
  5047. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  5048. MD->isCopyAssignmentOperator() ||
  5049. MD->isMoveAssignmentOperator()) {
  5050. // Synthesize and instantiate non-trivial implicit methods, explicitly
  5051. // defaulted methods, and the copy and move assignment operators. The
  5052. // latter are exported even if they are trivial, because the address of
  5053. // an operator can be taken and should compare equal across libraries.
  5054. DiagnosticErrorTrap Trap(S.Diags);
  5055. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5056. if (Trap.hasErrorOccurred()) {
  5057. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  5058. << Class << !S.getLangOpts().CPlusPlus11;
  5059. break;
  5060. }
  5061. // There is no later point when we will see the definition of this
  5062. // function, so pass it to the consumer now.
  5063. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5064. }
  5065. }
  5066. }
  5067. }
  5068. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  5069. CXXRecordDecl *Class) {
  5070. // Only the MS ABI has default constructor closures, so we don't need to do
  5071. // this semantic checking anywhere else.
  5072. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  5073. return;
  5074. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  5075. for (Decl *Member : Class->decls()) {
  5076. // Look for exported default constructors.
  5077. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  5078. if (!CD || !CD->isDefaultConstructor())
  5079. continue;
  5080. auto *Attr = CD->getAttr<DLLExportAttr>();
  5081. if (!Attr)
  5082. continue;
  5083. // If the class is non-dependent, mark the default arguments as ODR-used so
  5084. // that we can properly codegen the constructor closure.
  5085. if (!Class->isDependentContext()) {
  5086. for (ParmVarDecl *PD : CD->parameters()) {
  5087. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  5088. S.DiscardCleanupsInEvaluationContext();
  5089. }
  5090. }
  5091. if (LastExportedDefaultCtor) {
  5092. S.Diag(LastExportedDefaultCtor->getLocation(),
  5093. diag::err_attribute_dll_ambiguous_default_ctor)
  5094. << Class;
  5095. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  5096. << CD->getDeclName();
  5097. return;
  5098. }
  5099. LastExportedDefaultCtor = CD;
  5100. }
  5101. }
  5102. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  5103. // Mark any compiler-generated routines with the implicit code_seg attribute.
  5104. for (auto *Method : Class->methods()) {
  5105. if (Method->isUserProvided())
  5106. continue;
  5107. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  5108. Method->addAttr(A);
  5109. }
  5110. }
  5111. /// Check class-level dllimport/dllexport attribute.
  5112. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  5113. Attr *ClassAttr = getDLLAttr(Class);
  5114. // MSVC inherits DLL attributes to partial class template specializations.
  5115. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  5116. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  5117. if (Attr *TemplateAttr =
  5118. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  5119. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  5120. A->setInherited(true);
  5121. ClassAttr = A;
  5122. }
  5123. }
  5124. }
  5125. if (!ClassAttr)
  5126. return;
  5127. if (!Class->isExternallyVisible()) {
  5128. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  5129. << Class << ClassAttr;
  5130. return;
  5131. }
  5132. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5133. !ClassAttr->isInherited()) {
  5134. // Diagnose dll attributes on members of class with dll attribute.
  5135. for (Decl *Member : Class->decls()) {
  5136. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  5137. continue;
  5138. InheritableAttr *MemberAttr = getDLLAttr(Member);
  5139. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  5140. continue;
  5141. Diag(MemberAttr->getLocation(),
  5142. diag::err_attribute_dll_member_of_dll_class)
  5143. << MemberAttr << ClassAttr;
  5144. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  5145. Member->setInvalidDecl();
  5146. }
  5147. }
  5148. if (Class->getDescribedClassTemplate())
  5149. // Don't inherit dll attribute until the template is instantiated.
  5150. return;
  5151. // The class is either imported or exported.
  5152. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  5153. // Check if this was a dllimport attribute propagated from a derived class to
  5154. // a base class template specialization. We don't apply these attributes to
  5155. // static data members.
  5156. const bool PropagatedImport =
  5157. !ClassExported &&
  5158. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  5159. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5160. // Ignore explicit dllexport on explicit class template instantiation
  5161. // declarations, except in MinGW mode.
  5162. if (ClassExported && !ClassAttr->isInherited() &&
  5163. TSK == TSK_ExplicitInstantiationDeclaration &&
  5164. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  5165. Class->dropAttr<DLLExportAttr>();
  5166. return;
  5167. }
  5168. // Force declaration of implicit members so they can inherit the attribute.
  5169. ForceDeclarationOfImplicitMembers(Class);
  5170. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  5171. // seem to be true in practice?
  5172. for (Decl *Member : Class->decls()) {
  5173. VarDecl *VD = dyn_cast<VarDecl>(Member);
  5174. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5175. // Only methods and static fields inherit the attributes.
  5176. if (!VD && !MD)
  5177. continue;
  5178. if (MD) {
  5179. // Don't process deleted methods.
  5180. if (MD->isDeleted())
  5181. continue;
  5182. if (MD->isInlined()) {
  5183. // MinGW does not import or export inline methods. But do it for
  5184. // template instantiations.
  5185. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5186. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
  5187. TSK != TSK_ExplicitInstantiationDeclaration &&
  5188. TSK != TSK_ExplicitInstantiationDefinition)
  5189. continue;
  5190. // MSVC versions before 2015 don't export the move assignment operators
  5191. // and move constructor, so don't attempt to import/export them if
  5192. // we have a definition.
  5193. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5194. if ((MD->isMoveAssignmentOperator() ||
  5195. (Ctor && Ctor->isMoveConstructor())) &&
  5196. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5197. continue;
  5198. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5199. // operator is exported anyway.
  5200. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5201. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5202. continue;
  5203. }
  5204. }
  5205. // Don't apply dllimport attributes to static data members of class template
  5206. // instantiations when the attribute is propagated from a derived class.
  5207. if (VD && PropagatedImport)
  5208. continue;
  5209. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5210. continue;
  5211. if (!getDLLAttr(Member)) {
  5212. InheritableAttr *NewAttr = nullptr;
  5213. // Do not export/import inline function when -fno-dllexport-inlines is
  5214. // passed. But add attribute for later local static var check.
  5215. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5216. TSK != TSK_ExplicitInstantiationDeclaration &&
  5217. TSK != TSK_ExplicitInstantiationDefinition) {
  5218. if (ClassExported) {
  5219. NewAttr = ::new (getASTContext())
  5220. DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
  5221. } else {
  5222. NewAttr = ::new (getASTContext())
  5223. DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
  5224. }
  5225. } else {
  5226. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5227. }
  5228. NewAttr->setInherited(true);
  5229. Member->addAttr(NewAttr);
  5230. if (MD) {
  5231. // Propagate DLLAttr to friend re-declarations of MD that have already
  5232. // been constructed.
  5233. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5234. FD = FD->getPreviousDecl()) {
  5235. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5236. continue;
  5237. assert(!getDLLAttr(FD) &&
  5238. "friend re-decl should not already have a DLLAttr");
  5239. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5240. NewAttr->setInherited(true);
  5241. FD->addAttr(NewAttr);
  5242. }
  5243. }
  5244. }
  5245. }
  5246. if (ClassExported)
  5247. DelayedDllExportClasses.push_back(Class);
  5248. }
  5249. /// Perform propagation of DLL attributes from a derived class to a
  5250. /// templated base class for MS compatibility.
  5251. void Sema::propagateDLLAttrToBaseClassTemplate(
  5252. CXXRecordDecl *Class, Attr *ClassAttr,
  5253. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5254. if (getDLLAttr(
  5255. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5256. // If the base class template has a DLL attribute, don't try to change it.
  5257. return;
  5258. }
  5259. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5260. if (!getDLLAttr(BaseTemplateSpec) &&
  5261. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5262. TSK == TSK_ImplicitInstantiation)) {
  5263. // The template hasn't been instantiated yet (or it has, but only as an
  5264. // explicit instantiation declaration or implicit instantiation, which means
  5265. // we haven't codegenned any members yet), so propagate the attribute.
  5266. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5267. NewAttr->setInherited(true);
  5268. BaseTemplateSpec->addAttr(NewAttr);
  5269. // If this was an import, mark that we propagated it from a derived class to
  5270. // a base class template specialization.
  5271. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5272. ImportAttr->setPropagatedToBaseTemplate();
  5273. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5274. // needs to be run again to work see the new attribute. Otherwise this will
  5275. // get run whenever the template is instantiated.
  5276. if (TSK != TSK_Undeclared)
  5277. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5278. return;
  5279. }
  5280. if (getDLLAttr(BaseTemplateSpec)) {
  5281. // The template has already been specialized or instantiated with an
  5282. // attribute, explicitly or through propagation. We should not try to change
  5283. // it.
  5284. return;
  5285. }
  5286. // The template was previously instantiated or explicitly specialized without
  5287. // a dll attribute, It's too late for us to add an attribute, so warn that
  5288. // this is unsupported.
  5289. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5290. << BaseTemplateSpec->isExplicitSpecialization();
  5291. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5292. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5293. Diag(BaseTemplateSpec->getLocation(),
  5294. diag::note_template_class_explicit_specialization_was_here)
  5295. << BaseTemplateSpec;
  5296. } else {
  5297. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5298. diag::note_template_class_instantiation_was_here)
  5299. << BaseTemplateSpec;
  5300. }
  5301. }
  5302. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5303. SourceLocation DefaultLoc) {
  5304. switch (S.getSpecialMember(MD)) {
  5305. case Sema::CXXDefaultConstructor:
  5306. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5307. cast<CXXConstructorDecl>(MD));
  5308. break;
  5309. case Sema::CXXCopyConstructor:
  5310. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5311. break;
  5312. case Sema::CXXCopyAssignment:
  5313. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5314. break;
  5315. case Sema::CXXDestructor:
  5316. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5317. break;
  5318. case Sema::CXXMoveConstructor:
  5319. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5320. break;
  5321. case Sema::CXXMoveAssignment:
  5322. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5323. break;
  5324. case Sema::CXXInvalid:
  5325. llvm_unreachable("Invalid special member.");
  5326. }
  5327. }
  5328. /// Determine whether a type is permitted to be passed or returned in
  5329. /// registers, per C++ [class.temporary]p3.
  5330. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5331. TargetInfo::CallingConvKind CCK) {
  5332. if (D->isDependentType() || D->isInvalidDecl())
  5333. return false;
  5334. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5335. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5336. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5337. return !D->hasNonTrivialDestructorForCall() &&
  5338. !D->hasNonTrivialCopyConstructorForCall();
  5339. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5340. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5341. bool DtorIsTrivialForCall = false;
  5342. // If a class has at least one non-deleted, trivial copy constructor, it
  5343. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5344. //
  5345. // Note: This permits classes with non-trivial copy or move ctors to be
  5346. // passed in registers, so long as they *also* have a trivial copy ctor,
  5347. // which is non-conforming.
  5348. if (D->needsImplicitCopyConstructor()) {
  5349. if (!D->defaultedCopyConstructorIsDeleted()) {
  5350. if (D->hasTrivialCopyConstructor())
  5351. CopyCtorIsTrivial = true;
  5352. if (D->hasTrivialCopyConstructorForCall())
  5353. CopyCtorIsTrivialForCall = true;
  5354. }
  5355. } else {
  5356. for (const CXXConstructorDecl *CD : D->ctors()) {
  5357. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5358. if (CD->isTrivial())
  5359. CopyCtorIsTrivial = true;
  5360. if (CD->isTrivialForCall())
  5361. CopyCtorIsTrivialForCall = true;
  5362. }
  5363. }
  5364. }
  5365. if (D->needsImplicitDestructor()) {
  5366. if (!D->defaultedDestructorIsDeleted() &&
  5367. D->hasTrivialDestructorForCall())
  5368. DtorIsTrivialForCall = true;
  5369. } else if (const auto *DD = D->getDestructor()) {
  5370. if (!DD->isDeleted() && DD->isTrivialForCall())
  5371. DtorIsTrivialForCall = true;
  5372. }
  5373. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5374. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5375. return true;
  5376. // If a class has a destructor, we'd really like to pass it indirectly
  5377. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5378. // impossible for small types, which it will pass in a single register or
  5379. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5380. // We can't call out all large objects as being indirect because there are
  5381. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5382. // how we pass large POD types.
  5383. // Note: This permits small classes with nontrivial destructors to be
  5384. // passed in registers, which is non-conforming.
  5385. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5386. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5387. if (CopyCtorIsTrivial &&
  5388. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5389. return true;
  5390. return false;
  5391. }
  5392. // Per C++ [class.temporary]p3, the relevant condition is:
  5393. // each copy constructor, move constructor, and destructor of X is
  5394. // either trivial or deleted, and X has at least one non-deleted copy
  5395. // or move constructor
  5396. bool HasNonDeletedCopyOrMove = false;
  5397. if (D->needsImplicitCopyConstructor() &&
  5398. !D->defaultedCopyConstructorIsDeleted()) {
  5399. if (!D->hasTrivialCopyConstructorForCall())
  5400. return false;
  5401. HasNonDeletedCopyOrMove = true;
  5402. }
  5403. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5404. !D->defaultedMoveConstructorIsDeleted()) {
  5405. if (!D->hasTrivialMoveConstructorForCall())
  5406. return false;
  5407. HasNonDeletedCopyOrMove = true;
  5408. }
  5409. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5410. !D->hasTrivialDestructorForCall())
  5411. return false;
  5412. for (const CXXMethodDecl *MD : D->methods()) {
  5413. if (MD->isDeleted())
  5414. continue;
  5415. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5416. if (CD && CD->isCopyOrMoveConstructor())
  5417. HasNonDeletedCopyOrMove = true;
  5418. else if (!isa<CXXDestructorDecl>(MD))
  5419. continue;
  5420. if (!MD->isTrivialForCall())
  5421. return false;
  5422. }
  5423. return HasNonDeletedCopyOrMove;
  5424. }
  5425. /// Perform semantic checks on a class definition that has been
  5426. /// completing, introducing implicitly-declared members, checking for
  5427. /// abstract types, etc.
  5428. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5429. if (!Record)
  5430. return;
  5431. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5432. AbstractUsageInfo Info(*this, Record);
  5433. CheckAbstractClassUsage(Info, Record);
  5434. }
  5435. // If this is not an aggregate type and has no user-declared constructor,
  5436. // complain about any non-static data members of reference or const scalar
  5437. // type, since they will never get initializers.
  5438. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5439. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5440. !Record->isLambda()) {
  5441. bool Complained = false;
  5442. for (const auto *F : Record->fields()) {
  5443. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5444. continue;
  5445. if (F->getType()->isReferenceType() ||
  5446. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5447. if (!Complained) {
  5448. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5449. << Record->getTagKind() << Record;
  5450. Complained = true;
  5451. }
  5452. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5453. << F->getType()->isReferenceType()
  5454. << F->getDeclName();
  5455. }
  5456. }
  5457. }
  5458. if (Record->getIdentifier()) {
  5459. // C++ [class.mem]p13:
  5460. // If T is the name of a class, then each of the following shall have a
  5461. // name different from T:
  5462. // - every member of every anonymous union that is a member of class T.
  5463. //
  5464. // C++ [class.mem]p14:
  5465. // In addition, if class T has a user-declared constructor (12.1), every
  5466. // non-static data member of class T shall have a name different from T.
  5467. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5468. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5469. ++I) {
  5470. NamedDecl *D = (*I)->getUnderlyingDecl();
  5471. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5472. Record->hasUserDeclaredConstructor()) ||
  5473. isa<IndirectFieldDecl>(D)) {
  5474. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5475. << D->getDeclName();
  5476. break;
  5477. }
  5478. }
  5479. }
  5480. // Warn if the class has virtual methods but non-virtual public destructor.
  5481. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5482. CXXDestructorDecl *dtor = Record->getDestructor();
  5483. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5484. !Record->hasAttr<FinalAttr>())
  5485. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5486. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5487. }
  5488. if (Record->isAbstract()) {
  5489. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5490. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5491. << FA->isSpelledAsSealed();
  5492. DiagnoseAbstractType(Record);
  5493. }
  5494. }
  5495. // Warn if the class has a final destructor but is not itself marked final.
  5496. if (!Record->hasAttr<FinalAttr>()) {
  5497. if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
  5498. if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
  5499. Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
  5500. << FA->isSpelledAsSealed()
  5501. << FixItHint::CreateInsertion(
  5502. getLocForEndOfToken(Record->getLocation()),
  5503. (FA->isSpelledAsSealed() ? " sealed" : " final"));
  5504. Diag(Record->getLocation(),
  5505. diag::note_final_dtor_non_final_class_silence)
  5506. << Context.getRecordType(Record) << FA->isSpelledAsSealed();
  5507. }
  5508. }
  5509. }
  5510. // See if trivial_abi has to be dropped.
  5511. if (Record->hasAttr<TrivialABIAttr>())
  5512. checkIllFormedTrivialABIStruct(*Record);
  5513. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5514. // "trivial_abi".
  5515. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5516. if (HasTrivialABI)
  5517. Record->setHasTrivialSpecialMemberForCall();
  5518. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  5519. // Check whether the explicitly-defaulted special members are valid.
  5520. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5521. CheckExplicitlyDefaultedSpecialMember(M);
  5522. // For an explicitly defaulted or deleted special member, we defer
  5523. // determining triviality until the class is complete. That time is now!
  5524. CXXSpecialMember CSM = getSpecialMember(M);
  5525. if (!M->isImplicit() && !M->isUserProvided()) {
  5526. if (CSM != CXXInvalid) {
  5527. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5528. // Inform the class that we've finished declaring this member.
  5529. Record->finishedDefaultedOrDeletedMember(M);
  5530. M->setTrivialForCall(
  5531. HasTrivialABI ||
  5532. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5533. Record->setTrivialForCallFlags(M);
  5534. }
  5535. }
  5536. // Set triviality for the purpose of calls if this is a user-provided
  5537. // copy/move constructor or destructor.
  5538. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5539. CSM == CXXDestructor) && M->isUserProvided()) {
  5540. M->setTrivialForCall(HasTrivialABI);
  5541. Record->setTrivialForCallFlags(M);
  5542. }
  5543. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5544. M->hasAttr<DLLExportAttr>()) {
  5545. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5546. M->isTrivial() &&
  5547. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5548. CSM == CXXDestructor))
  5549. M->dropAttr<DLLExportAttr>();
  5550. if (M->hasAttr<DLLExportAttr>()) {
  5551. // Define after any fields with in-class initializers have been parsed.
  5552. DelayedDllExportMemberFunctions.push_back(M);
  5553. }
  5554. }
  5555. // Define defaulted constexpr virtual functions that override a base class
  5556. // function right away.
  5557. // FIXME: We can defer doing this until the vtable is marked as used.
  5558. if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
  5559. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5560. };
  5561. bool HasMethodWithOverrideControl = false,
  5562. HasOverridingMethodWithoutOverrideControl = false;
  5563. if (!Record->isDependentType()) {
  5564. // Check the destructor before any other member function. We need to
  5565. // determine whether it's trivial in order to determine whether the claas
  5566. // type is a literal type, which is a prerequisite for determining whether
  5567. // other special member functions are valid and whether they're implicitly
  5568. // 'constexpr'.
  5569. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  5570. CompleteMemberFunction(Dtor);
  5571. for (auto *M : Record->methods()) {
  5572. // See if a method overloads virtual methods in a base
  5573. // class without overriding any.
  5574. if (!M->isStatic())
  5575. DiagnoseHiddenVirtualMethods(M);
  5576. if (M->hasAttr<OverrideAttr>())
  5577. HasMethodWithOverrideControl = true;
  5578. else if (M->size_overridden_methods() > 0)
  5579. HasOverridingMethodWithoutOverrideControl = true;
  5580. if (!isa<CXXDestructorDecl>(M))
  5581. CompleteMemberFunction(M);
  5582. }
  5583. }
  5584. if (HasMethodWithOverrideControl &&
  5585. HasOverridingMethodWithoutOverrideControl) {
  5586. // At least one method has the 'override' control declared.
  5587. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5588. for (auto *M : Record->methods())
  5589. DiagnoseAbsenceOfOverrideControl(M);
  5590. }
  5591. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5592. // whether this class uses any C++ features that are implemented
  5593. // completely differently in MSVC, and if so, emit a diagnostic.
  5594. // That diagnostic defaults to an error, but we allow projects to
  5595. // map it down to a warning (or ignore it). It's a fairly common
  5596. // practice among users of the ms_struct pragma to mass-annotate
  5597. // headers, sweeping up a bunch of types that the project doesn't
  5598. // really rely on MSVC-compatible layout for. We must therefore
  5599. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5600. if (Record->isMsStruct(Context) &&
  5601. (Record->isPolymorphic() || Record->getNumBases())) {
  5602. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5603. }
  5604. checkClassLevelDLLAttribute(Record);
  5605. checkClassLevelCodeSegAttribute(Record);
  5606. bool ClangABICompat4 =
  5607. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5608. TargetInfo::CallingConvKind CCK =
  5609. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5610. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5611. // Do not change ArgPassingRestrictions if it has already been set to
  5612. // APK_CanNeverPassInRegs.
  5613. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5614. Record->setArgPassingRestrictions(CanPass
  5615. ? RecordDecl::APK_CanPassInRegs
  5616. : RecordDecl::APK_CannotPassInRegs);
  5617. // If canPassInRegisters returns true despite the record having a non-trivial
  5618. // destructor, the record is destructed in the callee. This happens only when
  5619. // the record or one of its subobjects has a field annotated with trivial_abi
  5620. // or a field qualified with ObjC __strong/__weak.
  5621. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5622. Record->setParamDestroyedInCallee(true);
  5623. else if (Record->hasNonTrivialDestructor())
  5624. Record->setParamDestroyedInCallee(CanPass);
  5625. if (getLangOpts().ForceEmitVTables) {
  5626. // If we want to emit all the vtables, we need to mark it as used. This
  5627. // is especially required for cases like vtable assumption loads.
  5628. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5629. }
  5630. }
  5631. /// Look up the special member function that would be called by a special
  5632. /// member function for a subobject of class type.
  5633. ///
  5634. /// \param Class The class type of the subobject.
  5635. /// \param CSM The kind of special member function.
  5636. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5637. /// \param ConstRHS True if this is a copy operation with a const object
  5638. /// on its RHS, that is, if the argument to the outer special member
  5639. /// function is 'const' and this is not a field marked 'mutable'.
  5640. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5641. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5642. unsigned FieldQuals, bool ConstRHS) {
  5643. unsigned LHSQuals = 0;
  5644. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5645. LHSQuals = FieldQuals;
  5646. unsigned RHSQuals = FieldQuals;
  5647. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5648. RHSQuals = 0;
  5649. else if (ConstRHS)
  5650. RHSQuals |= Qualifiers::Const;
  5651. return S.LookupSpecialMember(Class, CSM,
  5652. RHSQuals & Qualifiers::Const,
  5653. RHSQuals & Qualifiers::Volatile,
  5654. false,
  5655. LHSQuals & Qualifiers::Const,
  5656. LHSQuals & Qualifiers::Volatile);
  5657. }
  5658. class Sema::InheritedConstructorInfo {
  5659. Sema &S;
  5660. SourceLocation UseLoc;
  5661. /// A mapping from the base classes through which the constructor was
  5662. /// inherited to the using shadow declaration in that base class (or a null
  5663. /// pointer if the constructor was declared in that base class).
  5664. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5665. InheritedFromBases;
  5666. public:
  5667. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5668. ConstructorUsingShadowDecl *Shadow)
  5669. : S(S), UseLoc(UseLoc) {
  5670. bool DiagnosedMultipleConstructedBases = false;
  5671. CXXRecordDecl *ConstructedBase = nullptr;
  5672. UsingDecl *ConstructedBaseUsing = nullptr;
  5673. // Find the set of such base class subobjects and check that there's a
  5674. // unique constructed subobject.
  5675. for (auto *D : Shadow->redecls()) {
  5676. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5677. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5678. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5679. InheritedFromBases.insert(
  5680. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5681. DShadow->getNominatedBaseClassShadowDecl()));
  5682. if (DShadow->constructsVirtualBase())
  5683. InheritedFromBases.insert(
  5684. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5685. DShadow->getConstructedBaseClassShadowDecl()));
  5686. else
  5687. assert(DNominatedBase == DConstructedBase);
  5688. // [class.inhctor.init]p2:
  5689. // If the constructor was inherited from multiple base class subobjects
  5690. // of type B, the program is ill-formed.
  5691. if (!ConstructedBase) {
  5692. ConstructedBase = DConstructedBase;
  5693. ConstructedBaseUsing = D->getUsingDecl();
  5694. } else if (ConstructedBase != DConstructedBase &&
  5695. !Shadow->isInvalidDecl()) {
  5696. if (!DiagnosedMultipleConstructedBases) {
  5697. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5698. << Shadow->getTargetDecl();
  5699. S.Diag(ConstructedBaseUsing->getLocation(),
  5700. diag::note_ambiguous_inherited_constructor_using)
  5701. << ConstructedBase;
  5702. DiagnosedMultipleConstructedBases = true;
  5703. }
  5704. S.Diag(D->getUsingDecl()->getLocation(),
  5705. diag::note_ambiguous_inherited_constructor_using)
  5706. << DConstructedBase;
  5707. }
  5708. }
  5709. if (DiagnosedMultipleConstructedBases)
  5710. Shadow->setInvalidDecl();
  5711. }
  5712. /// Find the constructor to use for inherited construction of a base class,
  5713. /// and whether that base class constructor inherits the constructor from a
  5714. /// virtual base class (in which case it won't actually invoke it).
  5715. std::pair<CXXConstructorDecl *, bool>
  5716. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5717. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5718. if (It == InheritedFromBases.end())
  5719. return std::make_pair(nullptr, false);
  5720. // This is an intermediary class.
  5721. if (It->second)
  5722. return std::make_pair(
  5723. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5724. It->second->constructsVirtualBase());
  5725. // This is the base class from which the constructor was inherited.
  5726. return std::make_pair(Ctor, false);
  5727. }
  5728. };
  5729. /// Is the special member function which would be selected to perform the
  5730. /// specified operation on the specified class type a constexpr constructor?
  5731. static bool
  5732. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5733. Sema::CXXSpecialMember CSM, unsigned Quals,
  5734. bool ConstRHS,
  5735. CXXConstructorDecl *InheritedCtor = nullptr,
  5736. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5737. // If we're inheriting a constructor, see if we need to call it for this base
  5738. // class.
  5739. if (InheritedCtor) {
  5740. assert(CSM == Sema::CXXDefaultConstructor);
  5741. auto BaseCtor =
  5742. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5743. if (BaseCtor)
  5744. return BaseCtor->isConstexpr();
  5745. }
  5746. if (CSM == Sema::CXXDefaultConstructor)
  5747. return ClassDecl->hasConstexprDefaultConstructor();
  5748. if (CSM == Sema::CXXDestructor)
  5749. return ClassDecl->hasConstexprDestructor();
  5750. Sema::SpecialMemberOverloadResult SMOR =
  5751. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5752. if (!SMOR.getMethod())
  5753. // A constructor we wouldn't select can't be "involved in initializing"
  5754. // anything.
  5755. return true;
  5756. return SMOR.getMethod()->isConstexpr();
  5757. }
  5758. /// Determine whether the specified special member function would be constexpr
  5759. /// if it were implicitly defined.
  5760. static bool defaultedSpecialMemberIsConstexpr(
  5761. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5762. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5763. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5764. if (!S.getLangOpts().CPlusPlus11)
  5765. return false;
  5766. // C++11 [dcl.constexpr]p4:
  5767. // In the definition of a constexpr constructor [...]
  5768. bool Ctor = true;
  5769. switch (CSM) {
  5770. case Sema::CXXDefaultConstructor:
  5771. if (Inherited)
  5772. break;
  5773. // Since default constructor lookup is essentially trivial (and cannot
  5774. // involve, for instance, template instantiation), we compute whether a
  5775. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5776. //
  5777. // This is important for performance; we need to know whether the default
  5778. // constructor is constexpr to determine whether the type is a literal type.
  5779. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5780. case Sema::CXXCopyConstructor:
  5781. case Sema::CXXMoveConstructor:
  5782. // For copy or move constructors, we need to perform overload resolution.
  5783. break;
  5784. case Sema::CXXCopyAssignment:
  5785. case Sema::CXXMoveAssignment:
  5786. if (!S.getLangOpts().CPlusPlus14)
  5787. return false;
  5788. // In C++1y, we need to perform overload resolution.
  5789. Ctor = false;
  5790. break;
  5791. case Sema::CXXDestructor:
  5792. return ClassDecl->defaultedDestructorIsConstexpr();
  5793. case Sema::CXXInvalid:
  5794. return false;
  5795. }
  5796. // -- if the class is a non-empty union, or for each non-empty anonymous
  5797. // union member of a non-union class, exactly one non-static data member
  5798. // shall be initialized; [DR1359]
  5799. //
  5800. // If we squint, this is guaranteed, since exactly one non-static data member
  5801. // will be initialized (if the constructor isn't deleted), we just don't know
  5802. // which one.
  5803. if (Ctor && ClassDecl->isUnion())
  5804. return CSM == Sema::CXXDefaultConstructor
  5805. ? ClassDecl->hasInClassInitializer() ||
  5806. !ClassDecl->hasVariantMembers()
  5807. : true;
  5808. // -- the class shall not have any virtual base classes;
  5809. if (Ctor && ClassDecl->getNumVBases())
  5810. return false;
  5811. // C++1y [class.copy]p26:
  5812. // -- [the class] is a literal type, and
  5813. if (!Ctor && !ClassDecl->isLiteral())
  5814. return false;
  5815. // -- every constructor involved in initializing [...] base class
  5816. // sub-objects shall be a constexpr constructor;
  5817. // -- the assignment operator selected to copy/move each direct base
  5818. // class is a constexpr function, and
  5819. for (const auto &B : ClassDecl->bases()) {
  5820. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5821. if (!BaseType) continue;
  5822. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5823. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5824. InheritedCtor, Inherited))
  5825. return false;
  5826. }
  5827. // -- every constructor involved in initializing non-static data members
  5828. // [...] shall be a constexpr constructor;
  5829. // -- every non-static data member and base class sub-object shall be
  5830. // initialized
  5831. // -- for each non-static data member of X that is of class type (or array
  5832. // thereof), the assignment operator selected to copy/move that member is
  5833. // a constexpr function
  5834. for (const auto *F : ClassDecl->fields()) {
  5835. if (F->isInvalidDecl())
  5836. continue;
  5837. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5838. continue;
  5839. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5840. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5841. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5842. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5843. BaseType.getCVRQualifiers(),
  5844. ConstArg && !F->isMutable()))
  5845. return false;
  5846. } else if (CSM == Sema::CXXDefaultConstructor) {
  5847. return false;
  5848. }
  5849. }
  5850. // All OK, it's constexpr!
  5851. return true;
  5852. }
  5853. static Sema::ImplicitExceptionSpecification
  5854. ComputeDefaultedSpecialMemberExceptionSpec(
  5855. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5856. Sema::InheritedConstructorInfo *ICI);
  5857. static Sema::ImplicitExceptionSpecification
  5858. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5859. auto CSM = S.getSpecialMember(MD);
  5860. if (CSM != Sema::CXXInvalid)
  5861. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5862. auto *CD = cast<CXXConstructorDecl>(MD);
  5863. assert(CD->getInheritedConstructor() &&
  5864. "only special members have implicit exception specs");
  5865. Sema::InheritedConstructorInfo ICI(
  5866. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5867. return ComputeDefaultedSpecialMemberExceptionSpec(
  5868. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5869. }
  5870. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5871. CXXMethodDecl *MD) {
  5872. FunctionProtoType::ExtProtoInfo EPI;
  5873. // Build an exception specification pointing back at this member.
  5874. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5875. EPI.ExceptionSpec.SourceDecl = MD;
  5876. // Set the calling convention to the default for C++ instance methods.
  5877. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5878. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5879. /*IsCXXMethod=*/true));
  5880. return EPI;
  5881. }
  5882. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5883. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5884. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5885. return;
  5886. // Evaluate the exception specification.
  5887. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5888. auto ESI = IES.getExceptionSpec();
  5889. // Update the type of the special member to use it.
  5890. UpdateExceptionSpec(MD, ESI);
  5891. // A user-provided destructor can be defined outside the class. When that
  5892. // happens, be sure to update the exception specification on both
  5893. // declarations.
  5894. const FunctionProtoType *CanonicalFPT =
  5895. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5896. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5897. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5898. }
  5899. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5900. CXXRecordDecl *RD = MD->getParent();
  5901. CXXSpecialMember CSM = getSpecialMember(MD);
  5902. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5903. "not an explicitly-defaulted special member");
  5904. // Whether this was the first-declared instance of the constructor.
  5905. // This affects whether we implicitly add an exception spec and constexpr.
  5906. bool First = MD == MD->getCanonicalDecl();
  5907. bool HadError = false;
  5908. // C++11 [dcl.fct.def.default]p1:
  5909. // A function that is explicitly defaulted shall
  5910. // -- be a special member function (checked elsewhere),
  5911. // -- have the same type (except for ref-qualifiers, and except that a
  5912. // copy operation can take a non-const reference) as an implicit
  5913. // declaration, and
  5914. // -- not have default arguments.
  5915. // C++2a changes the second bullet to instead delete the function if it's
  5916. // defaulted on its first declaration, unless it's "an assignment operator,
  5917. // and its return type differs or its parameter type is not a reference".
  5918. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
  5919. bool ShouldDeleteForTypeMismatch = false;
  5920. unsigned ExpectedParams = 1;
  5921. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5922. ExpectedParams = 0;
  5923. if (MD->getNumParams() != ExpectedParams) {
  5924. // This checks for default arguments: a copy or move constructor with a
  5925. // default argument is classified as a default constructor, and assignment
  5926. // operations and destructors can't have default arguments.
  5927. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5928. << CSM << MD->getSourceRange();
  5929. HadError = true;
  5930. } else if (MD->isVariadic()) {
  5931. if (DeleteOnTypeMismatch)
  5932. ShouldDeleteForTypeMismatch = true;
  5933. else {
  5934. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5935. << CSM << MD->getSourceRange();
  5936. HadError = true;
  5937. }
  5938. }
  5939. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5940. bool CanHaveConstParam = false;
  5941. if (CSM == CXXCopyConstructor)
  5942. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5943. else if (CSM == CXXCopyAssignment)
  5944. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5945. QualType ReturnType = Context.VoidTy;
  5946. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5947. // Check for return type matching.
  5948. ReturnType = Type->getReturnType();
  5949. QualType DeclType = Context.getTypeDeclType(RD);
  5950. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  5951. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  5952. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5953. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5954. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5955. HadError = true;
  5956. }
  5957. // A defaulted special member cannot have cv-qualifiers.
  5958. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  5959. if (DeleteOnTypeMismatch)
  5960. ShouldDeleteForTypeMismatch = true;
  5961. else {
  5962. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5963. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5964. HadError = true;
  5965. }
  5966. }
  5967. }
  5968. // Check for parameter type matching.
  5969. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5970. bool HasConstParam = false;
  5971. if (ExpectedParams && ArgType->isReferenceType()) {
  5972. // Argument must be reference to possibly-const T.
  5973. QualType ReferentType = ArgType->getPointeeType();
  5974. HasConstParam = ReferentType.isConstQualified();
  5975. if (ReferentType.isVolatileQualified()) {
  5976. if (DeleteOnTypeMismatch)
  5977. ShouldDeleteForTypeMismatch = true;
  5978. else {
  5979. Diag(MD->getLocation(),
  5980. diag::err_defaulted_special_member_volatile_param) << CSM;
  5981. HadError = true;
  5982. }
  5983. }
  5984. if (HasConstParam && !CanHaveConstParam) {
  5985. if (DeleteOnTypeMismatch)
  5986. ShouldDeleteForTypeMismatch = true;
  5987. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5988. Diag(MD->getLocation(),
  5989. diag::err_defaulted_special_member_copy_const_param)
  5990. << (CSM == CXXCopyAssignment);
  5991. // FIXME: Explain why this special member can't be const.
  5992. HadError = true;
  5993. } else {
  5994. Diag(MD->getLocation(),
  5995. diag::err_defaulted_special_member_move_const_param)
  5996. << (CSM == CXXMoveAssignment);
  5997. HadError = true;
  5998. }
  5999. }
  6000. } else if (ExpectedParams) {
  6001. // A copy assignment operator can take its argument by value, but a
  6002. // defaulted one cannot.
  6003. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  6004. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  6005. HadError = true;
  6006. }
  6007. // C++11 [dcl.fct.def.default]p2:
  6008. // An explicitly-defaulted function may be declared constexpr only if it
  6009. // would have been implicitly declared as constexpr,
  6010. // Do not apply this rule to members of class templates, since core issue 1358
  6011. // makes such functions always instantiate to constexpr functions. For
  6012. // functions which cannot be constexpr (for non-constructors in C++11 and for
  6013. // destructors in C++14 and C++17), this is checked elsewhere.
  6014. //
  6015. // FIXME: This should not apply if the member is deleted.
  6016. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  6017. HasConstParam);
  6018. if ((getLangOpts().CPlusPlus2a ||
  6019. (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  6020. : isa<CXXConstructorDecl>(MD))) &&
  6021. MD->isConstexpr() && !Constexpr &&
  6022. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  6023. Diag(MD->getBeginLoc(), MD->isConsteval()
  6024. ? diag::err_incorrect_defaulted_consteval
  6025. : diag::err_incorrect_defaulted_constexpr)
  6026. << CSM;
  6027. // FIXME: Explain why the special member can't be constexpr.
  6028. HadError = true;
  6029. }
  6030. if (First) {
  6031. // C++2a [dcl.fct.def.default]p3:
  6032. // If a function is explicitly defaulted on its first declaration, it is
  6033. // implicitly considered to be constexpr if the implicit declaration
  6034. // would be.
  6035. MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
  6036. if (!Type->hasExceptionSpec()) {
  6037. // C++2a [except.spec]p3:
  6038. // If a declaration of a function does not have a noexcept-specifier
  6039. // [and] is defaulted on its first declaration, [...] the exception
  6040. // specification is as specified below
  6041. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  6042. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6043. EPI.ExceptionSpec.SourceDecl = MD;
  6044. MD->setType(Context.getFunctionType(ReturnType,
  6045. llvm::makeArrayRef(&ArgType,
  6046. ExpectedParams),
  6047. EPI));
  6048. }
  6049. }
  6050. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  6051. if (First) {
  6052. SetDeclDeleted(MD, MD->getLocation());
  6053. if (!inTemplateInstantiation() && !HadError) {
  6054. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  6055. if (ShouldDeleteForTypeMismatch) {
  6056. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  6057. } else {
  6058. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6059. }
  6060. }
  6061. if (ShouldDeleteForTypeMismatch && !HadError) {
  6062. Diag(MD->getLocation(),
  6063. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  6064. }
  6065. } else {
  6066. // C++11 [dcl.fct.def.default]p4:
  6067. // [For a] user-provided explicitly-defaulted function [...] if such a
  6068. // function is implicitly defined as deleted, the program is ill-formed.
  6069. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  6070. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  6071. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6072. HadError = true;
  6073. }
  6074. }
  6075. if (HadError)
  6076. MD->setInvalidDecl();
  6077. }
  6078. void Sema::CheckDelayedMemberExceptionSpecs() {
  6079. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  6080. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  6081. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  6082. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  6083. // Perform any deferred checking of exception specifications for virtual
  6084. // destructors.
  6085. for (auto &Check : Overriding)
  6086. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  6087. // Perform any deferred checking of exception specifications for befriended
  6088. // special members.
  6089. for (auto &Check : Equivalent)
  6090. CheckEquivalentExceptionSpec(Check.second, Check.first);
  6091. }
  6092. namespace {
  6093. /// CRTP base class for visiting operations performed by a special member
  6094. /// function (or inherited constructor).
  6095. template<typename Derived>
  6096. struct SpecialMemberVisitor {
  6097. Sema &S;
  6098. CXXMethodDecl *MD;
  6099. Sema::CXXSpecialMember CSM;
  6100. Sema::InheritedConstructorInfo *ICI;
  6101. // Properties of the special member, computed for convenience.
  6102. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  6103. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  6104. Sema::InheritedConstructorInfo *ICI)
  6105. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  6106. switch (CSM) {
  6107. case Sema::CXXDefaultConstructor:
  6108. case Sema::CXXCopyConstructor:
  6109. case Sema::CXXMoveConstructor:
  6110. IsConstructor = true;
  6111. break;
  6112. case Sema::CXXCopyAssignment:
  6113. case Sema::CXXMoveAssignment:
  6114. IsAssignment = true;
  6115. break;
  6116. case Sema::CXXDestructor:
  6117. break;
  6118. case Sema::CXXInvalid:
  6119. llvm_unreachable("invalid special member kind");
  6120. }
  6121. if (MD->getNumParams()) {
  6122. if (const ReferenceType *RT =
  6123. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  6124. ConstArg = RT->getPointeeType().isConstQualified();
  6125. }
  6126. }
  6127. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6128. /// Is this a "move" special member?
  6129. bool isMove() const {
  6130. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  6131. }
  6132. /// Look up the corresponding special member in the given class.
  6133. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  6134. unsigned Quals, bool IsMutable) {
  6135. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  6136. ConstArg && !IsMutable);
  6137. }
  6138. /// Look up the constructor for the specified base class to see if it's
  6139. /// overridden due to this being an inherited constructor.
  6140. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  6141. if (!ICI)
  6142. return {};
  6143. assert(CSM == Sema::CXXDefaultConstructor);
  6144. auto *BaseCtor =
  6145. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  6146. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  6147. return MD;
  6148. return {};
  6149. }
  6150. /// A base or member subobject.
  6151. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  6152. /// Get the location to use for a subobject in diagnostics.
  6153. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  6154. // FIXME: For an indirect virtual base, the direct base leading to
  6155. // the indirect virtual base would be a more useful choice.
  6156. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  6157. return B->getBaseTypeLoc();
  6158. else
  6159. return Subobj.get<FieldDecl*>()->getLocation();
  6160. }
  6161. enum BasesToVisit {
  6162. /// Visit all non-virtual (direct) bases.
  6163. VisitNonVirtualBases,
  6164. /// Visit all direct bases, virtual or not.
  6165. VisitDirectBases,
  6166. /// Visit all non-virtual bases, and all virtual bases if the class
  6167. /// is not abstract.
  6168. VisitPotentiallyConstructedBases,
  6169. /// Visit all direct or virtual bases.
  6170. VisitAllBases
  6171. };
  6172. // Visit the bases and members of the class.
  6173. bool visit(BasesToVisit Bases) {
  6174. CXXRecordDecl *RD = MD->getParent();
  6175. if (Bases == VisitPotentiallyConstructedBases)
  6176. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  6177. for (auto &B : RD->bases())
  6178. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  6179. getDerived().visitBase(&B))
  6180. return true;
  6181. if (Bases == VisitAllBases)
  6182. for (auto &B : RD->vbases())
  6183. if (getDerived().visitBase(&B))
  6184. return true;
  6185. for (auto *F : RD->fields())
  6186. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  6187. getDerived().visitField(F))
  6188. return true;
  6189. return false;
  6190. }
  6191. };
  6192. }
  6193. namespace {
  6194. struct SpecialMemberDeletionInfo
  6195. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  6196. bool Diagnose;
  6197. SourceLocation Loc;
  6198. bool AllFieldsAreConst;
  6199. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  6200. Sema::CXXSpecialMember CSM,
  6201. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  6202. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  6203. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  6204. bool inUnion() const { return MD->getParent()->isUnion(); }
  6205. Sema::CXXSpecialMember getEffectiveCSM() {
  6206. return ICI ? Sema::CXXInvalid : CSM;
  6207. }
  6208. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  6209. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  6210. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  6211. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  6212. bool shouldDeleteForField(FieldDecl *FD);
  6213. bool shouldDeleteForAllConstMembers();
  6214. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  6215. unsigned Quals);
  6216. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  6217. Sema::SpecialMemberOverloadResult SMOR,
  6218. bool IsDtorCallInCtor);
  6219. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  6220. };
  6221. }
  6222. /// Is the given special member inaccessible when used on the given
  6223. /// sub-object.
  6224. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  6225. CXXMethodDecl *target) {
  6226. /// If we're operating on a base class, the object type is the
  6227. /// type of this special member.
  6228. QualType objectTy;
  6229. AccessSpecifier access = target->getAccess();
  6230. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  6231. objectTy = S.Context.getTypeDeclType(MD->getParent());
  6232. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  6233. // If we're operating on a field, the object type is the type of the field.
  6234. } else {
  6235. objectTy = S.Context.getTypeDeclType(target->getParent());
  6236. }
  6237. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  6238. }
  6239. /// Check whether we should delete a special member due to the implicit
  6240. /// definition containing a call to a special member of a subobject.
  6241. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  6242. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  6243. bool IsDtorCallInCtor) {
  6244. CXXMethodDecl *Decl = SMOR.getMethod();
  6245. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6246. int DiagKind = -1;
  6247. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  6248. DiagKind = !Decl ? 0 : 1;
  6249. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6250. DiagKind = 2;
  6251. else if (!isAccessible(Subobj, Decl))
  6252. DiagKind = 3;
  6253. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  6254. !Decl->isTrivial()) {
  6255. // A member of a union must have a trivial corresponding special member.
  6256. // As a weird special case, a destructor call from a union's constructor
  6257. // must be accessible and non-deleted, but need not be trivial. Such a
  6258. // destructor is never actually called, but is semantically checked as
  6259. // if it were.
  6260. DiagKind = 4;
  6261. }
  6262. if (DiagKind == -1)
  6263. return false;
  6264. if (Diagnose) {
  6265. if (Field) {
  6266. S.Diag(Field->getLocation(),
  6267. diag::note_deleted_special_member_class_subobject)
  6268. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  6269. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  6270. } else {
  6271. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  6272. S.Diag(Base->getBeginLoc(),
  6273. diag::note_deleted_special_member_class_subobject)
  6274. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6275. << Base->getType() << DiagKind << IsDtorCallInCtor
  6276. << /*IsObjCPtr*/false;
  6277. }
  6278. if (DiagKind == 1)
  6279. S.NoteDeletedFunction(Decl);
  6280. // FIXME: Explain inaccessibility if DiagKind == 3.
  6281. }
  6282. return true;
  6283. }
  6284. /// Check whether we should delete a special member function due to having a
  6285. /// direct or virtual base class or non-static data member of class type M.
  6286. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  6287. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  6288. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6289. bool IsMutable = Field && Field->isMutable();
  6290. // C++11 [class.ctor]p5:
  6291. // -- any direct or virtual base class, or non-static data member with no
  6292. // brace-or-equal-initializer, has class type M (or array thereof) and
  6293. // either M has no default constructor or overload resolution as applied
  6294. // to M's default constructor results in an ambiguity or in a function
  6295. // that is deleted or inaccessible
  6296. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6297. // -- a direct or virtual base class B that cannot be copied/moved because
  6298. // overload resolution, as applied to B's corresponding special member,
  6299. // results in an ambiguity or a function that is deleted or inaccessible
  6300. // from the defaulted special member
  6301. // C++11 [class.dtor]p5:
  6302. // -- any direct or virtual base class [...] has a type with a destructor
  6303. // that is deleted or inaccessible
  6304. if (!(CSM == Sema::CXXDefaultConstructor &&
  6305. Field && Field->hasInClassInitializer()) &&
  6306. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6307. false))
  6308. return true;
  6309. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6310. // -- any direct or virtual base class or non-static data member has a
  6311. // type with a destructor that is deleted or inaccessible
  6312. if (IsConstructor) {
  6313. Sema::SpecialMemberOverloadResult SMOR =
  6314. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6315. false, false, false, false, false);
  6316. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6317. return true;
  6318. }
  6319. return false;
  6320. }
  6321. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  6322. FieldDecl *FD, QualType FieldType) {
  6323. // The defaulted special functions are defined as deleted if this is a variant
  6324. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  6325. // type under ARC.
  6326. if (!FieldType.hasNonTrivialObjCLifetime())
  6327. return false;
  6328. // Don't make the defaulted default constructor defined as deleted if the
  6329. // member has an in-class initializer.
  6330. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  6331. return false;
  6332. if (Diagnose) {
  6333. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  6334. S.Diag(FD->getLocation(),
  6335. diag::note_deleted_special_member_class_subobject)
  6336. << getEffectiveCSM() << ParentClass << /*IsField*/true
  6337. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  6338. }
  6339. return true;
  6340. }
  6341. /// Check whether we should delete a special member function due to the class
  6342. /// having a particular direct or virtual base class.
  6343. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6344. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6345. // If program is correct, BaseClass cannot be null, but if it is, the error
  6346. // must be reported elsewhere.
  6347. if (!BaseClass)
  6348. return false;
  6349. // If we have an inheriting constructor, check whether we're calling an
  6350. // inherited constructor instead of a default constructor.
  6351. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6352. if (auto *BaseCtor = SMOR.getMethod()) {
  6353. // Note that we do not check access along this path; other than that,
  6354. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6355. // FIXME: Check that the base has a usable destructor! Sink this into
  6356. // shouldDeleteForClassSubobject.
  6357. if (BaseCtor->isDeleted() && Diagnose) {
  6358. S.Diag(Base->getBeginLoc(),
  6359. diag::note_deleted_special_member_class_subobject)
  6360. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6361. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  6362. << /*IsObjCPtr*/false;
  6363. S.NoteDeletedFunction(BaseCtor);
  6364. }
  6365. return BaseCtor->isDeleted();
  6366. }
  6367. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6368. }
  6369. /// Check whether we should delete a special member function due to the class
  6370. /// having a particular non-static data member.
  6371. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6372. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6373. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6374. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  6375. return true;
  6376. if (CSM == Sema::CXXDefaultConstructor) {
  6377. // For a default constructor, all references must be initialized in-class
  6378. // and, if a union, it must have a non-const member.
  6379. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6380. if (Diagnose)
  6381. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6382. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6383. return true;
  6384. }
  6385. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6386. // const-qualified type (or array thereof) with no
  6387. // brace-or-equal-initializer does not have a user-provided default
  6388. // constructor.
  6389. if (!inUnion() && FieldType.isConstQualified() &&
  6390. !FD->hasInClassInitializer() &&
  6391. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6392. if (Diagnose)
  6393. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6394. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6395. return true;
  6396. }
  6397. if (inUnion() && !FieldType.isConstQualified())
  6398. AllFieldsAreConst = false;
  6399. } else if (CSM == Sema::CXXCopyConstructor) {
  6400. // For a copy constructor, data members must not be of rvalue reference
  6401. // type.
  6402. if (FieldType->isRValueReferenceType()) {
  6403. if (Diagnose)
  6404. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6405. << MD->getParent() << FD << FieldType;
  6406. return true;
  6407. }
  6408. } else if (IsAssignment) {
  6409. // For an assignment operator, data members must not be of reference type.
  6410. if (FieldType->isReferenceType()) {
  6411. if (Diagnose)
  6412. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6413. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6414. return true;
  6415. }
  6416. if (!FieldRecord && FieldType.isConstQualified()) {
  6417. // C++11 [class.copy]p23:
  6418. // -- a non-static data member of const non-class type (or array thereof)
  6419. if (Diagnose)
  6420. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6421. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6422. return true;
  6423. }
  6424. }
  6425. if (FieldRecord) {
  6426. // Some additional restrictions exist on the variant members.
  6427. if (!inUnion() && FieldRecord->isUnion() &&
  6428. FieldRecord->isAnonymousStructOrUnion()) {
  6429. bool AllVariantFieldsAreConst = true;
  6430. // FIXME: Handle anonymous unions declared within anonymous unions.
  6431. for (auto *UI : FieldRecord->fields()) {
  6432. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6433. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  6434. return true;
  6435. if (!UnionFieldType.isConstQualified())
  6436. AllVariantFieldsAreConst = false;
  6437. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6438. if (UnionFieldRecord &&
  6439. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6440. UnionFieldType.getCVRQualifiers()))
  6441. return true;
  6442. }
  6443. // At least one member in each anonymous union must be non-const
  6444. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6445. !FieldRecord->field_empty()) {
  6446. if (Diagnose)
  6447. S.Diag(FieldRecord->getLocation(),
  6448. diag::note_deleted_default_ctor_all_const)
  6449. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6450. return true;
  6451. }
  6452. // Don't check the implicit member of the anonymous union type.
  6453. // This is technically non-conformant, but sanity demands it.
  6454. return false;
  6455. }
  6456. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6457. FieldType.getCVRQualifiers()))
  6458. return true;
  6459. }
  6460. return false;
  6461. }
  6462. /// C++11 [class.ctor] p5:
  6463. /// A defaulted default constructor for a class X is defined as deleted if
  6464. /// X is a union and all of its variant members are of const-qualified type.
  6465. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6466. // This is a silly definition, because it gives an empty union a deleted
  6467. // default constructor. Don't do that.
  6468. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6469. bool AnyFields = false;
  6470. for (auto *F : MD->getParent()->fields())
  6471. if ((AnyFields = !F->isUnnamedBitfield()))
  6472. break;
  6473. if (!AnyFields)
  6474. return false;
  6475. if (Diagnose)
  6476. S.Diag(MD->getParent()->getLocation(),
  6477. diag::note_deleted_default_ctor_all_const)
  6478. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6479. return true;
  6480. }
  6481. return false;
  6482. }
  6483. /// Determine whether a defaulted special member function should be defined as
  6484. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6485. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6486. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6487. InheritedConstructorInfo *ICI,
  6488. bool Diagnose) {
  6489. if (MD->isInvalidDecl())
  6490. return false;
  6491. CXXRecordDecl *RD = MD->getParent();
  6492. assert(!RD->isDependentType() && "do deletion after instantiation");
  6493. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6494. return false;
  6495. // C++11 [expr.lambda.prim]p19:
  6496. // The closure type associated with a lambda-expression has a
  6497. // deleted (8.4.3) default constructor and a deleted copy
  6498. // assignment operator.
  6499. // C++2a adds back these operators if the lambda has no lambda-capture.
  6500. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  6501. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6502. if (Diagnose)
  6503. Diag(RD->getLocation(), diag::note_lambda_decl);
  6504. return true;
  6505. }
  6506. // For an anonymous struct or union, the copy and assignment special members
  6507. // will never be used, so skip the check. For an anonymous union declared at
  6508. // namespace scope, the constructor and destructor are used.
  6509. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6510. RD->isAnonymousStructOrUnion())
  6511. return false;
  6512. // C++11 [class.copy]p7, p18:
  6513. // If the class definition declares a move constructor or move assignment
  6514. // operator, an implicitly declared copy constructor or copy assignment
  6515. // operator is defined as deleted.
  6516. if (MD->isImplicit() &&
  6517. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6518. CXXMethodDecl *UserDeclaredMove = nullptr;
  6519. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6520. // deletion of the corresponding copy operation, not both copy operations.
  6521. // MSVC 2015 has adopted the standards conforming behavior.
  6522. bool DeletesOnlyMatchingCopy =
  6523. getLangOpts().MSVCCompat &&
  6524. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6525. if (RD->hasUserDeclaredMoveConstructor() &&
  6526. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6527. if (!Diagnose) return true;
  6528. // Find any user-declared move constructor.
  6529. for (auto *I : RD->ctors()) {
  6530. if (I->isMoveConstructor()) {
  6531. UserDeclaredMove = I;
  6532. break;
  6533. }
  6534. }
  6535. assert(UserDeclaredMove);
  6536. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6537. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6538. if (!Diagnose) return true;
  6539. // Find any user-declared move assignment operator.
  6540. for (auto *I : RD->methods()) {
  6541. if (I->isMoveAssignmentOperator()) {
  6542. UserDeclaredMove = I;
  6543. break;
  6544. }
  6545. }
  6546. assert(UserDeclaredMove);
  6547. }
  6548. if (UserDeclaredMove) {
  6549. Diag(UserDeclaredMove->getLocation(),
  6550. diag::note_deleted_copy_user_declared_move)
  6551. << (CSM == CXXCopyAssignment) << RD
  6552. << UserDeclaredMove->isMoveAssignmentOperator();
  6553. return true;
  6554. }
  6555. }
  6556. // Do access control from the special member function
  6557. ContextRAII MethodContext(*this, MD);
  6558. // C++11 [class.dtor]p5:
  6559. // -- for a virtual destructor, lookup of the non-array deallocation function
  6560. // results in an ambiguity or in a function that is deleted or inaccessible
  6561. if (CSM == CXXDestructor && MD->isVirtual()) {
  6562. FunctionDecl *OperatorDelete = nullptr;
  6563. DeclarationName Name =
  6564. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6565. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6566. OperatorDelete, /*Diagnose*/false)) {
  6567. if (Diagnose)
  6568. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6569. return true;
  6570. }
  6571. }
  6572. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6573. // Per DR1611, do not consider virtual bases of constructors of abstract
  6574. // classes, since we are not going to construct them.
  6575. // Per DR1658, do not consider virtual bases of destructors of abstract
  6576. // classes either.
  6577. // Per DR2180, for assignment operators we only assign (and thus only
  6578. // consider) direct bases.
  6579. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6580. : SMI.VisitPotentiallyConstructedBases))
  6581. return true;
  6582. if (SMI.shouldDeleteForAllConstMembers())
  6583. return true;
  6584. if (getLangOpts().CUDA) {
  6585. // We should delete the special member in CUDA mode if target inference
  6586. // failed.
  6587. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  6588. // is treated as certain special member, which may not reflect what special
  6589. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  6590. // expects CSM to match MD, therefore recalculate CSM.
  6591. assert(ICI || CSM == getSpecialMember(MD));
  6592. auto RealCSM = CSM;
  6593. if (ICI)
  6594. RealCSM = getSpecialMember(MD);
  6595. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  6596. SMI.ConstArg, Diagnose);
  6597. }
  6598. return false;
  6599. }
  6600. /// Perform lookup for a special member of the specified kind, and determine
  6601. /// whether it is trivial. If the triviality can be determined without the
  6602. /// lookup, skip it. This is intended for use when determining whether a
  6603. /// special member of a containing object is trivial, and thus does not ever
  6604. /// perform overload resolution for default constructors.
  6605. ///
  6606. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6607. /// member that was most likely to be intended to be trivial, if any.
  6608. ///
  6609. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6610. /// determine whether the special member is trivial.
  6611. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6612. Sema::CXXSpecialMember CSM, unsigned Quals,
  6613. bool ConstRHS,
  6614. Sema::TrivialABIHandling TAH,
  6615. CXXMethodDecl **Selected) {
  6616. if (Selected)
  6617. *Selected = nullptr;
  6618. switch (CSM) {
  6619. case Sema::CXXInvalid:
  6620. llvm_unreachable("not a special member");
  6621. case Sema::CXXDefaultConstructor:
  6622. // C++11 [class.ctor]p5:
  6623. // A default constructor is trivial if:
  6624. // - all the [direct subobjects] have trivial default constructors
  6625. //
  6626. // Note, no overload resolution is performed in this case.
  6627. if (RD->hasTrivialDefaultConstructor())
  6628. return true;
  6629. if (Selected) {
  6630. // If there's a default constructor which could have been trivial, dig it
  6631. // out. Otherwise, if there's any user-provided default constructor, point
  6632. // to that as an example of why there's not a trivial one.
  6633. CXXConstructorDecl *DefCtor = nullptr;
  6634. if (RD->needsImplicitDefaultConstructor())
  6635. S.DeclareImplicitDefaultConstructor(RD);
  6636. for (auto *CI : RD->ctors()) {
  6637. if (!CI->isDefaultConstructor())
  6638. continue;
  6639. DefCtor = CI;
  6640. if (!DefCtor->isUserProvided())
  6641. break;
  6642. }
  6643. *Selected = DefCtor;
  6644. }
  6645. return false;
  6646. case Sema::CXXDestructor:
  6647. // C++11 [class.dtor]p5:
  6648. // A destructor is trivial if:
  6649. // - all the direct [subobjects] have trivial destructors
  6650. if (RD->hasTrivialDestructor() ||
  6651. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6652. RD->hasTrivialDestructorForCall()))
  6653. return true;
  6654. if (Selected) {
  6655. if (RD->needsImplicitDestructor())
  6656. S.DeclareImplicitDestructor(RD);
  6657. *Selected = RD->getDestructor();
  6658. }
  6659. return false;
  6660. case Sema::CXXCopyConstructor:
  6661. // C++11 [class.copy]p12:
  6662. // A copy constructor is trivial if:
  6663. // - the constructor selected to copy each direct [subobject] is trivial
  6664. if (RD->hasTrivialCopyConstructor() ||
  6665. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6666. RD->hasTrivialCopyConstructorForCall())) {
  6667. if (Quals == Qualifiers::Const)
  6668. // We must either select the trivial copy constructor or reach an
  6669. // ambiguity; no need to actually perform overload resolution.
  6670. return true;
  6671. } else if (!Selected) {
  6672. return false;
  6673. }
  6674. // In C++98, we are not supposed to perform overload resolution here, but we
  6675. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6676. // cases like B as having a non-trivial copy constructor:
  6677. // struct A { template<typename T> A(T&); };
  6678. // struct B { mutable A a; };
  6679. goto NeedOverloadResolution;
  6680. case Sema::CXXCopyAssignment:
  6681. // C++11 [class.copy]p25:
  6682. // A copy assignment operator is trivial if:
  6683. // - the assignment operator selected to copy each direct [subobject] is
  6684. // trivial
  6685. if (RD->hasTrivialCopyAssignment()) {
  6686. if (Quals == Qualifiers::Const)
  6687. return true;
  6688. } else if (!Selected) {
  6689. return false;
  6690. }
  6691. // In C++98, we are not supposed to perform overload resolution here, but we
  6692. // treat that as a language defect.
  6693. goto NeedOverloadResolution;
  6694. case Sema::CXXMoveConstructor:
  6695. case Sema::CXXMoveAssignment:
  6696. NeedOverloadResolution:
  6697. Sema::SpecialMemberOverloadResult SMOR =
  6698. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6699. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6700. // We treat it as not making the member non-trivial, just like the standard
  6701. // mandates for the default constructor. This should rarely matter, because
  6702. // the member will also be deleted.
  6703. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6704. return true;
  6705. if (!SMOR.getMethod()) {
  6706. assert(SMOR.getKind() ==
  6707. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6708. return false;
  6709. }
  6710. // We deliberately don't check if we found a deleted special member. We're
  6711. // not supposed to!
  6712. if (Selected)
  6713. *Selected = SMOR.getMethod();
  6714. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6715. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6716. return SMOR.getMethod()->isTrivialForCall();
  6717. return SMOR.getMethod()->isTrivial();
  6718. }
  6719. llvm_unreachable("unknown special method kind");
  6720. }
  6721. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6722. for (auto *CI : RD->ctors())
  6723. if (!CI->isImplicit())
  6724. return CI;
  6725. // Look for constructor templates.
  6726. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6727. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6728. if (CXXConstructorDecl *CD =
  6729. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6730. return CD;
  6731. }
  6732. return nullptr;
  6733. }
  6734. /// The kind of subobject we are checking for triviality. The values of this
  6735. /// enumeration are used in diagnostics.
  6736. enum TrivialSubobjectKind {
  6737. /// The subobject is a base class.
  6738. TSK_BaseClass,
  6739. /// The subobject is a non-static data member.
  6740. TSK_Field,
  6741. /// The object is actually the complete object.
  6742. TSK_CompleteObject
  6743. };
  6744. /// Check whether the special member selected for a given type would be trivial.
  6745. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6746. QualType SubType, bool ConstRHS,
  6747. Sema::CXXSpecialMember CSM,
  6748. TrivialSubobjectKind Kind,
  6749. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6750. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6751. if (!SubRD)
  6752. return true;
  6753. CXXMethodDecl *Selected;
  6754. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6755. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6756. return true;
  6757. if (Diagnose) {
  6758. if (ConstRHS)
  6759. SubType.addConst();
  6760. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6761. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6762. << Kind << SubType.getUnqualifiedType();
  6763. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6764. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6765. } else if (!Selected)
  6766. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6767. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6768. else if (Selected->isUserProvided()) {
  6769. if (Kind == TSK_CompleteObject)
  6770. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6771. << Kind << SubType.getUnqualifiedType() << CSM;
  6772. else {
  6773. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6774. << Kind << SubType.getUnqualifiedType() << CSM;
  6775. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6776. }
  6777. } else {
  6778. if (Kind != TSK_CompleteObject)
  6779. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6780. << Kind << SubType.getUnqualifiedType() << CSM;
  6781. // Explain why the defaulted or deleted special member isn't trivial.
  6782. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6783. Diagnose);
  6784. }
  6785. }
  6786. return false;
  6787. }
  6788. /// Check whether the members of a class type allow a special member to be
  6789. /// trivial.
  6790. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6791. Sema::CXXSpecialMember CSM,
  6792. bool ConstArg,
  6793. Sema::TrivialABIHandling TAH,
  6794. bool Diagnose) {
  6795. for (const auto *FI : RD->fields()) {
  6796. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6797. continue;
  6798. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6799. // Pretend anonymous struct or union members are members of this class.
  6800. if (FI->isAnonymousStructOrUnion()) {
  6801. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6802. CSM, ConstArg, TAH, Diagnose))
  6803. return false;
  6804. continue;
  6805. }
  6806. // C++11 [class.ctor]p5:
  6807. // A default constructor is trivial if [...]
  6808. // -- no non-static data member of its class has a
  6809. // brace-or-equal-initializer
  6810. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6811. if (Diagnose)
  6812. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6813. return false;
  6814. }
  6815. // Objective C ARC 4.3.5:
  6816. // [...] nontrivally ownership-qualified types are [...] not trivially
  6817. // default constructible, copy constructible, move constructible, copy
  6818. // assignable, move assignable, or destructible [...]
  6819. if (FieldType.hasNonTrivialObjCLifetime()) {
  6820. if (Diagnose)
  6821. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6822. << RD << FieldType.getObjCLifetime();
  6823. return false;
  6824. }
  6825. bool ConstRHS = ConstArg && !FI->isMutable();
  6826. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6827. CSM, TSK_Field, TAH, Diagnose))
  6828. return false;
  6829. }
  6830. return true;
  6831. }
  6832. /// Diagnose why the specified class does not have a trivial special member of
  6833. /// the given kind.
  6834. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6835. QualType Ty = Context.getRecordType(RD);
  6836. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6837. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6838. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6839. /*Diagnose*/true);
  6840. }
  6841. /// Determine whether a defaulted or deleted special member function is trivial,
  6842. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6843. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6844. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6845. TrivialABIHandling TAH, bool Diagnose) {
  6846. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6847. CXXRecordDecl *RD = MD->getParent();
  6848. bool ConstArg = false;
  6849. // C++11 [class.copy]p12, p25: [DR1593]
  6850. // A [special member] is trivial if [...] its parameter-type-list is
  6851. // equivalent to the parameter-type-list of an implicit declaration [...]
  6852. switch (CSM) {
  6853. case CXXDefaultConstructor:
  6854. case CXXDestructor:
  6855. // Trivial default constructors and destructors cannot have parameters.
  6856. break;
  6857. case CXXCopyConstructor:
  6858. case CXXCopyAssignment: {
  6859. // Trivial copy operations always have const, non-volatile parameter types.
  6860. ConstArg = true;
  6861. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6862. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6863. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6864. if (Diagnose)
  6865. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6866. << Param0->getSourceRange() << Param0->getType()
  6867. << Context.getLValueReferenceType(
  6868. Context.getRecordType(RD).withConst());
  6869. return false;
  6870. }
  6871. break;
  6872. }
  6873. case CXXMoveConstructor:
  6874. case CXXMoveAssignment: {
  6875. // Trivial move operations always have non-cv-qualified parameters.
  6876. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6877. const RValueReferenceType *RT =
  6878. Param0->getType()->getAs<RValueReferenceType>();
  6879. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6880. if (Diagnose)
  6881. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6882. << Param0->getSourceRange() << Param0->getType()
  6883. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6884. return false;
  6885. }
  6886. break;
  6887. }
  6888. case CXXInvalid:
  6889. llvm_unreachable("not a special member");
  6890. }
  6891. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6892. if (Diagnose)
  6893. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6894. diag::note_nontrivial_default_arg)
  6895. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6896. return false;
  6897. }
  6898. if (MD->isVariadic()) {
  6899. if (Diagnose)
  6900. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6901. return false;
  6902. }
  6903. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6904. // A copy/move [constructor or assignment operator] is trivial if
  6905. // -- the [member] selected to copy/move each direct base class subobject
  6906. // is trivial
  6907. //
  6908. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6909. // A [default constructor or destructor] is trivial if
  6910. // -- all the direct base classes have trivial [default constructors or
  6911. // destructors]
  6912. for (const auto &BI : RD->bases())
  6913. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6914. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6915. return false;
  6916. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6917. // A copy/move [constructor or assignment operator] for a class X is
  6918. // trivial if
  6919. // -- for each non-static data member of X that is of class type (or array
  6920. // thereof), the constructor selected to copy/move that member is
  6921. // trivial
  6922. //
  6923. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6924. // A [default constructor or destructor] is trivial if
  6925. // -- for all of the non-static data members of its class that are of class
  6926. // type (or array thereof), each such class has a trivial [default
  6927. // constructor or destructor]
  6928. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6929. return false;
  6930. // C++11 [class.dtor]p5:
  6931. // A destructor is trivial if [...]
  6932. // -- the destructor is not virtual
  6933. if (CSM == CXXDestructor && MD->isVirtual()) {
  6934. if (Diagnose)
  6935. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6936. return false;
  6937. }
  6938. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6939. // A [special member] for class X is trivial if [...]
  6940. // -- class X has no virtual functions and no virtual base classes
  6941. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6942. if (!Diagnose)
  6943. return false;
  6944. if (RD->getNumVBases()) {
  6945. // Check for virtual bases. We already know that the corresponding
  6946. // member in all bases is trivial, so vbases must all be direct.
  6947. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6948. assert(BS.isVirtual());
  6949. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6950. return false;
  6951. }
  6952. // Must have a virtual method.
  6953. for (const auto *MI : RD->methods()) {
  6954. if (MI->isVirtual()) {
  6955. SourceLocation MLoc = MI->getBeginLoc();
  6956. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6957. return false;
  6958. }
  6959. }
  6960. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6961. }
  6962. // Looks like it's trivial!
  6963. return true;
  6964. }
  6965. namespace {
  6966. struct FindHiddenVirtualMethod {
  6967. Sema *S;
  6968. CXXMethodDecl *Method;
  6969. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6970. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6971. private:
  6972. /// Check whether any most overridden method from MD in Methods
  6973. static bool CheckMostOverridenMethods(
  6974. const CXXMethodDecl *MD,
  6975. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6976. if (MD->size_overridden_methods() == 0)
  6977. return Methods.count(MD->getCanonicalDecl());
  6978. for (const CXXMethodDecl *O : MD->overridden_methods())
  6979. if (CheckMostOverridenMethods(O, Methods))
  6980. return true;
  6981. return false;
  6982. }
  6983. public:
  6984. /// Member lookup function that determines whether a given C++
  6985. /// method overloads virtual methods in a base class without overriding any,
  6986. /// to be used with CXXRecordDecl::lookupInBases().
  6987. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6988. RecordDecl *BaseRecord =
  6989. Specifier->getType()->castAs<RecordType>()->getDecl();
  6990. DeclarationName Name = Method->getDeclName();
  6991. assert(Name.getNameKind() == DeclarationName::Identifier);
  6992. bool foundSameNameMethod = false;
  6993. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6994. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6995. Path.Decls = Path.Decls.slice(1)) {
  6996. NamedDecl *D = Path.Decls.front();
  6997. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6998. MD = MD->getCanonicalDecl();
  6999. foundSameNameMethod = true;
  7000. // Interested only in hidden virtual methods.
  7001. if (!MD->isVirtual())
  7002. continue;
  7003. // If the method we are checking overrides a method from its base
  7004. // don't warn about the other overloaded methods. Clang deviates from
  7005. // GCC by only diagnosing overloads of inherited virtual functions that
  7006. // do not override any other virtual functions in the base. GCC's
  7007. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  7008. // function from a base class. These cases may be better served by a
  7009. // warning (not specific to virtual functions) on call sites when the
  7010. // call would select a different function from the base class, were it
  7011. // visible.
  7012. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  7013. if (!S->IsOverload(Method, MD, false))
  7014. return true;
  7015. // Collect the overload only if its hidden.
  7016. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  7017. overloadedMethods.push_back(MD);
  7018. }
  7019. }
  7020. if (foundSameNameMethod)
  7021. OverloadedMethods.append(overloadedMethods.begin(),
  7022. overloadedMethods.end());
  7023. return foundSameNameMethod;
  7024. }
  7025. };
  7026. } // end anonymous namespace
  7027. /// Add the most overriden methods from MD to Methods
  7028. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  7029. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  7030. if (MD->size_overridden_methods() == 0)
  7031. Methods.insert(MD->getCanonicalDecl());
  7032. else
  7033. for (const CXXMethodDecl *O : MD->overridden_methods())
  7034. AddMostOverridenMethods(O, Methods);
  7035. }
  7036. /// Check if a method overloads virtual methods in a base class without
  7037. /// overriding any.
  7038. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  7039. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  7040. if (!MD->getDeclName().isIdentifier())
  7041. return;
  7042. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  7043. /*bool RecordPaths=*/false,
  7044. /*bool DetectVirtual=*/false);
  7045. FindHiddenVirtualMethod FHVM;
  7046. FHVM.Method = MD;
  7047. FHVM.S = this;
  7048. // Keep the base methods that were overridden or introduced in the subclass
  7049. // by 'using' in a set. A base method not in this set is hidden.
  7050. CXXRecordDecl *DC = MD->getParent();
  7051. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  7052. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7053. NamedDecl *ND = *I;
  7054. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  7055. ND = shad->getTargetDecl();
  7056. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  7057. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  7058. }
  7059. if (DC->lookupInBases(FHVM, Paths))
  7060. OverloadedMethods = FHVM.OverloadedMethods;
  7061. }
  7062. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  7063. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  7064. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  7065. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  7066. PartialDiagnostic PD = PDiag(
  7067. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  7068. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  7069. Diag(overloadedMD->getLocation(), PD);
  7070. }
  7071. }
  7072. /// Diagnose methods which overload virtual methods in a base class
  7073. /// without overriding any.
  7074. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  7075. if (MD->isInvalidDecl())
  7076. return;
  7077. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  7078. return;
  7079. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  7080. FindHiddenVirtualMethods(MD, OverloadedMethods);
  7081. if (!OverloadedMethods.empty()) {
  7082. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  7083. << MD << (OverloadedMethods.size() > 1);
  7084. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  7085. }
  7086. }
  7087. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  7088. auto PrintDiagAndRemoveAttr = [&]() {
  7089. // No diagnostics if this is a template instantiation.
  7090. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  7091. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  7092. diag::ext_cannot_use_trivial_abi) << &RD;
  7093. RD.dropAttr<TrivialABIAttr>();
  7094. };
  7095. // Ill-formed if the struct has virtual functions.
  7096. if (RD.isPolymorphic()) {
  7097. PrintDiagAndRemoveAttr();
  7098. return;
  7099. }
  7100. for (const auto &B : RD.bases()) {
  7101. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  7102. // virtual base.
  7103. if ((!B.getType()->isDependentType() &&
  7104. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  7105. B.isVirtual()) {
  7106. PrintDiagAndRemoveAttr();
  7107. return;
  7108. }
  7109. }
  7110. for (const auto *FD : RD.fields()) {
  7111. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  7112. // non-trivial for the purpose of calls.
  7113. QualType FT = FD->getType();
  7114. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  7115. PrintDiagAndRemoveAttr();
  7116. return;
  7117. }
  7118. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  7119. if (!RT->isDependentType() &&
  7120. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  7121. PrintDiagAndRemoveAttr();
  7122. return;
  7123. }
  7124. }
  7125. }
  7126. void Sema::ActOnFinishCXXMemberSpecification(
  7127. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  7128. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  7129. if (!TagDecl)
  7130. return;
  7131. AdjustDeclIfTemplate(TagDecl);
  7132. for (const ParsedAttr &AL : AttrList) {
  7133. if (AL.getKind() != ParsedAttr::AT_Visibility)
  7134. continue;
  7135. AL.setInvalid();
  7136. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
  7137. }
  7138. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  7139. // strict aliasing violation!
  7140. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  7141. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  7142. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  7143. }
  7144. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  7145. /// special functions, such as the default constructor, copy
  7146. /// constructor, or destructor, to the given C++ class (C++
  7147. /// [special]p1). This routine can only be executed just before the
  7148. /// definition of the class is complete.
  7149. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  7150. if (ClassDecl->needsImplicitDefaultConstructor()) {
  7151. ++getASTContext().NumImplicitDefaultConstructors;
  7152. if (ClassDecl->hasInheritedConstructor())
  7153. DeclareImplicitDefaultConstructor(ClassDecl);
  7154. }
  7155. if (ClassDecl->needsImplicitCopyConstructor()) {
  7156. ++getASTContext().NumImplicitCopyConstructors;
  7157. // If the properties or semantics of the copy constructor couldn't be
  7158. // determined while the class was being declared, force a declaration
  7159. // of it now.
  7160. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  7161. ClassDecl->hasInheritedConstructor())
  7162. DeclareImplicitCopyConstructor(ClassDecl);
  7163. // For the MS ABI we need to know whether the copy ctor is deleted. A
  7164. // prerequisite for deleting the implicit copy ctor is that the class has a
  7165. // move ctor or move assignment that is either user-declared or whose
  7166. // semantics are inherited from a subobject. FIXME: We should provide a more
  7167. // direct way for CodeGen to ask whether the constructor was deleted.
  7168. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  7169. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  7170. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7171. ClassDecl->hasUserDeclaredMoveAssignment() ||
  7172. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  7173. DeclareImplicitCopyConstructor(ClassDecl);
  7174. }
  7175. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  7176. ++getASTContext().NumImplicitMoveConstructors;
  7177. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7178. ClassDecl->hasInheritedConstructor())
  7179. DeclareImplicitMoveConstructor(ClassDecl);
  7180. }
  7181. if (ClassDecl->needsImplicitCopyAssignment()) {
  7182. ++getASTContext().NumImplicitCopyAssignmentOperators;
  7183. // If we have a dynamic class, then the copy assignment operator may be
  7184. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  7185. // it shows up in the right place in the vtable and that we diagnose
  7186. // problems with the implicit exception specification.
  7187. if (ClassDecl->isDynamicClass() ||
  7188. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  7189. ClassDecl->hasInheritedAssignment())
  7190. DeclareImplicitCopyAssignment(ClassDecl);
  7191. }
  7192. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  7193. ++getASTContext().NumImplicitMoveAssignmentOperators;
  7194. // Likewise for the move assignment operator.
  7195. if (ClassDecl->isDynamicClass() ||
  7196. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  7197. ClassDecl->hasInheritedAssignment())
  7198. DeclareImplicitMoveAssignment(ClassDecl);
  7199. }
  7200. if (ClassDecl->needsImplicitDestructor()) {
  7201. ++getASTContext().NumImplicitDestructors;
  7202. // If we have a dynamic class, then the destructor may be virtual, so we
  7203. // have to declare the destructor immediately. This ensures that, e.g., it
  7204. // shows up in the right place in the vtable and that we diagnose problems
  7205. // with the implicit exception specification.
  7206. if (ClassDecl->isDynamicClass() ||
  7207. ClassDecl->needsOverloadResolutionForDestructor())
  7208. DeclareImplicitDestructor(ClassDecl);
  7209. }
  7210. }
  7211. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  7212. if (!D)
  7213. return 0;
  7214. // The order of template parameters is not important here. All names
  7215. // get added to the same scope.
  7216. SmallVector<TemplateParameterList *, 4> ParameterLists;
  7217. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  7218. D = TD->getTemplatedDecl();
  7219. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  7220. ParameterLists.push_back(PSD->getTemplateParameters());
  7221. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  7222. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  7223. ParameterLists.push_back(DD->getTemplateParameterList(i));
  7224. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7225. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  7226. ParameterLists.push_back(FTD->getTemplateParameters());
  7227. }
  7228. }
  7229. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7230. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  7231. ParameterLists.push_back(TD->getTemplateParameterList(i));
  7232. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  7233. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  7234. ParameterLists.push_back(CTD->getTemplateParameters());
  7235. }
  7236. }
  7237. unsigned Count = 0;
  7238. for (TemplateParameterList *Params : ParameterLists) {
  7239. if (Params->size() > 0)
  7240. // Ignore explicit specializations; they don't contribute to the template
  7241. // depth.
  7242. ++Count;
  7243. for (NamedDecl *Param : *Params) {
  7244. if (Param->getDeclName()) {
  7245. S->AddDecl(Param);
  7246. IdResolver.AddDecl(Param);
  7247. }
  7248. }
  7249. }
  7250. return Count;
  7251. }
  7252. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7253. if (!RecordD) return;
  7254. AdjustDeclIfTemplate(RecordD);
  7255. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  7256. PushDeclContext(S, Record);
  7257. }
  7258. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7259. if (!RecordD) return;
  7260. PopDeclContext();
  7261. }
  7262. /// This is used to implement the constant expression evaluation part of the
  7263. /// attribute enable_if extension. There is nothing in standard C++ which would
  7264. /// require reentering parameters.
  7265. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  7266. if (!Param)
  7267. return;
  7268. S->AddDecl(Param);
  7269. if (Param->getDeclName())
  7270. IdResolver.AddDecl(Param);
  7271. }
  7272. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  7273. /// parsing a top-level (non-nested) C++ class, and we are now
  7274. /// parsing those parts of the given Method declaration that could
  7275. /// not be parsed earlier (C++ [class.mem]p2), such as default
  7276. /// arguments. This action should enter the scope of the given
  7277. /// Method declaration as if we had just parsed the qualified method
  7278. /// name. However, it should not bring the parameters into scope;
  7279. /// that will be performed by ActOnDelayedCXXMethodParameter.
  7280. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7281. }
  7282. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  7283. /// C++ method declaration. We're (re-)introducing the given
  7284. /// function parameter into scope for use in parsing later parts of
  7285. /// the method declaration. For example, we could see an
  7286. /// ActOnParamDefaultArgument event for this parameter.
  7287. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  7288. if (!ParamD)
  7289. return;
  7290. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  7291. // If this parameter has an unparsed default argument, clear it out
  7292. // to make way for the parsed default argument.
  7293. if (Param->hasUnparsedDefaultArg())
  7294. Param->setDefaultArg(nullptr);
  7295. S->AddDecl(Param);
  7296. if (Param->getDeclName())
  7297. IdResolver.AddDecl(Param);
  7298. }
  7299. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  7300. /// processing the delayed method declaration for Method. The method
  7301. /// declaration is now considered finished. There may be a separate
  7302. /// ActOnStartOfFunctionDef action later (not necessarily
  7303. /// immediately!) for this method, if it was also defined inside the
  7304. /// class body.
  7305. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7306. if (!MethodD)
  7307. return;
  7308. AdjustDeclIfTemplate(MethodD);
  7309. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  7310. // Now that we have our default arguments, check the constructor
  7311. // again. It could produce additional diagnostics or affect whether
  7312. // the class has implicitly-declared destructors, among other
  7313. // things.
  7314. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  7315. CheckConstructor(Constructor);
  7316. // Check the default arguments, which we may have added.
  7317. if (!Method->isInvalidDecl())
  7318. CheckCXXDefaultArguments(Method);
  7319. }
  7320. // Emit the given diagnostic for each non-address-space qualifier.
  7321. // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
  7322. static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
  7323. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7324. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  7325. bool DiagOccured = false;
  7326. FTI.MethodQualifiers->forEachQualifier(
  7327. [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
  7328. SourceLocation SL) {
  7329. // This diagnostic should be emitted on any qualifier except an addr
  7330. // space qualifier. However, forEachQualifier currently doesn't visit
  7331. // addr space qualifiers, so there's no way to write this condition
  7332. // right now; we just diagnose on everything.
  7333. S.Diag(SL, DiagID) << QualName << SourceRange(SL);
  7334. DiagOccured = true;
  7335. });
  7336. if (DiagOccured)
  7337. D.setInvalidType();
  7338. }
  7339. }
  7340. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  7341. /// the well-formedness of the constructor declarator @p D with type @p
  7342. /// R. If there are any errors in the declarator, this routine will
  7343. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7344. /// will be updated to reflect a well-formed type for the constructor and
  7345. /// returned.
  7346. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7347. StorageClass &SC) {
  7348. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7349. // C++ [class.ctor]p3:
  7350. // A constructor shall not be virtual (10.3) or static (9.4). A
  7351. // constructor can be invoked for a const, volatile or const
  7352. // volatile object. A constructor shall not be declared const,
  7353. // volatile, or const volatile (9.3.2).
  7354. if (isVirtual) {
  7355. if (!D.isInvalidType())
  7356. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7357. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7358. << SourceRange(D.getIdentifierLoc());
  7359. D.setInvalidType();
  7360. }
  7361. if (SC == SC_Static) {
  7362. if (!D.isInvalidType())
  7363. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7364. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7365. << SourceRange(D.getIdentifierLoc());
  7366. D.setInvalidType();
  7367. SC = SC_None;
  7368. }
  7369. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7370. diagnoseIgnoredQualifiers(
  7371. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7372. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7373. D.getDeclSpec().getRestrictSpecLoc(),
  7374. D.getDeclSpec().getAtomicSpecLoc());
  7375. D.setInvalidType();
  7376. }
  7377. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
  7378. // C++0x [class.ctor]p4:
  7379. // A constructor shall not be declared with a ref-qualifier.
  7380. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7381. if (FTI.hasRefQualifier()) {
  7382. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7383. << FTI.RefQualifierIsLValueRef
  7384. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7385. D.setInvalidType();
  7386. }
  7387. // Rebuild the function type "R" without any type qualifiers (in
  7388. // case any of the errors above fired) and with "void" as the
  7389. // return type, since constructors don't have return types.
  7390. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7391. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7392. return R;
  7393. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7394. EPI.TypeQuals = Qualifiers();
  7395. EPI.RefQualifier = RQ_None;
  7396. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7397. }
  7398. /// CheckConstructor - Checks a fully-formed constructor for
  7399. /// well-formedness, issuing any diagnostics required. Returns true if
  7400. /// the constructor declarator is invalid.
  7401. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7402. CXXRecordDecl *ClassDecl
  7403. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7404. if (!ClassDecl)
  7405. return Constructor->setInvalidDecl();
  7406. // C++ [class.copy]p3:
  7407. // A declaration of a constructor for a class X is ill-formed if
  7408. // its first parameter is of type (optionally cv-qualified) X and
  7409. // either there are no other parameters or else all other
  7410. // parameters have default arguments.
  7411. if (!Constructor->isInvalidDecl() &&
  7412. ((Constructor->getNumParams() == 1) ||
  7413. (Constructor->getNumParams() > 1 &&
  7414. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7415. Constructor->getTemplateSpecializationKind()
  7416. != TSK_ImplicitInstantiation) {
  7417. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7418. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7419. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7420. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7421. const char *ConstRef
  7422. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7423. : " const &";
  7424. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7425. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7426. // FIXME: Rather that making the constructor invalid, we should endeavor
  7427. // to fix the type.
  7428. Constructor->setInvalidDecl();
  7429. }
  7430. }
  7431. }
  7432. /// CheckDestructor - Checks a fully-formed destructor definition for
  7433. /// well-formedness, issuing any diagnostics required. Returns true
  7434. /// on error.
  7435. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7436. CXXRecordDecl *RD = Destructor->getParent();
  7437. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7438. SourceLocation Loc;
  7439. if (!Destructor->isImplicit())
  7440. Loc = Destructor->getLocation();
  7441. else
  7442. Loc = RD->getLocation();
  7443. // If we have a virtual destructor, look up the deallocation function
  7444. if (FunctionDecl *OperatorDelete =
  7445. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7446. Expr *ThisArg = nullptr;
  7447. // If the notional 'delete this' expression requires a non-trivial
  7448. // conversion from 'this' to the type of a destroying operator delete's
  7449. // first parameter, perform that conversion now.
  7450. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7451. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7452. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7453. // C++ [class.dtor]p13:
  7454. // ... as if for the expression 'delete this' appearing in a
  7455. // non-virtual destructor of the destructor's class.
  7456. ContextRAII SwitchContext(*this, Destructor);
  7457. ExprResult This =
  7458. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7459. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7460. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7461. if (This.isInvalid()) {
  7462. // FIXME: Register this as a context note so that it comes out
  7463. // in the right order.
  7464. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7465. return true;
  7466. }
  7467. ThisArg = This.get();
  7468. }
  7469. }
  7470. DiagnoseUseOfDecl(OperatorDelete, Loc);
  7471. MarkFunctionReferenced(Loc, OperatorDelete);
  7472. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7473. }
  7474. }
  7475. return false;
  7476. }
  7477. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7478. /// the well-formednes of the destructor declarator @p D with type @p
  7479. /// R. If there are any errors in the declarator, this routine will
  7480. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7481. /// will be updated to reflect a well-formed type for the destructor and
  7482. /// returned.
  7483. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7484. StorageClass& SC) {
  7485. // C++ [class.dtor]p1:
  7486. // [...] A typedef-name that names a class is a class-name
  7487. // (7.1.3); however, a typedef-name that names a class shall not
  7488. // be used as the identifier in the declarator for a destructor
  7489. // declaration.
  7490. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7491. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7492. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7493. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7494. else if (const TemplateSpecializationType *TST =
  7495. DeclaratorType->getAs<TemplateSpecializationType>())
  7496. if (TST->isTypeAlias())
  7497. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7498. << DeclaratorType << 1;
  7499. // C++ [class.dtor]p2:
  7500. // A destructor is used to destroy objects of its class type. A
  7501. // destructor takes no parameters, and no return type can be
  7502. // specified for it (not even void). The address of a destructor
  7503. // shall not be taken. A destructor shall not be static. A
  7504. // destructor can be invoked for a const, volatile or const
  7505. // volatile object. A destructor shall not be declared const,
  7506. // volatile or const volatile (9.3.2).
  7507. if (SC == SC_Static) {
  7508. if (!D.isInvalidType())
  7509. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7510. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7511. << SourceRange(D.getIdentifierLoc())
  7512. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7513. SC = SC_None;
  7514. }
  7515. if (!D.isInvalidType()) {
  7516. // Destructors don't have return types, but the parser will
  7517. // happily parse something like:
  7518. //
  7519. // class X {
  7520. // float ~X();
  7521. // };
  7522. //
  7523. // The return type will be eliminated later.
  7524. if (D.getDeclSpec().hasTypeSpecifier())
  7525. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7526. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7527. << SourceRange(D.getIdentifierLoc());
  7528. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7529. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7530. SourceLocation(),
  7531. D.getDeclSpec().getConstSpecLoc(),
  7532. D.getDeclSpec().getVolatileSpecLoc(),
  7533. D.getDeclSpec().getRestrictSpecLoc(),
  7534. D.getDeclSpec().getAtomicSpecLoc());
  7535. D.setInvalidType();
  7536. }
  7537. }
  7538. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
  7539. // C++0x [class.dtor]p2:
  7540. // A destructor shall not be declared with a ref-qualifier.
  7541. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7542. if (FTI.hasRefQualifier()) {
  7543. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7544. << FTI.RefQualifierIsLValueRef
  7545. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7546. D.setInvalidType();
  7547. }
  7548. // Make sure we don't have any parameters.
  7549. if (FTIHasNonVoidParameters(FTI)) {
  7550. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7551. // Delete the parameters.
  7552. FTI.freeParams();
  7553. D.setInvalidType();
  7554. }
  7555. // Make sure the destructor isn't variadic.
  7556. if (FTI.isVariadic) {
  7557. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7558. D.setInvalidType();
  7559. }
  7560. // Rebuild the function type "R" without any type qualifiers or
  7561. // parameters (in case any of the errors above fired) and with
  7562. // "void" as the return type, since destructors don't have return
  7563. // types.
  7564. if (!D.isInvalidType())
  7565. return R;
  7566. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7567. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7568. EPI.Variadic = false;
  7569. EPI.TypeQuals = Qualifiers();
  7570. EPI.RefQualifier = RQ_None;
  7571. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7572. }
  7573. static void extendLeft(SourceRange &R, SourceRange Before) {
  7574. if (Before.isInvalid())
  7575. return;
  7576. R.setBegin(Before.getBegin());
  7577. if (R.getEnd().isInvalid())
  7578. R.setEnd(Before.getEnd());
  7579. }
  7580. static void extendRight(SourceRange &R, SourceRange After) {
  7581. if (After.isInvalid())
  7582. return;
  7583. if (R.getBegin().isInvalid())
  7584. R.setBegin(After.getBegin());
  7585. R.setEnd(After.getEnd());
  7586. }
  7587. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7588. /// well-formednes of the conversion function declarator @p D with
  7589. /// type @p R. If there are any errors in the declarator, this routine
  7590. /// will emit diagnostics and return true. Otherwise, it will return
  7591. /// false. Either way, the type @p R will be updated to reflect a
  7592. /// well-formed type for the conversion operator.
  7593. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7594. StorageClass& SC) {
  7595. // C++ [class.conv.fct]p1:
  7596. // Neither parameter types nor return type can be specified. The
  7597. // type of a conversion function (8.3.5) is "function taking no
  7598. // parameter returning conversion-type-id."
  7599. if (SC == SC_Static) {
  7600. if (!D.isInvalidType())
  7601. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7602. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7603. << D.getName().getSourceRange();
  7604. D.setInvalidType();
  7605. SC = SC_None;
  7606. }
  7607. TypeSourceInfo *ConvTSI = nullptr;
  7608. QualType ConvType =
  7609. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7610. const DeclSpec &DS = D.getDeclSpec();
  7611. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7612. // Conversion functions don't have return types, but the parser will
  7613. // happily parse something like:
  7614. //
  7615. // class X {
  7616. // float operator bool();
  7617. // };
  7618. //
  7619. // The return type will be changed later anyway.
  7620. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7621. << SourceRange(DS.getTypeSpecTypeLoc())
  7622. << SourceRange(D.getIdentifierLoc());
  7623. D.setInvalidType();
  7624. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7625. // It's also plausible that the user writes type qualifiers in the wrong
  7626. // place, such as:
  7627. // struct S { const operator int(); };
  7628. // FIXME: we could provide a fixit to move the qualifiers onto the
  7629. // conversion type.
  7630. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7631. << SourceRange(D.getIdentifierLoc()) << 0;
  7632. D.setInvalidType();
  7633. }
  7634. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7635. // Make sure we don't have any parameters.
  7636. if (Proto->getNumParams() > 0) {
  7637. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7638. // Delete the parameters.
  7639. D.getFunctionTypeInfo().freeParams();
  7640. D.setInvalidType();
  7641. } else if (Proto->isVariadic()) {
  7642. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7643. D.setInvalidType();
  7644. }
  7645. // Diagnose "&operator bool()" and other such nonsense. This
  7646. // is actually a gcc extension which we don't support.
  7647. if (Proto->getReturnType() != ConvType) {
  7648. bool NeedsTypedef = false;
  7649. SourceRange Before, After;
  7650. // Walk the chunks and extract information on them for our diagnostic.
  7651. bool PastFunctionChunk = false;
  7652. for (auto &Chunk : D.type_objects()) {
  7653. switch (Chunk.Kind) {
  7654. case DeclaratorChunk::Function:
  7655. if (!PastFunctionChunk) {
  7656. if (Chunk.Fun.HasTrailingReturnType) {
  7657. TypeSourceInfo *TRT = nullptr;
  7658. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7659. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7660. }
  7661. PastFunctionChunk = true;
  7662. break;
  7663. }
  7664. LLVM_FALLTHROUGH;
  7665. case DeclaratorChunk::Array:
  7666. NeedsTypedef = true;
  7667. extendRight(After, Chunk.getSourceRange());
  7668. break;
  7669. case DeclaratorChunk::Pointer:
  7670. case DeclaratorChunk::BlockPointer:
  7671. case DeclaratorChunk::Reference:
  7672. case DeclaratorChunk::MemberPointer:
  7673. case DeclaratorChunk::Pipe:
  7674. extendLeft(Before, Chunk.getSourceRange());
  7675. break;
  7676. case DeclaratorChunk::Paren:
  7677. extendLeft(Before, Chunk.Loc);
  7678. extendRight(After, Chunk.EndLoc);
  7679. break;
  7680. }
  7681. }
  7682. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7683. After.isValid() ? After.getBegin() :
  7684. D.getIdentifierLoc();
  7685. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7686. DB << Before << After;
  7687. if (!NeedsTypedef) {
  7688. DB << /*don't need a typedef*/0;
  7689. // If we can provide a correct fix-it hint, do so.
  7690. if (After.isInvalid() && ConvTSI) {
  7691. SourceLocation InsertLoc =
  7692. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7693. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7694. << FixItHint::CreateInsertionFromRange(
  7695. InsertLoc, CharSourceRange::getTokenRange(Before))
  7696. << FixItHint::CreateRemoval(Before);
  7697. }
  7698. } else if (!Proto->getReturnType()->isDependentType()) {
  7699. DB << /*typedef*/1 << Proto->getReturnType();
  7700. } else if (getLangOpts().CPlusPlus11) {
  7701. DB << /*alias template*/2 << Proto->getReturnType();
  7702. } else {
  7703. DB << /*might not be fixable*/3;
  7704. }
  7705. // Recover by incorporating the other type chunks into the result type.
  7706. // Note, this does *not* change the name of the function. This is compatible
  7707. // with the GCC extension:
  7708. // struct S { &operator int(); } s;
  7709. // int &r = s.operator int(); // ok in GCC
  7710. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7711. ConvType = Proto->getReturnType();
  7712. }
  7713. // C++ [class.conv.fct]p4:
  7714. // The conversion-type-id shall not represent a function type nor
  7715. // an array type.
  7716. if (ConvType->isArrayType()) {
  7717. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7718. ConvType = Context.getPointerType(ConvType);
  7719. D.setInvalidType();
  7720. } else if (ConvType->isFunctionType()) {
  7721. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7722. ConvType = Context.getPointerType(ConvType);
  7723. D.setInvalidType();
  7724. }
  7725. // Rebuild the function type "R" without any parameters (in case any
  7726. // of the errors above fired) and with the conversion type as the
  7727. // return type.
  7728. if (D.isInvalidType())
  7729. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7730. // C++0x explicit conversion operators.
  7731. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
  7732. Diag(DS.getExplicitSpecLoc(),
  7733. getLangOpts().CPlusPlus11
  7734. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7735. : diag::ext_explicit_conversion_functions)
  7736. << SourceRange(DS.getExplicitSpecRange());
  7737. }
  7738. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7739. /// the declaration of the given C++ conversion function. This routine
  7740. /// is responsible for recording the conversion function in the C++
  7741. /// class, if possible.
  7742. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7743. assert(Conversion && "Expected to receive a conversion function declaration");
  7744. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7745. // Make sure we aren't redeclaring the conversion function.
  7746. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7747. // C++ [class.conv.fct]p1:
  7748. // [...] A conversion function is never used to convert a
  7749. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7750. // same object type (or a reference to it), to a (possibly
  7751. // cv-qualified) base class of that type (or a reference to it),
  7752. // or to (possibly cv-qualified) void.
  7753. // FIXME: Suppress this warning if the conversion function ends up being a
  7754. // virtual function that overrides a virtual function in a base class.
  7755. QualType ClassType
  7756. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7757. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7758. ConvType = ConvTypeRef->getPointeeType();
  7759. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7760. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7761. /* Suppress diagnostics for instantiations. */;
  7762. else if (ConvType->isRecordType()) {
  7763. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7764. if (ConvType == ClassType)
  7765. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7766. << ClassType;
  7767. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7768. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7769. << ClassType << ConvType;
  7770. } else if (ConvType->isVoidType()) {
  7771. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7772. << ClassType << ConvType;
  7773. }
  7774. if (FunctionTemplateDecl *ConversionTemplate
  7775. = Conversion->getDescribedFunctionTemplate())
  7776. return ConversionTemplate;
  7777. return Conversion;
  7778. }
  7779. namespace {
  7780. /// Utility class to accumulate and print a diagnostic listing the invalid
  7781. /// specifier(s) on a declaration.
  7782. struct BadSpecifierDiagnoser {
  7783. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7784. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7785. ~BadSpecifierDiagnoser() {
  7786. Diagnostic << Specifiers;
  7787. }
  7788. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7789. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7790. }
  7791. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7792. return check(SpecLoc,
  7793. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7794. }
  7795. void check(SourceLocation SpecLoc, const char *Spec) {
  7796. if (SpecLoc.isInvalid()) return;
  7797. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7798. if (!Specifiers.empty()) Specifiers += " ";
  7799. Specifiers += Spec;
  7800. }
  7801. Sema &S;
  7802. Sema::SemaDiagnosticBuilder Diagnostic;
  7803. std::string Specifiers;
  7804. };
  7805. }
  7806. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7807. /// These aren't actually declarators in the grammar, so we need to check that
  7808. /// the user didn't specify any pieces that are not part of the deduction-guide
  7809. /// grammar.
  7810. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7811. StorageClass &SC) {
  7812. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7813. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7814. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7815. // C++ [temp.deduct.guide]p3:
  7816. // A deduction-gide shall be declared in the same scope as the
  7817. // corresponding class template.
  7818. if (!CurContext->getRedeclContext()->Equals(
  7819. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7820. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7821. << GuidedTemplateDecl;
  7822. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7823. }
  7824. auto &DS = D.getMutableDeclSpec();
  7825. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7826. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7827. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7828. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  7829. BadSpecifierDiagnoser Diagnoser(
  7830. *this, D.getIdentifierLoc(),
  7831. diag::err_deduction_guide_invalid_specifier);
  7832. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7833. DS.ClearStorageClassSpecs();
  7834. SC = SC_None;
  7835. // 'explicit' is permitted.
  7836. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7837. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7838. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7839. DS.ClearConstexprSpec();
  7840. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7841. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7842. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7843. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7844. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7845. DS.ClearTypeQualifiers();
  7846. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7847. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7848. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7849. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7850. DS.ClearTypeSpecType();
  7851. }
  7852. if (D.isInvalidType())
  7853. return;
  7854. // Check the declarator is simple enough.
  7855. bool FoundFunction = false;
  7856. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7857. if (Chunk.Kind == DeclaratorChunk::Paren)
  7858. continue;
  7859. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7860. Diag(D.getDeclSpec().getBeginLoc(),
  7861. diag::err_deduction_guide_with_complex_decl)
  7862. << D.getSourceRange();
  7863. break;
  7864. }
  7865. if (!Chunk.Fun.hasTrailingReturnType()) {
  7866. Diag(D.getName().getBeginLoc(),
  7867. diag::err_deduction_guide_no_trailing_return_type);
  7868. break;
  7869. }
  7870. // Check that the return type is written as a specialization of
  7871. // the template specified as the deduction-guide's name.
  7872. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7873. TypeSourceInfo *TSI = nullptr;
  7874. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7875. assert(TSI && "deduction guide has valid type but invalid return type?");
  7876. bool AcceptableReturnType = false;
  7877. bool MightInstantiateToSpecialization = false;
  7878. if (auto RetTST =
  7879. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7880. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7881. bool TemplateMatches =
  7882. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7883. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7884. AcceptableReturnType = true;
  7885. else {
  7886. // This could still instantiate to the right type, unless we know it
  7887. // names the wrong class template.
  7888. auto *TD = SpecifiedName.getAsTemplateDecl();
  7889. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7890. !TemplateMatches);
  7891. }
  7892. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7893. MightInstantiateToSpecialization = true;
  7894. }
  7895. if (!AcceptableReturnType) {
  7896. Diag(TSI->getTypeLoc().getBeginLoc(),
  7897. diag::err_deduction_guide_bad_trailing_return_type)
  7898. << GuidedTemplate << TSI->getType()
  7899. << MightInstantiateToSpecialization
  7900. << TSI->getTypeLoc().getSourceRange();
  7901. }
  7902. // Keep going to check that we don't have any inner declarator pieces (we
  7903. // could still have a function returning a pointer to a function).
  7904. FoundFunction = true;
  7905. }
  7906. if (D.isFunctionDefinition())
  7907. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7908. }
  7909. //===----------------------------------------------------------------------===//
  7910. // Namespace Handling
  7911. //===----------------------------------------------------------------------===//
  7912. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7913. /// reopened.
  7914. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7915. SourceLocation Loc,
  7916. IdentifierInfo *II, bool *IsInline,
  7917. NamespaceDecl *PrevNS) {
  7918. assert(*IsInline != PrevNS->isInline());
  7919. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7920. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7921. // inline namespaces, with the intention of bringing names into namespace std.
  7922. //
  7923. // We support this just well enough to get that case working; this is not
  7924. // sufficient to support reopening namespaces as inline in general.
  7925. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7926. S.getSourceManager().isInSystemHeader(Loc)) {
  7927. // Mark all prior declarations of the namespace as inline.
  7928. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7929. NS = NS->getPreviousDecl())
  7930. NS->setInline(*IsInline);
  7931. // Patch up the lookup table for the containing namespace. This isn't really
  7932. // correct, but it's good enough for this particular case.
  7933. for (auto *I : PrevNS->decls())
  7934. if (auto *ND = dyn_cast<NamedDecl>(I))
  7935. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7936. return;
  7937. }
  7938. if (PrevNS->isInline())
  7939. // The user probably just forgot the 'inline', so suggest that it
  7940. // be added back.
  7941. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7942. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7943. else
  7944. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7945. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7946. *IsInline = PrevNS->isInline();
  7947. }
  7948. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7949. /// definition.
  7950. Decl *Sema::ActOnStartNamespaceDef(
  7951. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7952. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7953. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7954. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7955. // For anonymous namespace, take the location of the left brace.
  7956. SourceLocation Loc = II ? IdentLoc : LBrace;
  7957. bool IsInline = InlineLoc.isValid();
  7958. bool IsInvalid = false;
  7959. bool IsStd = false;
  7960. bool AddToKnown = false;
  7961. Scope *DeclRegionScope = NamespcScope->getParent();
  7962. NamespaceDecl *PrevNS = nullptr;
  7963. if (II) {
  7964. // C++ [namespace.def]p2:
  7965. // The identifier in an original-namespace-definition shall not
  7966. // have been previously defined in the declarative region in
  7967. // which the original-namespace-definition appears. The
  7968. // identifier in an original-namespace-definition is the name of
  7969. // the namespace. Subsequently in that declarative region, it is
  7970. // treated as an original-namespace-name.
  7971. //
  7972. // Since namespace names are unique in their scope, and we don't
  7973. // look through using directives, just look for any ordinary names
  7974. // as if by qualified name lookup.
  7975. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7976. ForExternalRedeclaration);
  7977. LookupQualifiedName(R, CurContext->getRedeclContext());
  7978. NamedDecl *PrevDecl =
  7979. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7980. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7981. if (PrevNS) {
  7982. // This is an extended namespace definition.
  7983. if (IsInline != PrevNS->isInline())
  7984. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7985. &IsInline, PrevNS);
  7986. } else if (PrevDecl) {
  7987. // This is an invalid name redefinition.
  7988. Diag(Loc, diag::err_redefinition_different_kind)
  7989. << II;
  7990. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7991. IsInvalid = true;
  7992. // Continue on to push Namespc as current DeclContext and return it.
  7993. } else if (II->isStr("std") &&
  7994. CurContext->getRedeclContext()->isTranslationUnit()) {
  7995. // This is the first "real" definition of the namespace "std", so update
  7996. // our cache of the "std" namespace to point at this definition.
  7997. PrevNS = getStdNamespace();
  7998. IsStd = true;
  7999. AddToKnown = !IsInline;
  8000. } else {
  8001. // We've seen this namespace for the first time.
  8002. AddToKnown = !IsInline;
  8003. }
  8004. } else {
  8005. // Anonymous namespaces.
  8006. // Determine whether the parent already has an anonymous namespace.
  8007. DeclContext *Parent = CurContext->getRedeclContext();
  8008. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  8009. PrevNS = TU->getAnonymousNamespace();
  8010. } else {
  8011. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  8012. PrevNS = ND->getAnonymousNamespace();
  8013. }
  8014. if (PrevNS && IsInline != PrevNS->isInline())
  8015. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  8016. &IsInline, PrevNS);
  8017. }
  8018. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  8019. StartLoc, Loc, II, PrevNS);
  8020. if (IsInvalid)
  8021. Namespc->setInvalidDecl();
  8022. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  8023. AddPragmaAttributes(DeclRegionScope, Namespc);
  8024. // FIXME: Should we be merging attributes?
  8025. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  8026. PushNamespaceVisibilityAttr(Attr, Loc);
  8027. if (IsStd)
  8028. StdNamespace = Namespc;
  8029. if (AddToKnown)
  8030. KnownNamespaces[Namespc] = false;
  8031. if (II) {
  8032. PushOnScopeChains(Namespc, DeclRegionScope);
  8033. } else {
  8034. // Link the anonymous namespace into its parent.
  8035. DeclContext *Parent = CurContext->getRedeclContext();
  8036. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  8037. TU->setAnonymousNamespace(Namespc);
  8038. } else {
  8039. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  8040. }
  8041. CurContext->addDecl(Namespc);
  8042. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  8043. // behaves as if it were replaced by
  8044. // namespace unique { /* empty body */ }
  8045. // using namespace unique;
  8046. // namespace unique { namespace-body }
  8047. // where all occurrences of 'unique' in a translation unit are
  8048. // replaced by the same identifier and this identifier differs
  8049. // from all other identifiers in the entire program.
  8050. // We just create the namespace with an empty name and then add an
  8051. // implicit using declaration, just like the standard suggests.
  8052. //
  8053. // CodeGen enforces the "universally unique" aspect by giving all
  8054. // declarations semantically contained within an anonymous
  8055. // namespace internal linkage.
  8056. if (!PrevNS) {
  8057. UD = UsingDirectiveDecl::Create(Context, Parent,
  8058. /* 'using' */ LBrace,
  8059. /* 'namespace' */ SourceLocation(),
  8060. /* qualifier */ NestedNameSpecifierLoc(),
  8061. /* identifier */ SourceLocation(),
  8062. Namespc,
  8063. /* Ancestor */ Parent);
  8064. UD->setImplicit();
  8065. Parent->addDecl(UD);
  8066. }
  8067. }
  8068. ActOnDocumentableDecl(Namespc);
  8069. // Although we could have an invalid decl (i.e. the namespace name is a
  8070. // redefinition), push it as current DeclContext and try to continue parsing.
  8071. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  8072. // for the namespace has the declarations that showed up in that particular
  8073. // namespace definition.
  8074. PushDeclContext(NamespcScope, Namespc);
  8075. return Namespc;
  8076. }
  8077. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  8078. /// is a namespace alias, returns the namespace it points to.
  8079. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  8080. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  8081. return AD->getNamespace();
  8082. return dyn_cast_or_null<NamespaceDecl>(D);
  8083. }
  8084. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  8085. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  8086. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  8087. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  8088. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  8089. Namespc->setRBraceLoc(RBrace);
  8090. PopDeclContext();
  8091. if (Namespc->hasAttr<VisibilityAttr>())
  8092. PopPragmaVisibility(true, RBrace);
  8093. // If this namespace contains an export-declaration, export it now.
  8094. if (DeferredExportedNamespaces.erase(Namespc))
  8095. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  8096. }
  8097. CXXRecordDecl *Sema::getStdBadAlloc() const {
  8098. return cast_or_null<CXXRecordDecl>(
  8099. StdBadAlloc.get(Context.getExternalSource()));
  8100. }
  8101. EnumDecl *Sema::getStdAlignValT() const {
  8102. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  8103. }
  8104. NamespaceDecl *Sema::getStdNamespace() const {
  8105. return cast_or_null<NamespaceDecl>(
  8106. StdNamespace.get(Context.getExternalSource()));
  8107. }
  8108. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  8109. if (!StdExperimentalNamespaceCache) {
  8110. if (auto Std = getStdNamespace()) {
  8111. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  8112. SourceLocation(), LookupNamespaceName);
  8113. if (!LookupQualifiedName(Result, Std) ||
  8114. !(StdExperimentalNamespaceCache =
  8115. Result.getAsSingle<NamespaceDecl>()))
  8116. Result.suppressDiagnostics();
  8117. }
  8118. }
  8119. return StdExperimentalNamespaceCache;
  8120. }
  8121. namespace {
  8122. enum UnsupportedSTLSelect {
  8123. USS_InvalidMember,
  8124. USS_MissingMember,
  8125. USS_NonTrivial,
  8126. USS_Other
  8127. };
  8128. struct InvalidSTLDiagnoser {
  8129. Sema &S;
  8130. SourceLocation Loc;
  8131. QualType TyForDiags;
  8132. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  8133. const VarDecl *VD = nullptr) {
  8134. {
  8135. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  8136. << TyForDiags << ((int)Sel);
  8137. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  8138. assert(!Name.empty());
  8139. D << Name;
  8140. }
  8141. }
  8142. if (Sel == USS_InvalidMember) {
  8143. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  8144. << VD << VD->getSourceRange();
  8145. }
  8146. return QualType();
  8147. }
  8148. };
  8149. } // namespace
  8150. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  8151. SourceLocation Loc) {
  8152. assert(getLangOpts().CPlusPlus &&
  8153. "Looking for comparison category type outside of C++.");
  8154. // Check if we've already successfully checked the comparison category type
  8155. // before. If so, skip checking it again.
  8156. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  8157. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  8158. return Info->getType();
  8159. // If lookup failed
  8160. if (!Info) {
  8161. std::string NameForDiags = "std::";
  8162. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  8163. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  8164. << NameForDiags;
  8165. return QualType();
  8166. }
  8167. assert(Info->Kind == Kind);
  8168. assert(Info->Record);
  8169. // Update the Record decl in case we encountered a forward declaration on our
  8170. // first pass. FIXME: This is a bit of a hack.
  8171. if (Info->Record->hasDefinition())
  8172. Info->Record = Info->Record->getDefinition();
  8173. // Use an elaborated type for diagnostics which has a name containing the
  8174. // prepended 'std' namespace but not any inline namespace names.
  8175. QualType TyForDiags = [&]() {
  8176. auto *NNS =
  8177. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  8178. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  8179. }();
  8180. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  8181. return QualType();
  8182. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  8183. if (!Info->Record->isTriviallyCopyable())
  8184. return UnsupportedSTLError(USS_NonTrivial);
  8185. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  8186. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  8187. // Tolerate empty base classes.
  8188. if (Base->isEmpty())
  8189. continue;
  8190. // Reject STL implementations which have at least one non-empty base.
  8191. return UnsupportedSTLError();
  8192. }
  8193. // Check that the STL has implemented the types using a single integer field.
  8194. // This expectation allows better codegen for builtin operators. We require:
  8195. // (1) The class has exactly one field.
  8196. // (2) The field is an integral or enumeration type.
  8197. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  8198. if (std::distance(FIt, FEnd) != 1 ||
  8199. !FIt->getType()->isIntegralOrEnumerationType()) {
  8200. return UnsupportedSTLError();
  8201. }
  8202. // Build each of the require values and store them in Info.
  8203. for (ComparisonCategoryResult CCR :
  8204. ComparisonCategories::getPossibleResultsForType(Kind)) {
  8205. StringRef MemName = ComparisonCategories::getResultString(CCR);
  8206. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  8207. if (!ValInfo)
  8208. return UnsupportedSTLError(USS_MissingMember, MemName);
  8209. VarDecl *VD = ValInfo->VD;
  8210. assert(VD && "should not be null!");
  8211. // Attempt to diagnose reasons why the STL definition of this type
  8212. // might be foobar, including it failing to be a constant expression.
  8213. // TODO Handle more ways the lookup or result can be invalid.
  8214. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  8215. !VD->checkInitIsICE())
  8216. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  8217. // Attempt to evaluate the var decl as a constant expression and extract
  8218. // the value of its first field as a ICE. If this fails, the STL
  8219. // implementation is not supported.
  8220. if (!ValInfo->hasValidIntValue())
  8221. return UnsupportedSTLError();
  8222. MarkVariableReferenced(Loc, VD);
  8223. }
  8224. // We've successfully built the required types and expressions. Update
  8225. // the cache and return the newly cached value.
  8226. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  8227. return Info->getType();
  8228. }
  8229. /// Retrieve the special "std" namespace, which may require us to
  8230. /// implicitly define the namespace.
  8231. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  8232. if (!StdNamespace) {
  8233. // The "std" namespace has not yet been defined, so build one implicitly.
  8234. StdNamespace = NamespaceDecl::Create(Context,
  8235. Context.getTranslationUnitDecl(),
  8236. /*Inline=*/false,
  8237. SourceLocation(), SourceLocation(),
  8238. &PP.getIdentifierTable().get("std"),
  8239. /*PrevDecl=*/nullptr);
  8240. getStdNamespace()->setImplicit(true);
  8241. }
  8242. return getStdNamespace();
  8243. }
  8244. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  8245. assert(getLangOpts().CPlusPlus &&
  8246. "Looking for std::initializer_list outside of C++.");
  8247. // We're looking for implicit instantiations of
  8248. // template <typename E> class std::initializer_list.
  8249. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  8250. return false;
  8251. ClassTemplateDecl *Template = nullptr;
  8252. const TemplateArgument *Arguments = nullptr;
  8253. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  8254. ClassTemplateSpecializationDecl *Specialization =
  8255. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8256. if (!Specialization)
  8257. return false;
  8258. Template = Specialization->getSpecializedTemplate();
  8259. Arguments = Specialization->getTemplateArgs().data();
  8260. } else if (const TemplateSpecializationType *TST =
  8261. Ty->getAs<TemplateSpecializationType>()) {
  8262. Template = dyn_cast_or_null<ClassTemplateDecl>(
  8263. TST->getTemplateName().getAsTemplateDecl());
  8264. Arguments = TST->getArgs();
  8265. }
  8266. if (!Template)
  8267. return false;
  8268. if (!StdInitializerList) {
  8269. // Haven't recognized std::initializer_list yet, maybe this is it.
  8270. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  8271. if (TemplateClass->getIdentifier() !=
  8272. &PP.getIdentifierTable().get("initializer_list") ||
  8273. !getStdNamespace()->InEnclosingNamespaceSetOf(
  8274. TemplateClass->getDeclContext()))
  8275. return false;
  8276. // This is a template called std::initializer_list, but is it the right
  8277. // template?
  8278. TemplateParameterList *Params = Template->getTemplateParameters();
  8279. if (Params->getMinRequiredArguments() != 1)
  8280. return false;
  8281. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  8282. return false;
  8283. // It's the right template.
  8284. StdInitializerList = Template;
  8285. }
  8286. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  8287. return false;
  8288. // This is an instance of std::initializer_list. Find the argument type.
  8289. if (Element)
  8290. *Element = Arguments[0].getAsType();
  8291. return true;
  8292. }
  8293. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  8294. NamespaceDecl *Std = S.getStdNamespace();
  8295. if (!Std) {
  8296. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8297. return nullptr;
  8298. }
  8299. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  8300. Loc, Sema::LookupOrdinaryName);
  8301. if (!S.LookupQualifiedName(Result, Std)) {
  8302. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8303. return nullptr;
  8304. }
  8305. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  8306. if (!Template) {
  8307. Result.suppressDiagnostics();
  8308. // We found something weird. Complain about the first thing we found.
  8309. NamedDecl *Found = *Result.begin();
  8310. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  8311. return nullptr;
  8312. }
  8313. // We found some template called std::initializer_list. Now verify that it's
  8314. // correct.
  8315. TemplateParameterList *Params = Template->getTemplateParameters();
  8316. if (Params->getMinRequiredArguments() != 1 ||
  8317. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  8318. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  8319. return nullptr;
  8320. }
  8321. return Template;
  8322. }
  8323. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  8324. if (!StdInitializerList) {
  8325. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8326. if (!StdInitializerList)
  8327. return QualType();
  8328. }
  8329. TemplateArgumentListInfo Args(Loc, Loc);
  8330. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8331. Context.getTrivialTypeSourceInfo(Element,
  8332. Loc)));
  8333. return Context.getCanonicalType(
  8334. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8335. }
  8336. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8337. // C++ [dcl.init.list]p2:
  8338. // A constructor is an initializer-list constructor if its first parameter
  8339. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8340. // std::initializer_list<E> for some type E, and either there are no other
  8341. // parameters or else all other parameters have default arguments.
  8342. if (Ctor->getNumParams() < 1 ||
  8343. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8344. return false;
  8345. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8346. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8347. ArgType = RT->getPointeeType().getUnqualifiedType();
  8348. return isStdInitializerList(ArgType, nullptr);
  8349. }
  8350. /// Determine whether a using statement is in a context where it will be
  8351. /// apply in all contexts.
  8352. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8353. switch (CurContext->getDeclKind()) {
  8354. case Decl::TranslationUnit:
  8355. return true;
  8356. case Decl::LinkageSpec:
  8357. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8358. default:
  8359. return false;
  8360. }
  8361. }
  8362. namespace {
  8363. // Callback to only accept typo corrections that are namespaces.
  8364. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  8365. public:
  8366. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8367. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8368. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8369. return false;
  8370. }
  8371. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8372. return std::make_unique<NamespaceValidatorCCC>(*this);
  8373. }
  8374. };
  8375. }
  8376. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8377. CXXScopeSpec &SS,
  8378. SourceLocation IdentLoc,
  8379. IdentifierInfo *Ident) {
  8380. R.clear();
  8381. NamespaceValidatorCCC CCC{};
  8382. if (TypoCorrection Corrected =
  8383. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  8384. Sema::CTK_ErrorRecovery)) {
  8385. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8386. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8387. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8388. Ident->getName().equals(CorrectedStr);
  8389. S.diagnoseTypo(Corrected,
  8390. S.PDiag(diag::err_using_directive_member_suggest)
  8391. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8392. S.PDiag(diag::note_namespace_defined_here));
  8393. } else {
  8394. S.diagnoseTypo(Corrected,
  8395. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8396. S.PDiag(diag::note_namespace_defined_here));
  8397. }
  8398. R.addDecl(Corrected.getFoundDecl());
  8399. return true;
  8400. }
  8401. return false;
  8402. }
  8403. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8404. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8405. SourceLocation IdentLoc,
  8406. IdentifierInfo *NamespcName,
  8407. const ParsedAttributesView &AttrList) {
  8408. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8409. assert(NamespcName && "Invalid NamespcName.");
  8410. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8411. // This can only happen along a recovery path.
  8412. while (S->isTemplateParamScope())
  8413. S = S->getParent();
  8414. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8415. UsingDirectiveDecl *UDir = nullptr;
  8416. NestedNameSpecifier *Qualifier = nullptr;
  8417. if (SS.isSet())
  8418. Qualifier = SS.getScopeRep();
  8419. // Lookup namespace name.
  8420. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8421. LookupParsedName(R, S, &SS);
  8422. if (R.isAmbiguous())
  8423. return nullptr;
  8424. if (R.empty()) {
  8425. R.clear();
  8426. // Allow "using namespace std;" or "using namespace ::std;" even if
  8427. // "std" hasn't been defined yet, for GCC compatibility.
  8428. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8429. NamespcName->isStr("std")) {
  8430. Diag(IdentLoc, diag::ext_using_undefined_std);
  8431. R.addDecl(getOrCreateStdNamespace());
  8432. R.resolveKind();
  8433. }
  8434. // Otherwise, attempt typo correction.
  8435. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8436. }
  8437. if (!R.empty()) {
  8438. NamedDecl *Named = R.getRepresentativeDecl();
  8439. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8440. assert(NS && "expected namespace decl");
  8441. // The use of a nested name specifier may trigger deprecation warnings.
  8442. DiagnoseUseOfDecl(Named, IdentLoc);
  8443. // C++ [namespace.udir]p1:
  8444. // A using-directive specifies that the names in the nominated
  8445. // namespace can be used in the scope in which the
  8446. // using-directive appears after the using-directive. During
  8447. // unqualified name lookup (3.4.1), the names appear as if they
  8448. // were declared in the nearest enclosing namespace which
  8449. // contains both the using-directive and the nominated
  8450. // namespace. [Note: in this context, "contains" means "contains
  8451. // directly or indirectly". ]
  8452. // Find enclosing context containing both using-directive and
  8453. // nominated namespace.
  8454. DeclContext *CommonAncestor = NS;
  8455. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8456. CommonAncestor = CommonAncestor->getParent();
  8457. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8458. SS.getWithLocInContext(Context),
  8459. IdentLoc, Named, CommonAncestor);
  8460. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8461. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8462. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8463. }
  8464. PushUsingDirective(S, UDir);
  8465. } else {
  8466. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8467. }
  8468. if (UDir)
  8469. ProcessDeclAttributeList(S, UDir, AttrList);
  8470. return UDir;
  8471. }
  8472. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8473. // If the scope has an associated entity and the using directive is at
  8474. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8475. // its lookup structure so qualified name lookup can find it.
  8476. DeclContext *Ctx = S->getEntity();
  8477. if (Ctx && !Ctx->isFunctionOrMethod())
  8478. Ctx->addDecl(UDir);
  8479. else
  8480. // Otherwise, it is at block scope. The using-directives will affect lookup
  8481. // only to the end of the scope.
  8482. S->PushUsingDirective(UDir);
  8483. }
  8484. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8485. SourceLocation UsingLoc,
  8486. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8487. UnqualifiedId &Name,
  8488. SourceLocation EllipsisLoc,
  8489. const ParsedAttributesView &AttrList) {
  8490. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8491. if (SS.isEmpty()) {
  8492. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8493. return nullptr;
  8494. }
  8495. switch (Name.getKind()) {
  8496. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8497. case UnqualifiedIdKind::IK_Identifier:
  8498. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8499. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8500. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8501. break;
  8502. case UnqualifiedIdKind::IK_ConstructorName:
  8503. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8504. // C++11 inheriting constructors.
  8505. Diag(Name.getBeginLoc(),
  8506. getLangOpts().CPlusPlus11
  8507. ? diag::warn_cxx98_compat_using_decl_constructor
  8508. : diag::err_using_decl_constructor)
  8509. << SS.getRange();
  8510. if (getLangOpts().CPlusPlus11) break;
  8511. return nullptr;
  8512. case UnqualifiedIdKind::IK_DestructorName:
  8513. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8514. return nullptr;
  8515. case UnqualifiedIdKind::IK_TemplateId:
  8516. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8517. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8518. return nullptr;
  8519. case UnqualifiedIdKind::IK_DeductionGuideName:
  8520. llvm_unreachable("cannot parse qualified deduction guide name");
  8521. }
  8522. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8523. DeclarationName TargetName = TargetNameInfo.getName();
  8524. if (!TargetName)
  8525. return nullptr;
  8526. // Warn about access declarations.
  8527. if (UsingLoc.isInvalid()) {
  8528. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8529. ? diag::err_access_decl
  8530. : diag::warn_access_decl_deprecated)
  8531. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8532. }
  8533. if (EllipsisLoc.isInvalid()) {
  8534. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8535. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8536. return nullptr;
  8537. } else {
  8538. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8539. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8540. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8541. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8542. EllipsisLoc = SourceLocation();
  8543. }
  8544. }
  8545. NamedDecl *UD =
  8546. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8547. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8548. /*IsInstantiation*/false);
  8549. if (UD)
  8550. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8551. return UD;
  8552. }
  8553. /// Determine whether a using declaration considers the given
  8554. /// declarations as "equivalent", e.g., if they are redeclarations of
  8555. /// the same entity or are both typedefs of the same type.
  8556. static bool
  8557. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8558. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8559. return true;
  8560. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8561. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8562. return Context.hasSameType(TD1->getUnderlyingType(),
  8563. TD2->getUnderlyingType());
  8564. return false;
  8565. }
  8566. /// Determines whether to create a using shadow decl for a particular
  8567. /// decl, given the set of decls existing prior to this using lookup.
  8568. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8569. const LookupResult &Previous,
  8570. UsingShadowDecl *&PrevShadow) {
  8571. // Diagnose finding a decl which is not from a base class of the
  8572. // current class. We do this now because there are cases where this
  8573. // function will silently decide not to build a shadow decl, which
  8574. // will pre-empt further diagnostics.
  8575. //
  8576. // We don't need to do this in C++11 because we do the check once on
  8577. // the qualifier.
  8578. //
  8579. // FIXME: diagnose the following if we care enough:
  8580. // struct A { int foo; };
  8581. // struct B : A { using A::foo; };
  8582. // template <class T> struct C : A {};
  8583. // template <class T> struct D : C<T> { using B::foo; } // <---
  8584. // This is invalid (during instantiation) in C++03 because B::foo
  8585. // resolves to the using decl in B, which is not a base class of D<T>.
  8586. // We can't diagnose it immediately because C<T> is an unknown
  8587. // specialization. The UsingShadowDecl in D<T> then points directly
  8588. // to A::foo, which will look well-formed when we instantiate.
  8589. // The right solution is to not collapse the shadow-decl chain.
  8590. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8591. DeclContext *OrigDC = Orig->getDeclContext();
  8592. // Handle enums and anonymous structs.
  8593. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8594. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8595. while (OrigRec->isAnonymousStructOrUnion())
  8596. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8597. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8598. if (OrigDC == CurContext) {
  8599. Diag(Using->getLocation(),
  8600. diag::err_using_decl_nested_name_specifier_is_current_class)
  8601. << Using->getQualifierLoc().getSourceRange();
  8602. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8603. Using->setInvalidDecl();
  8604. return true;
  8605. }
  8606. Diag(Using->getQualifierLoc().getBeginLoc(),
  8607. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8608. << Using->getQualifier()
  8609. << cast<CXXRecordDecl>(CurContext)
  8610. << Using->getQualifierLoc().getSourceRange();
  8611. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8612. Using->setInvalidDecl();
  8613. return true;
  8614. }
  8615. }
  8616. if (Previous.empty()) return false;
  8617. NamedDecl *Target = Orig;
  8618. if (isa<UsingShadowDecl>(Target))
  8619. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8620. // If the target happens to be one of the previous declarations, we
  8621. // don't have a conflict.
  8622. //
  8623. // FIXME: but we might be increasing its access, in which case we
  8624. // should redeclare it.
  8625. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8626. bool FoundEquivalentDecl = false;
  8627. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8628. I != E; ++I) {
  8629. NamedDecl *D = (*I)->getUnderlyingDecl();
  8630. // We can have UsingDecls in our Previous results because we use the same
  8631. // LookupResult for checking whether the UsingDecl itself is a valid
  8632. // redeclaration.
  8633. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8634. continue;
  8635. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8636. // C++ [class.mem]p19:
  8637. // If T is the name of a class, then [every named member other than
  8638. // a non-static data member] shall have a name different from T
  8639. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8640. !isa<IndirectFieldDecl>(Target) &&
  8641. !isa<UnresolvedUsingValueDecl>(Target) &&
  8642. DiagnoseClassNameShadow(
  8643. CurContext,
  8644. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8645. return true;
  8646. }
  8647. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8648. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8649. PrevShadow = Shadow;
  8650. FoundEquivalentDecl = true;
  8651. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8652. // We don't conflict with an existing using shadow decl of an equivalent
  8653. // declaration, but we're not a redeclaration of it.
  8654. FoundEquivalentDecl = true;
  8655. }
  8656. if (isVisible(D))
  8657. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8658. }
  8659. if (FoundEquivalentDecl)
  8660. return false;
  8661. if (FunctionDecl *FD = Target->getAsFunction()) {
  8662. NamedDecl *OldDecl = nullptr;
  8663. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8664. /*IsForUsingDecl*/ true)) {
  8665. case Ovl_Overload:
  8666. return false;
  8667. case Ovl_NonFunction:
  8668. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8669. break;
  8670. // We found a decl with the exact signature.
  8671. case Ovl_Match:
  8672. // If we're in a record, we want to hide the target, so we
  8673. // return true (without a diagnostic) to tell the caller not to
  8674. // build a shadow decl.
  8675. if (CurContext->isRecord())
  8676. return true;
  8677. // If we're not in a record, this is an error.
  8678. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8679. break;
  8680. }
  8681. Diag(Target->getLocation(), diag::note_using_decl_target);
  8682. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8683. Using->setInvalidDecl();
  8684. return true;
  8685. }
  8686. // Target is not a function.
  8687. if (isa<TagDecl>(Target)) {
  8688. // No conflict between a tag and a non-tag.
  8689. if (!Tag) return false;
  8690. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8691. Diag(Target->getLocation(), diag::note_using_decl_target);
  8692. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8693. Using->setInvalidDecl();
  8694. return true;
  8695. }
  8696. // No conflict between a tag and a non-tag.
  8697. if (!NonTag) return false;
  8698. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8699. Diag(Target->getLocation(), diag::note_using_decl_target);
  8700. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8701. Using->setInvalidDecl();
  8702. return true;
  8703. }
  8704. /// Determine whether a direct base class is a virtual base class.
  8705. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8706. if (!Derived->getNumVBases())
  8707. return false;
  8708. for (auto &B : Derived->bases())
  8709. if (B.getType()->getAsCXXRecordDecl() == Base)
  8710. return B.isVirtual();
  8711. llvm_unreachable("not a direct base class");
  8712. }
  8713. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8714. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8715. UsingDecl *UD,
  8716. NamedDecl *Orig,
  8717. UsingShadowDecl *PrevDecl) {
  8718. // If we resolved to another shadow declaration, just coalesce them.
  8719. NamedDecl *Target = Orig;
  8720. if (isa<UsingShadowDecl>(Target)) {
  8721. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8722. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8723. }
  8724. NamedDecl *NonTemplateTarget = Target;
  8725. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8726. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8727. UsingShadowDecl *Shadow;
  8728. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8729. bool IsVirtualBase =
  8730. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8731. UD->getQualifier()->getAsRecordDecl());
  8732. Shadow = ConstructorUsingShadowDecl::Create(
  8733. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8734. } else {
  8735. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8736. Target);
  8737. }
  8738. UD->addShadowDecl(Shadow);
  8739. Shadow->setAccess(UD->getAccess());
  8740. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8741. Shadow->setInvalidDecl();
  8742. Shadow->setPreviousDecl(PrevDecl);
  8743. if (S)
  8744. PushOnScopeChains(Shadow, S);
  8745. else
  8746. CurContext->addDecl(Shadow);
  8747. return Shadow;
  8748. }
  8749. /// Hides a using shadow declaration. This is required by the current
  8750. /// using-decl implementation when a resolvable using declaration in a
  8751. /// class is followed by a declaration which would hide or override
  8752. /// one or more of the using decl's targets; for example:
  8753. ///
  8754. /// struct Base { void foo(int); };
  8755. /// struct Derived : Base {
  8756. /// using Base::foo;
  8757. /// void foo(int);
  8758. /// };
  8759. ///
  8760. /// The governing language is C++03 [namespace.udecl]p12:
  8761. ///
  8762. /// When a using-declaration brings names from a base class into a
  8763. /// derived class scope, member functions in the derived class
  8764. /// override and/or hide member functions with the same name and
  8765. /// parameter types in a base class (rather than conflicting).
  8766. ///
  8767. /// There are two ways to implement this:
  8768. /// (1) optimistically create shadow decls when they're not hidden
  8769. /// by existing declarations, or
  8770. /// (2) don't create any shadow decls (or at least don't make them
  8771. /// visible) until we've fully parsed/instantiated the class.
  8772. /// The problem with (1) is that we might have to retroactively remove
  8773. /// a shadow decl, which requires several O(n) operations because the
  8774. /// decl structures are (very reasonably) not designed for removal.
  8775. /// (2) avoids this but is very fiddly and phase-dependent.
  8776. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8777. if (Shadow->getDeclName().getNameKind() ==
  8778. DeclarationName::CXXConversionFunctionName)
  8779. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8780. // Remove it from the DeclContext...
  8781. Shadow->getDeclContext()->removeDecl(Shadow);
  8782. // ...and the scope, if applicable...
  8783. if (S) {
  8784. S->RemoveDecl(Shadow);
  8785. IdResolver.RemoveDecl(Shadow);
  8786. }
  8787. // ...and the using decl.
  8788. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8789. // TODO: complain somehow if Shadow was used. It shouldn't
  8790. // be possible for this to happen, because...?
  8791. }
  8792. /// Find the base specifier for a base class with the given type.
  8793. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8794. QualType DesiredBase,
  8795. bool &AnyDependentBases) {
  8796. // Check whether the named type is a direct base class.
  8797. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
  8798. .getUnqualifiedType();
  8799. for (auto &Base : Derived->bases()) {
  8800. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8801. if (CanonicalDesiredBase == BaseType)
  8802. return &Base;
  8803. if (BaseType->isDependentType())
  8804. AnyDependentBases = true;
  8805. }
  8806. return nullptr;
  8807. }
  8808. namespace {
  8809. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  8810. public:
  8811. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8812. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8813. : HasTypenameKeyword(HasTypenameKeyword),
  8814. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8815. RequireMemberOf(RequireMemberOf) {}
  8816. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8817. NamedDecl *ND = Candidate.getCorrectionDecl();
  8818. // Keywords are not valid here.
  8819. if (!ND || isa<NamespaceDecl>(ND))
  8820. return false;
  8821. // Completely unqualified names are invalid for a 'using' declaration.
  8822. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8823. return false;
  8824. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8825. // reject.
  8826. if (RequireMemberOf) {
  8827. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8828. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8829. // No-one ever wants a using-declaration to name an injected-class-name
  8830. // of a base class, unless they're declaring an inheriting constructor.
  8831. ASTContext &Ctx = ND->getASTContext();
  8832. if (!Ctx.getLangOpts().CPlusPlus11)
  8833. return false;
  8834. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8835. // Check that the injected-class-name is named as a member of its own
  8836. // type; we don't want to suggest 'using Derived::Base;', since that
  8837. // means something else.
  8838. NestedNameSpecifier *Specifier =
  8839. Candidate.WillReplaceSpecifier()
  8840. ? Candidate.getCorrectionSpecifier()
  8841. : OldNNS;
  8842. if (!Specifier->getAsType() ||
  8843. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8844. return false;
  8845. // Check that this inheriting constructor declaration actually names a
  8846. // direct base class of the current class.
  8847. bool AnyDependentBases = false;
  8848. if (!findDirectBaseWithType(RequireMemberOf,
  8849. Ctx.getRecordType(FoundRecord),
  8850. AnyDependentBases) &&
  8851. !AnyDependentBases)
  8852. return false;
  8853. } else {
  8854. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8855. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8856. return false;
  8857. // FIXME: Check that the base class member is accessible?
  8858. }
  8859. } else {
  8860. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8861. if (FoundRecord && FoundRecord->isInjectedClassName())
  8862. return false;
  8863. }
  8864. if (isa<TypeDecl>(ND))
  8865. return HasTypenameKeyword || !IsInstantiation;
  8866. return !HasTypenameKeyword;
  8867. }
  8868. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8869. return std::make_unique<UsingValidatorCCC>(*this);
  8870. }
  8871. private:
  8872. bool HasTypenameKeyword;
  8873. bool IsInstantiation;
  8874. NestedNameSpecifier *OldNNS;
  8875. CXXRecordDecl *RequireMemberOf;
  8876. };
  8877. } // end anonymous namespace
  8878. /// Builds a using declaration.
  8879. ///
  8880. /// \param IsInstantiation - Whether this call arises from an
  8881. /// instantiation of an unresolved using declaration. We treat
  8882. /// the lookup differently for these declarations.
  8883. NamedDecl *Sema::BuildUsingDeclaration(
  8884. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8885. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8886. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8887. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8888. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8889. SourceLocation IdentLoc = NameInfo.getLoc();
  8890. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8891. // FIXME: We ignore attributes for now.
  8892. // For an inheriting constructor declaration, the name of the using
  8893. // declaration is the name of a constructor in this class, not in the
  8894. // base class.
  8895. DeclarationNameInfo UsingName = NameInfo;
  8896. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8897. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8898. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8899. Context.getCanonicalType(Context.getRecordType(RD))));
  8900. // Do the redeclaration lookup in the current scope.
  8901. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8902. ForVisibleRedeclaration);
  8903. Previous.setHideTags(false);
  8904. if (S) {
  8905. LookupName(Previous, S);
  8906. // It is really dumb that we have to do this.
  8907. LookupResult::Filter F = Previous.makeFilter();
  8908. while (F.hasNext()) {
  8909. NamedDecl *D = F.next();
  8910. if (!isDeclInScope(D, CurContext, S))
  8911. F.erase();
  8912. // If we found a local extern declaration that's not ordinarily visible,
  8913. // and this declaration is being added to a non-block scope, ignore it.
  8914. // We're only checking for scope conflicts here, not also for violations
  8915. // of the linkage rules.
  8916. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8917. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8918. F.erase();
  8919. }
  8920. F.done();
  8921. } else {
  8922. assert(IsInstantiation && "no scope in non-instantiation");
  8923. if (CurContext->isRecord())
  8924. LookupQualifiedName(Previous, CurContext);
  8925. else {
  8926. // No redeclaration check is needed here; in non-member contexts we
  8927. // diagnosed all possible conflicts with other using-declarations when
  8928. // building the template:
  8929. //
  8930. // For a dependent non-type using declaration, the only valid case is
  8931. // if we instantiate to a single enumerator. We check for conflicts
  8932. // between shadow declarations we introduce, and we check in the template
  8933. // definition for conflicts between a non-type using declaration and any
  8934. // other declaration, which together covers all cases.
  8935. //
  8936. // A dependent typename using declaration will never successfully
  8937. // instantiate, since it will always name a class member, so we reject
  8938. // that in the template definition.
  8939. }
  8940. }
  8941. // Check for invalid redeclarations.
  8942. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8943. SS, IdentLoc, Previous))
  8944. return nullptr;
  8945. // Check for bad qualifiers.
  8946. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8947. IdentLoc))
  8948. return nullptr;
  8949. DeclContext *LookupContext = computeDeclContext(SS);
  8950. NamedDecl *D;
  8951. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8952. if (!LookupContext || EllipsisLoc.isValid()) {
  8953. if (HasTypenameKeyword) {
  8954. // FIXME: not all declaration name kinds are legal here
  8955. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8956. UsingLoc, TypenameLoc,
  8957. QualifierLoc,
  8958. IdentLoc, NameInfo.getName(),
  8959. EllipsisLoc);
  8960. } else {
  8961. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8962. QualifierLoc, NameInfo, EllipsisLoc);
  8963. }
  8964. D->setAccess(AS);
  8965. CurContext->addDecl(D);
  8966. return D;
  8967. }
  8968. auto Build = [&](bool Invalid) {
  8969. UsingDecl *UD =
  8970. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8971. UsingName, HasTypenameKeyword);
  8972. UD->setAccess(AS);
  8973. CurContext->addDecl(UD);
  8974. UD->setInvalidDecl(Invalid);
  8975. return UD;
  8976. };
  8977. auto BuildInvalid = [&]{ return Build(true); };
  8978. auto BuildValid = [&]{ return Build(false); };
  8979. if (RequireCompleteDeclContext(SS, LookupContext))
  8980. return BuildInvalid();
  8981. // Look up the target name.
  8982. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8983. // Unlike most lookups, we don't always want to hide tag
  8984. // declarations: tag names are visible through the using declaration
  8985. // even if hidden by ordinary names, *except* in a dependent context
  8986. // where it's important for the sanity of two-phase lookup.
  8987. if (!IsInstantiation)
  8988. R.setHideTags(false);
  8989. // For the purposes of this lookup, we have a base object type
  8990. // equal to that of the current context.
  8991. if (CurContext->isRecord()) {
  8992. R.setBaseObjectType(
  8993. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8994. }
  8995. LookupQualifiedName(R, LookupContext);
  8996. // Try to correct typos if possible. If constructor name lookup finds no
  8997. // results, that means the named class has no explicit constructors, and we
  8998. // suppressed declaring implicit ones (probably because it's dependent or
  8999. // invalid).
  9000. if (R.empty() &&
  9001. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  9002. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  9003. // it will believe that glibc provides a ::gets in cases where it does not,
  9004. // and will try to pull it into namespace std with a using-declaration.
  9005. // Just ignore the using-declaration in that case.
  9006. auto *II = NameInfo.getName().getAsIdentifierInfo();
  9007. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  9008. CurContext->isStdNamespace() &&
  9009. isa<TranslationUnitDecl>(LookupContext) &&
  9010. getSourceManager().isInSystemHeader(UsingLoc))
  9011. return nullptr;
  9012. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  9013. dyn_cast<CXXRecordDecl>(CurContext));
  9014. if (TypoCorrection Corrected =
  9015. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  9016. CTK_ErrorRecovery)) {
  9017. // We reject candidates where DroppedSpecifier == true, hence the
  9018. // literal '0' below.
  9019. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  9020. << NameInfo.getName() << LookupContext << 0
  9021. << SS.getRange());
  9022. // If we picked a correction with no attached Decl we can't do anything
  9023. // useful with it, bail out.
  9024. NamedDecl *ND = Corrected.getCorrectionDecl();
  9025. if (!ND)
  9026. return BuildInvalid();
  9027. // If we corrected to an inheriting constructor, handle it as one.
  9028. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  9029. if (RD && RD->isInjectedClassName()) {
  9030. // The parent of the injected class name is the class itself.
  9031. RD = cast<CXXRecordDecl>(RD->getParent());
  9032. // Fix up the information we'll use to build the using declaration.
  9033. if (Corrected.WillReplaceSpecifier()) {
  9034. NestedNameSpecifierLocBuilder Builder;
  9035. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  9036. QualifierLoc.getSourceRange());
  9037. QualifierLoc = Builder.getWithLocInContext(Context);
  9038. }
  9039. // In this case, the name we introduce is the name of a derived class
  9040. // constructor.
  9041. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  9042. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  9043. Context.getCanonicalType(Context.getRecordType(CurClass))));
  9044. UsingName.setNamedTypeInfo(nullptr);
  9045. for (auto *Ctor : LookupConstructors(RD))
  9046. R.addDecl(Ctor);
  9047. R.resolveKind();
  9048. } else {
  9049. // FIXME: Pick up all the declarations if we found an overloaded
  9050. // function.
  9051. UsingName.setName(ND->getDeclName());
  9052. R.addDecl(ND);
  9053. }
  9054. } else {
  9055. Diag(IdentLoc, diag::err_no_member)
  9056. << NameInfo.getName() << LookupContext << SS.getRange();
  9057. return BuildInvalid();
  9058. }
  9059. }
  9060. if (R.isAmbiguous())
  9061. return BuildInvalid();
  9062. if (HasTypenameKeyword) {
  9063. // If we asked for a typename and got a non-type decl, error out.
  9064. if (!R.getAsSingle<TypeDecl>()) {
  9065. Diag(IdentLoc, diag::err_using_typename_non_type);
  9066. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9067. Diag((*I)->getUnderlyingDecl()->getLocation(),
  9068. diag::note_using_decl_target);
  9069. return BuildInvalid();
  9070. }
  9071. } else {
  9072. // If we asked for a non-typename and we got a type, error out,
  9073. // but only if this is an instantiation of an unresolved using
  9074. // decl. Otherwise just silently find the type name.
  9075. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  9076. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  9077. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  9078. return BuildInvalid();
  9079. }
  9080. }
  9081. // C++14 [namespace.udecl]p6:
  9082. // A using-declaration shall not name a namespace.
  9083. if (R.getAsSingle<NamespaceDecl>()) {
  9084. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  9085. << SS.getRange();
  9086. return BuildInvalid();
  9087. }
  9088. // C++14 [namespace.udecl]p7:
  9089. // A using-declaration shall not name a scoped enumerator.
  9090. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  9091. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  9092. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  9093. << SS.getRange();
  9094. return BuildInvalid();
  9095. }
  9096. }
  9097. UsingDecl *UD = BuildValid();
  9098. // Some additional rules apply to inheriting constructors.
  9099. if (UsingName.getName().getNameKind() ==
  9100. DeclarationName::CXXConstructorName) {
  9101. // Suppress access diagnostics; the access check is instead performed at the
  9102. // point of use for an inheriting constructor.
  9103. R.suppressDiagnostics();
  9104. if (CheckInheritingConstructorUsingDecl(UD))
  9105. return UD;
  9106. }
  9107. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  9108. UsingShadowDecl *PrevDecl = nullptr;
  9109. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  9110. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  9111. }
  9112. return UD;
  9113. }
  9114. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  9115. ArrayRef<NamedDecl *> Expansions) {
  9116. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  9117. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  9118. isa<UsingPackDecl>(InstantiatedFrom));
  9119. auto *UPD =
  9120. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  9121. UPD->setAccess(InstantiatedFrom->getAccess());
  9122. CurContext->addDecl(UPD);
  9123. return UPD;
  9124. }
  9125. /// Additional checks for a using declaration referring to a constructor name.
  9126. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  9127. assert(!UD->hasTypename() && "expecting a constructor name");
  9128. const Type *SourceType = UD->getQualifier()->getAsType();
  9129. assert(SourceType &&
  9130. "Using decl naming constructor doesn't have type in scope spec.");
  9131. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  9132. // Check whether the named type is a direct base class.
  9133. bool AnyDependentBases = false;
  9134. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  9135. AnyDependentBases);
  9136. if (!Base && !AnyDependentBases) {
  9137. Diag(UD->getUsingLoc(),
  9138. diag::err_using_decl_constructor_not_in_direct_base)
  9139. << UD->getNameInfo().getSourceRange()
  9140. << QualType(SourceType, 0) << TargetClass;
  9141. UD->setInvalidDecl();
  9142. return true;
  9143. }
  9144. if (Base)
  9145. Base->setInheritConstructors();
  9146. return false;
  9147. }
  9148. /// Checks that the given using declaration is not an invalid
  9149. /// redeclaration. Note that this is checking only for the using decl
  9150. /// itself, not for any ill-formedness among the UsingShadowDecls.
  9151. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  9152. bool HasTypenameKeyword,
  9153. const CXXScopeSpec &SS,
  9154. SourceLocation NameLoc,
  9155. const LookupResult &Prev) {
  9156. NestedNameSpecifier *Qual = SS.getScopeRep();
  9157. // C++03 [namespace.udecl]p8:
  9158. // C++0x [namespace.udecl]p10:
  9159. // A using-declaration is a declaration and can therefore be used
  9160. // repeatedly where (and only where) multiple declarations are
  9161. // allowed.
  9162. //
  9163. // That's in non-member contexts.
  9164. if (!CurContext->getRedeclContext()->isRecord()) {
  9165. // A dependent qualifier outside a class can only ever resolve to an
  9166. // enumeration type. Therefore it conflicts with any other non-type
  9167. // declaration in the same scope.
  9168. // FIXME: How should we check for dependent type-type conflicts at block
  9169. // scope?
  9170. if (Qual->isDependent() && !HasTypenameKeyword) {
  9171. for (auto *D : Prev) {
  9172. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  9173. bool OldCouldBeEnumerator =
  9174. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  9175. Diag(NameLoc,
  9176. OldCouldBeEnumerator ? diag::err_redefinition
  9177. : diag::err_redefinition_different_kind)
  9178. << Prev.getLookupName();
  9179. Diag(D->getLocation(), diag::note_previous_definition);
  9180. return true;
  9181. }
  9182. }
  9183. }
  9184. return false;
  9185. }
  9186. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  9187. NamedDecl *D = *I;
  9188. bool DTypename;
  9189. NestedNameSpecifier *DQual;
  9190. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  9191. DTypename = UD->hasTypename();
  9192. DQual = UD->getQualifier();
  9193. } else if (UnresolvedUsingValueDecl *UD
  9194. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  9195. DTypename = false;
  9196. DQual = UD->getQualifier();
  9197. } else if (UnresolvedUsingTypenameDecl *UD
  9198. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  9199. DTypename = true;
  9200. DQual = UD->getQualifier();
  9201. } else continue;
  9202. // using decls differ if one says 'typename' and the other doesn't.
  9203. // FIXME: non-dependent using decls?
  9204. if (HasTypenameKeyword != DTypename) continue;
  9205. // using decls differ if they name different scopes (but note that
  9206. // template instantiation can cause this check to trigger when it
  9207. // didn't before instantiation).
  9208. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  9209. Context.getCanonicalNestedNameSpecifier(DQual))
  9210. continue;
  9211. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  9212. Diag(D->getLocation(), diag::note_using_decl) << 1;
  9213. return true;
  9214. }
  9215. return false;
  9216. }
  9217. /// Checks that the given nested-name qualifier used in a using decl
  9218. /// in the current context is appropriately related to the current
  9219. /// scope. If an error is found, diagnoses it and returns true.
  9220. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  9221. bool HasTypename,
  9222. const CXXScopeSpec &SS,
  9223. const DeclarationNameInfo &NameInfo,
  9224. SourceLocation NameLoc) {
  9225. DeclContext *NamedContext = computeDeclContext(SS);
  9226. if (!CurContext->isRecord()) {
  9227. // C++03 [namespace.udecl]p3:
  9228. // C++0x [namespace.udecl]p8:
  9229. // A using-declaration for a class member shall be a member-declaration.
  9230. // If we weren't able to compute a valid scope, it might validly be a
  9231. // dependent class scope or a dependent enumeration unscoped scope. If
  9232. // we have a 'typename' keyword, the scope must resolve to a class type.
  9233. if ((HasTypename && !NamedContext) ||
  9234. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  9235. auto *RD = NamedContext
  9236. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  9237. : nullptr;
  9238. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  9239. RD = nullptr;
  9240. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  9241. << SS.getRange();
  9242. // If we have a complete, non-dependent source type, try to suggest a
  9243. // way to get the same effect.
  9244. if (!RD)
  9245. return true;
  9246. // Find what this using-declaration was referring to.
  9247. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  9248. R.setHideTags(false);
  9249. R.suppressDiagnostics();
  9250. LookupQualifiedName(R, RD);
  9251. if (R.getAsSingle<TypeDecl>()) {
  9252. if (getLangOpts().CPlusPlus11) {
  9253. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  9254. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  9255. << 0 // alias declaration
  9256. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  9257. NameInfo.getName().getAsString() +
  9258. " = ");
  9259. } else {
  9260. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  9261. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  9262. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  9263. << 1 // typedef declaration
  9264. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  9265. << FixItHint::CreateInsertion(
  9266. InsertLoc, " " + NameInfo.getName().getAsString());
  9267. }
  9268. } else if (R.getAsSingle<VarDecl>()) {
  9269. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9270. // repeating the type of the static data member here.
  9271. FixItHint FixIt;
  9272. if (getLangOpts().CPlusPlus11) {
  9273. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9274. FixIt = FixItHint::CreateReplacement(
  9275. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  9276. }
  9277. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9278. << 2 // reference declaration
  9279. << FixIt;
  9280. } else if (R.getAsSingle<EnumConstantDecl>()) {
  9281. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9282. // repeating the type of the enumeration here, and we can't do so if
  9283. // the type is anonymous.
  9284. FixItHint FixIt;
  9285. if (getLangOpts().CPlusPlus11) {
  9286. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9287. FixIt = FixItHint::CreateReplacement(
  9288. UsingLoc,
  9289. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  9290. }
  9291. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9292. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  9293. << FixIt;
  9294. }
  9295. return true;
  9296. }
  9297. // Otherwise, this might be valid.
  9298. return false;
  9299. }
  9300. // The current scope is a record.
  9301. // If the named context is dependent, we can't decide much.
  9302. if (!NamedContext) {
  9303. // FIXME: in C++0x, we can diagnose if we can prove that the
  9304. // nested-name-specifier does not refer to a base class, which is
  9305. // still possible in some cases.
  9306. // Otherwise we have to conservatively report that things might be
  9307. // okay.
  9308. return false;
  9309. }
  9310. if (!NamedContext->isRecord()) {
  9311. // Ideally this would point at the last name in the specifier,
  9312. // but we don't have that level of source info.
  9313. Diag(SS.getRange().getBegin(),
  9314. diag::err_using_decl_nested_name_specifier_is_not_class)
  9315. << SS.getScopeRep() << SS.getRange();
  9316. return true;
  9317. }
  9318. if (!NamedContext->isDependentContext() &&
  9319. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  9320. return true;
  9321. if (getLangOpts().CPlusPlus11) {
  9322. // C++11 [namespace.udecl]p3:
  9323. // In a using-declaration used as a member-declaration, the
  9324. // nested-name-specifier shall name a base class of the class
  9325. // being defined.
  9326. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  9327. cast<CXXRecordDecl>(NamedContext))) {
  9328. if (CurContext == NamedContext) {
  9329. Diag(NameLoc,
  9330. diag::err_using_decl_nested_name_specifier_is_current_class)
  9331. << SS.getRange();
  9332. return true;
  9333. }
  9334. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9335. Diag(SS.getRange().getBegin(),
  9336. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9337. << SS.getScopeRep()
  9338. << cast<CXXRecordDecl>(CurContext)
  9339. << SS.getRange();
  9340. }
  9341. return true;
  9342. }
  9343. return false;
  9344. }
  9345. // C++03 [namespace.udecl]p4:
  9346. // A using-declaration used as a member-declaration shall refer
  9347. // to a member of a base class of the class being defined [etc.].
  9348. // Salient point: SS doesn't have to name a base class as long as
  9349. // lookup only finds members from base classes. Therefore we can
  9350. // diagnose here only if we can prove that that can't happen,
  9351. // i.e. if the class hierarchies provably don't intersect.
  9352. // TODO: it would be nice if "definitely valid" results were cached
  9353. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9354. // need to be repeated.
  9355. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9356. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9357. Bases.insert(Base);
  9358. return true;
  9359. };
  9360. // Collect all bases. Return false if we find a dependent base.
  9361. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9362. return false;
  9363. // Returns true if the base is dependent or is one of the accumulated base
  9364. // classes.
  9365. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9366. return !Bases.count(Base);
  9367. };
  9368. // Return false if the class has a dependent base or if it or one
  9369. // of its bases is present in the base set of the current context.
  9370. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9371. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9372. return false;
  9373. Diag(SS.getRange().getBegin(),
  9374. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9375. << SS.getScopeRep()
  9376. << cast<CXXRecordDecl>(CurContext)
  9377. << SS.getRange();
  9378. return true;
  9379. }
  9380. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9381. MultiTemplateParamsArg TemplateParamLists,
  9382. SourceLocation UsingLoc, UnqualifiedId &Name,
  9383. const ParsedAttributesView &AttrList,
  9384. TypeResult Type, Decl *DeclFromDeclSpec) {
  9385. // Skip up to the relevant declaration scope.
  9386. while (S->isTemplateParamScope())
  9387. S = S->getParent();
  9388. assert((S->getFlags() & Scope::DeclScope) &&
  9389. "got alias-declaration outside of declaration scope");
  9390. if (Type.isInvalid())
  9391. return nullptr;
  9392. bool Invalid = false;
  9393. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9394. TypeSourceInfo *TInfo = nullptr;
  9395. GetTypeFromParser(Type.get(), &TInfo);
  9396. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9397. return nullptr;
  9398. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9399. UPPC_DeclarationType)) {
  9400. Invalid = true;
  9401. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9402. TInfo->getTypeLoc().getBeginLoc());
  9403. }
  9404. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9405. TemplateParamLists.size()
  9406. ? forRedeclarationInCurContext()
  9407. : ForVisibleRedeclaration);
  9408. LookupName(Previous, S);
  9409. // Warn about shadowing the name of a template parameter.
  9410. if (Previous.isSingleResult() &&
  9411. Previous.getFoundDecl()->isTemplateParameter()) {
  9412. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9413. Previous.clear();
  9414. }
  9415. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9416. "name in alias declaration must be an identifier");
  9417. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9418. Name.StartLocation,
  9419. Name.Identifier, TInfo);
  9420. NewTD->setAccess(AS);
  9421. if (Invalid)
  9422. NewTD->setInvalidDecl();
  9423. ProcessDeclAttributeList(S, NewTD, AttrList);
  9424. AddPragmaAttributes(S, NewTD);
  9425. CheckTypedefForVariablyModifiedType(S, NewTD);
  9426. Invalid |= NewTD->isInvalidDecl();
  9427. bool Redeclaration = false;
  9428. NamedDecl *NewND;
  9429. if (TemplateParamLists.size()) {
  9430. TypeAliasTemplateDecl *OldDecl = nullptr;
  9431. TemplateParameterList *OldTemplateParams = nullptr;
  9432. if (TemplateParamLists.size() != 1) {
  9433. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9434. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9435. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9436. }
  9437. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9438. // Check that we can declare a template here.
  9439. if (CheckTemplateDeclScope(S, TemplateParams))
  9440. return nullptr;
  9441. // Only consider previous declarations in the same scope.
  9442. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9443. /*ExplicitInstantiationOrSpecialization*/false);
  9444. if (!Previous.empty()) {
  9445. Redeclaration = true;
  9446. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9447. if (!OldDecl && !Invalid) {
  9448. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9449. << Name.Identifier;
  9450. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9451. if (OldD->getLocation().isValid())
  9452. Diag(OldD->getLocation(), diag::note_previous_definition);
  9453. Invalid = true;
  9454. }
  9455. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9456. if (TemplateParameterListsAreEqual(TemplateParams,
  9457. OldDecl->getTemplateParameters(),
  9458. /*Complain=*/true,
  9459. TPL_TemplateMatch))
  9460. OldTemplateParams =
  9461. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9462. else
  9463. Invalid = true;
  9464. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9465. if (!Invalid &&
  9466. !Context.hasSameType(OldTD->getUnderlyingType(),
  9467. NewTD->getUnderlyingType())) {
  9468. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9469. // but we can't reasonably accept it.
  9470. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9471. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9472. if (OldTD->getLocation().isValid())
  9473. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9474. Invalid = true;
  9475. }
  9476. }
  9477. }
  9478. // Merge any previous default template arguments into our parameters,
  9479. // and check the parameter list.
  9480. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9481. TPC_TypeAliasTemplate))
  9482. return nullptr;
  9483. TypeAliasTemplateDecl *NewDecl =
  9484. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9485. Name.Identifier, TemplateParams,
  9486. NewTD);
  9487. NewTD->setDescribedAliasTemplate(NewDecl);
  9488. NewDecl->setAccess(AS);
  9489. if (Invalid)
  9490. NewDecl->setInvalidDecl();
  9491. else if (OldDecl) {
  9492. NewDecl->setPreviousDecl(OldDecl);
  9493. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9494. }
  9495. NewND = NewDecl;
  9496. } else {
  9497. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9498. setTagNameForLinkagePurposes(TD, NewTD);
  9499. handleTagNumbering(TD, S);
  9500. }
  9501. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9502. NewND = NewTD;
  9503. }
  9504. PushOnScopeChains(NewND, S);
  9505. ActOnDocumentableDecl(NewND);
  9506. return NewND;
  9507. }
  9508. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9509. SourceLocation AliasLoc,
  9510. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9511. SourceLocation IdentLoc,
  9512. IdentifierInfo *Ident) {
  9513. // Lookup the namespace name.
  9514. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9515. LookupParsedName(R, S, &SS);
  9516. if (R.isAmbiguous())
  9517. return nullptr;
  9518. if (R.empty()) {
  9519. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9520. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9521. return nullptr;
  9522. }
  9523. }
  9524. assert(!R.isAmbiguous() && !R.empty());
  9525. NamedDecl *ND = R.getRepresentativeDecl();
  9526. // Check if we have a previous declaration with the same name.
  9527. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9528. ForVisibleRedeclaration);
  9529. LookupName(PrevR, S);
  9530. // Check we're not shadowing a template parameter.
  9531. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9532. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9533. PrevR.clear();
  9534. }
  9535. // Filter out any other lookup result from an enclosing scope.
  9536. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9537. /*AllowInlineNamespace*/false);
  9538. // Find the previous declaration and check that we can redeclare it.
  9539. NamespaceAliasDecl *Prev = nullptr;
  9540. if (PrevR.isSingleResult()) {
  9541. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9542. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9543. // We already have an alias with the same name that points to the same
  9544. // namespace; check that it matches.
  9545. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9546. Prev = AD;
  9547. } else if (isVisible(PrevDecl)) {
  9548. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9549. << Alias;
  9550. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9551. << AD->getNamespace();
  9552. return nullptr;
  9553. }
  9554. } else if (isVisible(PrevDecl)) {
  9555. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9556. ? diag::err_redefinition
  9557. : diag::err_redefinition_different_kind;
  9558. Diag(AliasLoc, DiagID) << Alias;
  9559. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9560. return nullptr;
  9561. }
  9562. }
  9563. // The use of a nested name specifier may trigger deprecation warnings.
  9564. DiagnoseUseOfDecl(ND, IdentLoc);
  9565. NamespaceAliasDecl *AliasDecl =
  9566. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9567. Alias, SS.getWithLocInContext(Context),
  9568. IdentLoc, ND);
  9569. if (Prev)
  9570. AliasDecl->setPreviousDecl(Prev);
  9571. PushOnScopeChains(AliasDecl, S);
  9572. return AliasDecl;
  9573. }
  9574. namespace {
  9575. struct SpecialMemberExceptionSpecInfo
  9576. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9577. SourceLocation Loc;
  9578. Sema::ImplicitExceptionSpecification ExceptSpec;
  9579. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9580. Sema::CXXSpecialMember CSM,
  9581. Sema::InheritedConstructorInfo *ICI,
  9582. SourceLocation Loc)
  9583. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9584. bool visitBase(CXXBaseSpecifier *Base);
  9585. bool visitField(FieldDecl *FD);
  9586. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9587. unsigned Quals);
  9588. void visitSubobjectCall(Subobject Subobj,
  9589. Sema::SpecialMemberOverloadResult SMOR);
  9590. };
  9591. }
  9592. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9593. auto *RT = Base->getType()->getAs<RecordType>();
  9594. if (!RT)
  9595. return false;
  9596. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9597. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9598. if (auto *BaseCtor = SMOR.getMethod()) {
  9599. visitSubobjectCall(Base, BaseCtor);
  9600. return false;
  9601. }
  9602. visitClassSubobject(BaseClass, Base, 0);
  9603. return false;
  9604. }
  9605. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9606. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9607. Expr *E = FD->getInClassInitializer();
  9608. if (!E)
  9609. // FIXME: It's a little wasteful to build and throw away a
  9610. // CXXDefaultInitExpr here.
  9611. // FIXME: We should have a single context note pointing at Loc, and
  9612. // this location should be MD->getLocation() instead, since that's
  9613. // the location where we actually use the default init expression.
  9614. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9615. if (E)
  9616. ExceptSpec.CalledExpr(E);
  9617. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9618. ->getAs<RecordType>()) {
  9619. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9620. FD->getType().getCVRQualifiers());
  9621. }
  9622. return false;
  9623. }
  9624. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9625. Subobject Subobj,
  9626. unsigned Quals) {
  9627. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9628. bool IsMutable = Field && Field->isMutable();
  9629. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9630. }
  9631. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9632. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9633. // Note, if lookup fails, it doesn't matter what exception specification we
  9634. // choose because the special member will be deleted.
  9635. if (CXXMethodDecl *MD = SMOR.getMethod())
  9636. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9637. }
  9638. namespace {
  9639. /// RAII object to register a special member as being currently declared.
  9640. struct ComputingExceptionSpec {
  9641. Sema &S;
  9642. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9643. : S(S) {
  9644. Sema::CodeSynthesisContext Ctx;
  9645. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9646. Ctx.PointOfInstantiation = Loc;
  9647. Ctx.Entity = MD;
  9648. S.pushCodeSynthesisContext(Ctx);
  9649. }
  9650. ~ComputingExceptionSpec() {
  9651. S.popCodeSynthesisContext();
  9652. }
  9653. };
  9654. }
  9655. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  9656. llvm::APSInt Result;
  9657. ExprResult Converted = CheckConvertedConstantExpression(
  9658. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  9659. ExplicitSpec.setExpr(Converted.get());
  9660. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  9661. ExplicitSpec.setKind(Result.getBoolValue()
  9662. ? ExplicitSpecKind::ResolvedTrue
  9663. : ExplicitSpecKind::ResolvedFalse);
  9664. return true;
  9665. }
  9666. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  9667. return false;
  9668. }
  9669. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  9670. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  9671. if (!ExplicitExpr->isTypeDependent())
  9672. tryResolveExplicitSpecifier(ES);
  9673. return ES;
  9674. }
  9675. static Sema::ImplicitExceptionSpecification
  9676. ComputeDefaultedSpecialMemberExceptionSpec(
  9677. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9678. Sema::InheritedConstructorInfo *ICI) {
  9679. ComputingExceptionSpec CES(S, MD, Loc);
  9680. CXXRecordDecl *ClassDecl = MD->getParent();
  9681. // C++ [except.spec]p14:
  9682. // An implicitly declared special member function (Clause 12) shall have an
  9683. // exception-specification. [...]
  9684. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9685. if (ClassDecl->isInvalidDecl())
  9686. return Info.ExceptSpec;
  9687. // FIXME: If this diagnostic fires, we're probably missing a check for
  9688. // attempting to resolve an exception specification before it's known
  9689. // at a higher level.
  9690. if (S.RequireCompleteType(MD->getLocation(),
  9691. S.Context.getRecordType(ClassDecl),
  9692. diag::err_exception_spec_incomplete_type))
  9693. return Info.ExceptSpec;
  9694. // C++1z [except.spec]p7:
  9695. // [Look for exceptions thrown by] a constructor selected [...] to
  9696. // initialize a potentially constructed subobject,
  9697. // C++1z [except.spec]p8:
  9698. // The exception specification for an implicitly-declared destructor, or a
  9699. // destructor without a noexcept-specifier, is potentially-throwing if and
  9700. // only if any of the destructors for any of its potentially constructed
  9701. // subojects is potentially throwing.
  9702. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9703. // in the second rule to resolve a core issue (no number yet) that would have
  9704. // us reject:
  9705. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9706. // struct B : A {};
  9707. // struct C : B { void f(); };
  9708. // ... due to giving B::~B() a non-throwing exception specification.
  9709. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9710. : Info.VisitAllBases);
  9711. return Info.ExceptSpec;
  9712. }
  9713. namespace {
  9714. /// RAII object to register a special member as being currently declared.
  9715. struct DeclaringSpecialMember {
  9716. Sema &S;
  9717. Sema::SpecialMemberDecl D;
  9718. Sema::ContextRAII SavedContext;
  9719. bool WasAlreadyBeingDeclared;
  9720. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9721. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9722. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9723. if (WasAlreadyBeingDeclared)
  9724. // This almost never happens, but if it does, ensure that our cache
  9725. // doesn't contain a stale result.
  9726. S.SpecialMemberCache.clear();
  9727. else {
  9728. // Register a note to be produced if we encounter an error while
  9729. // declaring the special member.
  9730. Sema::CodeSynthesisContext Ctx;
  9731. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9732. // FIXME: We don't have a location to use here. Using the class's
  9733. // location maintains the fiction that we declare all special members
  9734. // with the class, but (1) it's not clear that lying about that helps our
  9735. // users understand what's going on, and (2) there may be outer contexts
  9736. // on the stack (some of which are relevant) and printing them exposes
  9737. // our lies.
  9738. Ctx.PointOfInstantiation = RD->getLocation();
  9739. Ctx.Entity = RD;
  9740. Ctx.SpecialMember = CSM;
  9741. S.pushCodeSynthesisContext(Ctx);
  9742. }
  9743. }
  9744. ~DeclaringSpecialMember() {
  9745. if (!WasAlreadyBeingDeclared) {
  9746. S.SpecialMembersBeingDeclared.erase(D);
  9747. S.popCodeSynthesisContext();
  9748. }
  9749. }
  9750. /// Are we already trying to declare this special member?
  9751. bool isAlreadyBeingDeclared() const {
  9752. return WasAlreadyBeingDeclared;
  9753. }
  9754. };
  9755. }
  9756. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9757. // Look up any existing declarations, but don't trigger declaration of all
  9758. // implicit special members with this name.
  9759. DeclarationName Name = FD->getDeclName();
  9760. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9761. ForExternalRedeclaration);
  9762. for (auto *D : FD->getParent()->lookup(Name))
  9763. if (auto *Acceptable = R.getAcceptableDecl(D))
  9764. R.addDecl(Acceptable);
  9765. R.resolveKind();
  9766. R.suppressDiagnostics();
  9767. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9768. }
  9769. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  9770. QualType ResultTy,
  9771. ArrayRef<QualType> Args) {
  9772. // Build an exception specification pointing back at this constructor.
  9773. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  9774. if (getLangOpts().OpenCLCPlusPlus) {
  9775. // OpenCL: Implicitly defaulted special member are of the generic address
  9776. // space.
  9777. EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
  9778. }
  9779. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  9780. SpecialMem->setType(QT);
  9781. }
  9782. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9783. CXXRecordDecl *ClassDecl) {
  9784. // C++ [class.ctor]p5:
  9785. // A default constructor for a class X is a constructor of class X
  9786. // that can be called without an argument. If there is no
  9787. // user-declared constructor for class X, a default constructor is
  9788. // implicitly declared. An implicitly-declared default constructor
  9789. // is an inline public member of its class.
  9790. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9791. "Should not build implicit default constructor!");
  9792. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9793. if (DSM.isAlreadyBeingDeclared())
  9794. return nullptr;
  9795. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9796. CXXDefaultConstructor,
  9797. false);
  9798. // Create the actual constructor declaration.
  9799. CanQualType ClassType
  9800. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9801. SourceLocation ClassLoc = ClassDecl->getLocation();
  9802. DeclarationName Name
  9803. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9804. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9805. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9806. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  9807. /*TInfo=*/nullptr, ExplicitSpecifier(),
  9808. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9809. Constexpr ? CSK_constexpr : CSK_unspecified);
  9810. DefaultCon->setAccess(AS_public);
  9811. DefaultCon->setDefaulted();
  9812. if (getLangOpts().CUDA) {
  9813. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9814. DefaultCon,
  9815. /* ConstRHS */ false,
  9816. /* Diagnose */ false);
  9817. }
  9818. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
  9819. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9820. // constructors is easy to compute.
  9821. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9822. // Note that we have declared this constructor.
  9823. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  9824. Scope *S = getScopeForContext(ClassDecl);
  9825. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9826. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9827. SetDeclDeleted(DefaultCon, ClassLoc);
  9828. if (S)
  9829. PushOnScopeChains(DefaultCon, S, false);
  9830. ClassDecl->addDecl(DefaultCon);
  9831. return DefaultCon;
  9832. }
  9833. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9834. CXXConstructorDecl *Constructor) {
  9835. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9836. !Constructor->doesThisDeclarationHaveABody() &&
  9837. !Constructor->isDeleted()) &&
  9838. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9839. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9840. return;
  9841. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9842. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9843. SynthesizedFunctionScope Scope(*this, Constructor);
  9844. // The exception specification is needed because we are defining the
  9845. // function.
  9846. ResolveExceptionSpec(CurrentLocation,
  9847. Constructor->getType()->castAs<FunctionProtoType>());
  9848. MarkVTableUsed(CurrentLocation, ClassDecl);
  9849. // Add a context note for diagnostics produced after this point.
  9850. Scope.addContextNote(CurrentLocation);
  9851. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9852. Constructor->setInvalidDecl();
  9853. return;
  9854. }
  9855. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9856. ? Constructor->getEndLoc()
  9857. : Constructor->getLocation();
  9858. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9859. Constructor->markUsed(Context);
  9860. if (ASTMutationListener *L = getASTMutationListener()) {
  9861. L->CompletedImplicitDefinition(Constructor);
  9862. }
  9863. DiagnoseUninitializedFields(*this, Constructor);
  9864. }
  9865. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9866. // Perform any delayed checks on exception specifications.
  9867. CheckDelayedMemberExceptionSpecs();
  9868. }
  9869. /// Find or create the fake constructor we synthesize to model constructing an
  9870. /// object of a derived class via a constructor of a base class.
  9871. CXXConstructorDecl *
  9872. Sema::findInheritingConstructor(SourceLocation Loc,
  9873. CXXConstructorDecl *BaseCtor,
  9874. ConstructorUsingShadowDecl *Shadow) {
  9875. CXXRecordDecl *Derived = Shadow->getParent();
  9876. SourceLocation UsingLoc = Shadow->getLocation();
  9877. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9878. // For now we use the name of the base class constructor as a member of the
  9879. // derived class to indicate a (fake) inherited constructor name.
  9880. DeclarationName Name = BaseCtor->getDeclName();
  9881. // Check to see if we already have a fake constructor for this inherited
  9882. // constructor call.
  9883. for (NamedDecl *Ctor : Derived->lookup(Name))
  9884. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9885. ->getInheritedConstructor()
  9886. .getConstructor(),
  9887. BaseCtor))
  9888. return cast<CXXConstructorDecl>(Ctor);
  9889. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9890. TypeSourceInfo *TInfo =
  9891. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9892. FunctionProtoTypeLoc ProtoLoc =
  9893. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9894. // Check the inherited constructor is valid and find the list of base classes
  9895. // from which it was inherited.
  9896. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9897. bool Constexpr =
  9898. BaseCtor->isConstexpr() &&
  9899. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9900. false, BaseCtor, &ICI);
  9901. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9902. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9903. BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
  9904. /*isImplicitlyDeclared=*/true,
  9905. Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
  9906. InheritedConstructor(Shadow, BaseCtor));
  9907. if (Shadow->isInvalidDecl())
  9908. DerivedCtor->setInvalidDecl();
  9909. // Build an unevaluated exception specification for this fake constructor.
  9910. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9911. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9912. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9913. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9914. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9915. FPT->getParamTypes(), EPI));
  9916. // Build the parameter declarations.
  9917. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9918. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9919. TypeSourceInfo *TInfo =
  9920. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9921. ParmVarDecl *PD = ParmVarDecl::Create(
  9922. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9923. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  9924. PD->setScopeInfo(0, I);
  9925. PD->setImplicit();
  9926. // Ensure attributes are propagated onto parameters (this matters for
  9927. // format, pass_object_size, ...).
  9928. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9929. ParamDecls.push_back(PD);
  9930. ProtoLoc.setParam(I, PD);
  9931. }
  9932. // Set up the new constructor.
  9933. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9934. DerivedCtor->setAccess(BaseCtor->getAccess());
  9935. DerivedCtor->setParams(ParamDecls);
  9936. Derived->addDecl(DerivedCtor);
  9937. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9938. SetDeclDeleted(DerivedCtor, UsingLoc);
  9939. return DerivedCtor;
  9940. }
  9941. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9942. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9943. Ctor->getInheritedConstructor().getShadowDecl());
  9944. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9945. /*Diagnose*/true);
  9946. }
  9947. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9948. CXXConstructorDecl *Constructor) {
  9949. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9950. assert(Constructor->getInheritedConstructor() &&
  9951. !Constructor->doesThisDeclarationHaveABody() &&
  9952. !Constructor->isDeleted());
  9953. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9954. return;
  9955. // Initializations are performed "as if by a defaulted default constructor",
  9956. // so enter the appropriate scope.
  9957. SynthesizedFunctionScope Scope(*this, Constructor);
  9958. // The exception specification is needed because we are defining the
  9959. // function.
  9960. ResolveExceptionSpec(CurrentLocation,
  9961. Constructor->getType()->castAs<FunctionProtoType>());
  9962. MarkVTableUsed(CurrentLocation, ClassDecl);
  9963. // Add a context note for diagnostics produced after this point.
  9964. Scope.addContextNote(CurrentLocation);
  9965. ConstructorUsingShadowDecl *Shadow =
  9966. Constructor->getInheritedConstructor().getShadowDecl();
  9967. CXXConstructorDecl *InheritedCtor =
  9968. Constructor->getInheritedConstructor().getConstructor();
  9969. // [class.inhctor.init]p1:
  9970. // initialization proceeds as if a defaulted default constructor is used to
  9971. // initialize the D object and each base class subobject from which the
  9972. // constructor was inherited
  9973. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9974. CXXRecordDecl *RD = Shadow->getParent();
  9975. SourceLocation InitLoc = Shadow->getLocation();
  9976. // Build explicit initializers for all base classes from which the
  9977. // constructor was inherited.
  9978. SmallVector<CXXCtorInitializer*, 8> Inits;
  9979. for (bool VBase : {false, true}) {
  9980. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9981. if (B.isVirtual() != VBase)
  9982. continue;
  9983. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9984. if (!BaseRD)
  9985. continue;
  9986. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9987. if (!BaseCtor.first)
  9988. continue;
  9989. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9990. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9991. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9992. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9993. Inits.push_back(new (Context) CXXCtorInitializer(
  9994. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9995. SourceLocation()));
  9996. }
  9997. }
  9998. // We now proceed as if for a defaulted default constructor, with the relevant
  9999. // initializers replaced.
  10000. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  10001. Constructor->setInvalidDecl();
  10002. return;
  10003. }
  10004. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  10005. Constructor->markUsed(Context);
  10006. if (ASTMutationListener *L = getASTMutationListener()) {
  10007. L->CompletedImplicitDefinition(Constructor);
  10008. }
  10009. DiagnoseUninitializedFields(*this, Constructor);
  10010. }
  10011. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  10012. // C++ [class.dtor]p2:
  10013. // If a class has no user-declared destructor, a destructor is
  10014. // declared implicitly. An implicitly-declared destructor is an
  10015. // inline public member of its class.
  10016. assert(ClassDecl->needsImplicitDestructor());
  10017. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  10018. if (DSM.isAlreadyBeingDeclared())
  10019. return nullptr;
  10020. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10021. CXXDestructor,
  10022. false);
  10023. // Create the actual destructor declaration.
  10024. CanQualType ClassType
  10025. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  10026. SourceLocation ClassLoc = ClassDecl->getLocation();
  10027. DeclarationName Name
  10028. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  10029. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10030. CXXDestructorDecl *Destructor =
  10031. CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  10032. QualType(), nullptr, /*isInline=*/true,
  10033. /*isImplicitlyDeclared=*/true,
  10034. Constexpr ? CSK_constexpr : CSK_unspecified);
  10035. Destructor->setAccess(AS_public);
  10036. Destructor->setDefaulted();
  10037. if (getLangOpts().CUDA) {
  10038. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  10039. Destructor,
  10040. /* ConstRHS */ false,
  10041. /* Diagnose */ false);
  10042. }
  10043. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
  10044. // We don't need to use SpecialMemberIsTrivial here; triviality for
  10045. // destructors is easy to compute.
  10046. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  10047. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  10048. ClassDecl->hasTrivialDestructorForCall());
  10049. // Note that we have declared this destructor.
  10050. ++getASTContext().NumImplicitDestructorsDeclared;
  10051. Scope *S = getScopeForContext(ClassDecl);
  10052. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  10053. // We can't check whether an implicit destructor is deleted before we complete
  10054. // the definition of the class, because its validity depends on the alignment
  10055. // of the class. We'll check this from ActOnFields once the class is complete.
  10056. if (ClassDecl->isCompleteDefinition() &&
  10057. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  10058. SetDeclDeleted(Destructor, ClassLoc);
  10059. // Introduce this destructor into its scope.
  10060. if (S)
  10061. PushOnScopeChains(Destructor, S, false);
  10062. ClassDecl->addDecl(Destructor);
  10063. return Destructor;
  10064. }
  10065. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  10066. CXXDestructorDecl *Destructor) {
  10067. assert((Destructor->isDefaulted() &&
  10068. !Destructor->doesThisDeclarationHaveABody() &&
  10069. !Destructor->isDeleted()) &&
  10070. "DefineImplicitDestructor - call it for implicit default dtor");
  10071. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  10072. return;
  10073. CXXRecordDecl *ClassDecl = Destructor->getParent();
  10074. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  10075. SynthesizedFunctionScope Scope(*this, Destructor);
  10076. // The exception specification is needed because we are defining the
  10077. // function.
  10078. ResolveExceptionSpec(CurrentLocation,
  10079. Destructor->getType()->castAs<FunctionProtoType>());
  10080. MarkVTableUsed(CurrentLocation, ClassDecl);
  10081. // Add a context note for diagnostics produced after this point.
  10082. Scope.addContextNote(CurrentLocation);
  10083. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  10084. Destructor->getParent());
  10085. if (CheckDestructor(Destructor)) {
  10086. Destructor->setInvalidDecl();
  10087. return;
  10088. }
  10089. SourceLocation Loc = Destructor->getEndLoc().isValid()
  10090. ? Destructor->getEndLoc()
  10091. : Destructor->getLocation();
  10092. Destructor->setBody(new (Context) CompoundStmt(Loc));
  10093. Destructor->markUsed(Context);
  10094. if (ASTMutationListener *L = getASTMutationListener()) {
  10095. L->CompletedImplicitDefinition(Destructor);
  10096. }
  10097. }
  10098. /// Perform any semantic analysis which needs to be delayed until all
  10099. /// pending class member declarations have been parsed.
  10100. void Sema::ActOnFinishCXXMemberDecls() {
  10101. // If the context is an invalid C++ class, just suppress these checks.
  10102. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  10103. if (Record->isInvalidDecl()) {
  10104. DelayedOverridingExceptionSpecChecks.clear();
  10105. DelayedEquivalentExceptionSpecChecks.clear();
  10106. return;
  10107. }
  10108. checkForMultipleExportedDefaultConstructors(*this, Record);
  10109. }
  10110. }
  10111. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  10112. referenceDLLExportedClassMethods();
  10113. if (!DelayedDllExportMemberFunctions.empty()) {
  10114. SmallVector<CXXMethodDecl*, 4> WorkList;
  10115. std::swap(DelayedDllExportMemberFunctions, WorkList);
  10116. for (CXXMethodDecl *M : WorkList) {
  10117. DefineImplicitSpecialMember(*this, M, M->getLocation());
  10118. // Pass the method to the consumer to get emitted. This is not necessary
  10119. // for explicit instantiation definitions, as they will get emitted
  10120. // anyway.
  10121. if (M->getParent()->getTemplateSpecializationKind() !=
  10122. TSK_ExplicitInstantiationDefinition)
  10123. ActOnFinishInlineFunctionDef(M);
  10124. }
  10125. }
  10126. }
  10127. void Sema::referenceDLLExportedClassMethods() {
  10128. if (!DelayedDllExportClasses.empty()) {
  10129. // Calling ReferenceDllExportedMembers might cause the current function to
  10130. // be called again, so use a local copy of DelayedDllExportClasses.
  10131. SmallVector<CXXRecordDecl *, 4> WorkList;
  10132. std::swap(DelayedDllExportClasses, WorkList);
  10133. for (CXXRecordDecl *Class : WorkList)
  10134. ReferenceDllExportedMembers(*this, Class);
  10135. }
  10136. }
  10137. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  10138. assert(getLangOpts().CPlusPlus11 &&
  10139. "adjusting dtor exception specs was introduced in c++11");
  10140. if (Destructor->isDependentContext())
  10141. return;
  10142. // C++11 [class.dtor]p3:
  10143. // A declaration of a destructor that does not have an exception-
  10144. // specification is implicitly considered to have the same exception-
  10145. // specification as an implicit declaration.
  10146. const FunctionProtoType *DtorType = Destructor->getType()->
  10147. getAs<FunctionProtoType>();
  10148. if (DtorType->hasExceptionSpec())
  10149. return;
  10150. // Replace the destructor's type, building off the existing one. Fortunately,
  10151. // the only thing of interest in the destructor type is its extended info.
  10152. // The return and arguments are fixed.
  10153. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  10154. EPI.ExceptionSpec.Type = EST_Unevaluated;
  10155. EPI.ExceptionSpec.SourceDecl = Destructor;
  10156. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  10157. // FIXME: If the destructor has a body that could throw, and the newly created
  10158. // spec doesn't allow exceptions, we should emit a warning, because this
  10159. // change in behavior can break conforming C++03 programs at runtime.
  10160. // However, we don't have a body or an exception specification yet, so it
  10161. // needs to be done somewhere else.
  10162. }
  10163. namespace {
  10164. /// An abstract base class for all helper classes used in building the
  10165. // copy/move operators. These classes serve as factory functions and help us
  10166. // avoid using the same Expr* in the AST twice.
  10167. class ExprBuilder {
  10168. ExprBuilder(const ExprBuilder&) = delete;
  10169. ExprBuilder &operator=(const ExprBuilder&) = delete;
  10170. protected:
  10171. static Expr *assertNotNull(Expr *E) {
  10172. assert(E && "Expression construction must not fail.");
  10173. return E;
  10174. }
  10175. public:
  10176. ExprBuilder() {}
  10177. virtual ~ExprBuilder() {}
  10178. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  10179. };
  10180. class RefBuilder: public ExprBuilder {
  10181. VarDecl *Var;
  10182. QualType VarType;
  10183. public:
  10184. Expr *build(Sema &S, SourceLocation Loc) const override {
  10185. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  10186. }
  10187. RefBuilder(VarDecl *Var, QualType VarType)
  10188. : Var(Var), VarType(VarType) {}
  10189. };
  10190. class ThisBuilder: public ExprBuilder {
  10191. public:
  10192. Expr *build(Sema &S, SourceLocation Loc) const override {
  10193. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  10194. }
  10195. };
  10196. class CastBuilder: public ExprBuilder {
  10197. const ExprBuilder &Builder;
  10198. QualType Type;
  10199. ExprValueKind Kind;
  10200. const CXXCastPath &Path;
  10201. public:
  10202. Expr *build(Sema &S, SourceLocation Loc) const override {
  10203. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  10204. CK_UncheckedDerivedToBase, Kind,
  10205. &Path).get());
  10206. }
  10207. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  10208. const CXXCastPath &Path)
  10209. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  10210. };
  10211. class DerefBuilder: public ExprBuilder {
  10212. const ExprBuilder &Builder;
  10213. public:
  10214. Expr *build(Sema &S, SourceLocation Loc) const override {
  10215. return assertNotNull(
  10216. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  10217. }
  10218. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10219. };
  10220. class MemberBuilder: public ExprBuilder {
  10221. const ExprBuilder &Builder;
  10222. QualType Type;
  10223. CXXScopeSpec SS;
  10224. bool IsArrow;
  10225. LookupResult &MemberLookup;
  10226. public:
  10227. Expr *build(Sema &S, SourceLocation Loc) const override {
  10228. return assertNotNull(S.BuildMemberReferenceExpr(
  10229. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  10230. nullptr, MemberLookup, nullptr, nullptr).get());
  10231. }
  10232. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  10233. LookupResult &MemberLookup)
  10234. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  10235. MemberLookup(MemberLookup) {}
  10236. };
  10237. class MoveCastBuilder: public ExprBuilder {
  10238. const ExprBuilder &Builder;
  10239. public:
  10240. Expr *build(Sema &S, SourceLocation Loc) const override {
  10241. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  10242. }
  10243. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10244. };
  10245. class LvalueConvBuilder: public ExprBuilder {
  10246. const ExprBuilder &Builder;
  10247. public:
  10248. Expr *build(Sema &S, SourceLocation Loc) const override {
  10249. return assertNotNull(
  10250. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  10251. }
  10252. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10253. };
  10254. class SubscriptBuilder: public ExprBuilder {
  10255. const ExprBuilder &Base;
  10256. const ExprBuilder &Index;
  10257. public:
  10258. Expr *build(Sema &S, SourceLocation Loc) const override {
  10259. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  10260. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  10261. }
  10262. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  10263. : Base(Base), Index(Index) {}
  10264. };
  10265. } // end anonymous namespace
  10266. /// When generating a defaulted copy or move assignment operator, if a field
  10267. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  10268. /// do so. This optimization only applies for arrays of scalars, and for arrays
  10269. /// of class type where the selected copy/move-assignment operator is trivial.
  10270. static StmtResult
  10271. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  10272. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  10273. // Compute the size of the memory buffer to be copied.
  10274. QualType SizeType = S.Context.getSizeType();
  10275. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  10276. S.Context.getTypeSizeInChars(T).getQuantity());
  10277. // Take the address of the field references for "from" and "to". We
  10278. // directly construct UnaryOperators here because semantic analysis
  10279. // does not permit us to take the address of an xvalue.
  10280. Expr *From = FromB.build(S, Loc);
  10281. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  10282. S.Context.getPointerType(From->getType()),
  10283. VK_RValue, OK_Ordinary, Loc, false);
  10284. Expr *To = ToB.build(S, Loc);
  10285. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  10286. S.Context.getPointerType(To->getType()),
  10287. VK_RValue, OK_Ordinary, Loc, false);
  10288. const Type *E = T->getBaseElementTypeUnsafe();
  10289. bool NeedsCollectableMemCpy =
  10290. E->isRecordType() &&
  10291. E->castAs<RecordType>()->getDecl()->hasObjectMember();
  10292. // Create a reference to the __builtin_objc_memmove_collectable function
  10293. StringRef MemCpyName = NeedsCollectableMemCpy ?
  10294. "__builtin_objc_memmove_collectable" :
  10295. "__builtin_memcpy";
  10296. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  10297. Sema::LookupOrdinaryName);
  10298. S.LookupName(R, S.TUScope, true);
  10299. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  10300. if (!MemCpy)
  10301. // Something went horribly wrong earlier, and we will have complained
  10302. // about it.
  10303. return StmtError();
  10304. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  10305. VK_RValue, Loc, nullptr);
  10306. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  10307. Expr *CallArgs[] = {
  10308. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  10309. };
  10310. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  10311. Loc, CallArgs, Loc);
  10312. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  10313. return Call.getAs<Stmt>();
  10314. }
  10315. /// Builds a statement that copies/moves the given entity from \p From to
  10316. /// \c To.
  10317. ///
  10318. /// This routine is used to copy/move the members of a class with an
  10319. /// implicitly-declared copy/move assignment operator. When the entities being
  10320. /// copied are arrays, this routine builds for loops to copy them.
  10321. ///
  10322. /// \param S The Sema object used for type-checking.
  10323. ///
  10324. /// \param Loc The location where the implicit copy/move is being generated.
  10325. ///
  10326. /// \param T The type of the expressions being copied/moved. Both expressions
  10327. /// must have this type.
  10328. ///
  10329. /// \param To The expression we are copying/moving to.
  10330. ///
  10331. /// \param From The expression we are copying/moving from.
  10332. ///
  10333. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  10334. /// Otherwise, it's a non-static member subobject.
  10335. ///
  10336. /// \param Copying Whether we're copying or moving.
  10337. ///
  10338. /// \param Depth Internal parameter recording the depth of the recursion.
  10339. ///
  10340. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  10341. /// if a memcpy should be used instead.
  10342. static StmtResult
  10343. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  10344. const ExprBuilder &To, const ExprBuilder &From,
  10345. bool CopyingBaseSubobject, bool Copying,
  10346. unsigned Depth = 0) {
  10347. // C++11 [class.copy]p28:
  10348. // Each subobject is assigned in the manner appropriate to its type:
  10349. //
  10350. // - if the subobject is of class type, as if by a call to operator= with
  10351. // the subobject as the object expression and the corresponding
  10352. // subobject of x as a single function argument (as if by explicit
  10353. // qualification; that is, ignoring any possible virtual overriding
  10354. // functions in more derived classes);
  10355. //
  10356. // C++03 [class.copy]p13:
  10357. // - if the subobject is of class type, the copy assignment operator for
  10358. // the class is used (as if by explicit qualification; that is,
  10359. // ignoring any possible virtual overriding functions in more derived
  10360. // classes);
  10361. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  10362. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  10363. // Look for operator=.
  10364. DeclarationName Name
  10365. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10366. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  10367. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  10368. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  10369. // operator.
  10370. if (!S.getLangOpts().CPlusPlus11) {
  10371. LookupResult::Filter F = OpLookup.makeFilter();
  10372. while (F.hasNext()) {
  10373. NamedDecl *D = F.next();
  10374. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  10375. if (Method->isCopyAssignmentOperator() ||
  10376. (!Copying && Method->isMoveAssignmentOperator()))
  10377. continue;
  10378. F.erase();
  10379. }
  10380. F.done();
  10381. }
  10382. // Suppress the protected check (C++ [class.protected]) for each of the
  10383. // assignment operators we found. This strange dance is required when
  10384. // we're assigning via a base classes's copy-assignment operator. To
  10385. // ensure that we're getting the right base class subobject (without
  10386. // ambiguities), we need to cast "this" to that subobject type; to
  10387. // ensure that we don't go through the virtual call mechanism, we need
  10388. // to qualify the operator= name with the base class (see below). However,
  10389. // this means that if the base class has a protected copy assignment
  10390. // operator, the protected member access check will fail. So, we
  10391. // rewrite "protected" access to "public" access in this case, since we
  10392. // know by construction that we're calling from a derived class.
  10393. if (CopyingBaseSubobject) {
  10394. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10395. L != LEnd; ++L) {
  10396. if (L.getAccess() == AS_protected)
  10397. L.setAccess(AS_public);
  10398. }
  10399. }
  10400. // Create the nested-name-specifier that will be used to qualify the
  10401. // reference to operator=; this is required to suppress the virtual
  10402. // call mechanism.
  10403. CXXScopeSpec SS;
  10404. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10405. SS.MakeTrivial(S.Context,
  10406. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10407. CanonicalT),
  10408. Loc);
  10409. // Create the reference to operator=.
  10410. ExprResult OpEqualRef
  10411. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  10412. SS, /*TemplateKWLoc=*/SourceLocation(),
  10413. /*FirstQualifierInScope=*/nullptr,
  10414. OpLookup,
  10415. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10416. /*SuppressQualifierCheck=*/true);
  10417. if (OpEqualRef.isInvalid())
  10418. return StmtError();
  10419. // Build the call to the assignment operator.
  10420. Expr *FromInst = From.build(S, Loc);
  10421. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10422. OpEqualRef.getAs<Expr>(),
  10423. Loc, FromInst, Loc);
  10424. if (Call.isInvalid())
  10425. return StmtError();
  10426. // If we built a call to a trivial 'operator=' while copying an array,
  10427. // bail out. We'll replace the whole shebang with a memcpy.
  10428. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10429. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10430. return StmtResult((Stmt*)nullptr);
  10431. // Convert to an expression-statement, and clean up any produced
  10432. // temporaries.
  10433. return S.ActOnExprStmt(Call);
  10434. }
  10435. // - if the subobject is of scalar type, the built-in assignment
  10436. // operator is used.
  10437. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10438. if (!ArrayTy) {
  10439. ExprResult Assignment = S.CreateBuiltinBinOp(
  10440. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10441. if (Assignment.isInvalid())
  10442. return StmtError();
  10443. return S.ActOnExprStmt(Assignment);
  10444. }
  10445. // - if the subobject is an array, each element is assigned, in the
  10446. // manner appropriate to the element type;
  10447. // Construct a loop over the array bounds, e.g.,
  10448. //
  10449. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10450. //
  10451. // that will copy each of the array elements.
  10452. QualType SizeType = S.Context.getSizeType();
  10453. // Create the iteration variable.
  10454. IdentifierInfo *IterationVarName = nullptr;
  10455. {
  10456. SmallString<8> Str;
  10457. llvm::raw_svector_ostream OS(Str);
  10458. OS << "__i" << Depth;
  10459. IterationVarName = &S.Context.Idents.get(OS.str());
  10460. }
  10461. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10462. IterationVarName, SizeType,
  10463. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10464. SC_None);
  10465. // Initialize the iteration variable to zero.
  10466. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10467. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10468. // Creates a reference to the iteration variable.
  10469. RefBuilder IterationVarRef(IterationVar, SizeType);
  10470. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10471. // Create the DeclStmt that holds the iteration variable.
  10472. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10473. // Subscript the "from" and "to" expressions with the iteration variable.
  10474. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10475. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10476. const ExprBuilder *FromIndex;
  10477. if (Copying)
  10478. FromIndex = &FromIndexCopy;
  10479. else
  10480. FromIndex = &FromIndexMove;
  10481. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10482. // Build the copy/move for an individual element of the array.
  10483. StmtResult Copy =
  10484. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10485. ToIndex, *FromIndex, CopyingBaseSubobject,
  10486. Copying, Depth + 1);
  10487. // Bail out if copying fails or if we determined that we should use memcpy.
  10488. if (Copy.isInvalid() || !Copy.get())
  10489. return Copy;
  10490. // Create the comparison against the array bound.
  10491. llvm::APInt Upper
  10492. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10493. Expr *Comparison
  10494. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10495. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10496. BO_NE, S.Context.BoolTy,
  10497. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10498. // Create the pre-increment of the iteration variable. We can determine
  10499. // whether the increment will overflow based on the value of the array
  10500. // bound.
  10501. Expr *Increment = new (S.Context)
  10502. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10503. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10504. // Construct the loop that copies all elements of this array.
  10505. return S.ActOnForStmt(
  10506. Loc, Loc, InitStmt,
  10507. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10508. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10509. }
  10510. static StmtResult
  10511. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10512. const ExprBuilder &To, const ExprBuilder &From,
  10513. bool CopyingBaseSubobject, bool Copying) {
  10514. // Maybe we should use a memcpy?
  10515. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10516. T.isTriviallyCopyableType(S.Context))
  10517. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10518. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10519. CopyingBaseSubobject,
  10520. Copying, 0));
  10521. // If we ended up picking a trivial assignment operator for an array of a
  10522. // non-trivially-copyable class type, just emit a memcpy.
  10523. if (!Result.isInvalid() && !Result.get())
  10524. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10525. return Result;
  10526. }
  10527. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10528. // Note: The following rules are largely analoguous to the copy
  10529. // constructor rules. Note that virtual bases are not taken into account
  10530. // for determining the argument type of the operator. Note also that
  10531. // operators taking an object instead of a reference are allowed.
  10532. assert(ClassDecl->needsImplicitCopyAssignment());
  10533. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10534. if (DSM.isAlreadyBeingDeclared())
  10535. return nullptr;
  10536. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10537. if (Context.getLangOpts().OpenCLCPlusPlus)
  10538. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10539. QualType RetType = Context.getLValueReferenceType(ArgType);
  10540. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10541. if (Const)
  10542. ArgType = ArgType.withConst();
  10543. ArgType = Context.getLValueReferenceType(ArgType);
  10544. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10545. CXXCopyAssignment,
  10546. Const);
  10547. // An implicitly-declared copy assignment operator is an inline public
  10548. // member of its class.
  10549. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10550. SourceLocation ClassLoc = ClassDecl->getLocation();
  10551. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10552. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  10553. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10554. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10555. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10556. SourceLocation());
  10557. CopyAssignment->setAccess(AS_public);
  10558. CopyAssignment->setDefaulted();
  10559. CopyAssignment->setImplicit();
  10560. if (getLangOpts().CUDA) {
  10561. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10562. CopyAssignment,
  10563. /* ConstRHS */ Const,
  10564. /* Diagnose */ false);
  10565. }
  10566. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  10567. // Add the parameter to the operator.
  10568. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10569. ClassLoc, ClassLoc,
  10570. /*Id=*/nullptr, ArgType,
  10571. /*TInfo=*/nullptr, SC_None,
  10572. nullptr);
  10573. CopyAssignment->setParams(FromParam);
  10574. CopyAssignment->setTrivial(
  10575. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10576. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10577. : ClassDecl->hasTrivialCopyAssignment());
  10578. // Note that we have added this copy-assignment operator.
  10579. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  10580. Scope *S = getScopeForContext(ClassDecl);
  10581. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10582. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10583. SetDeclDeleted(CopyAssignment, ClassLoc);
  10584. if (S)
  10585. PushOnScopeChains(CopyAssignment, S, false);
  10586. ClassDecl->addDecl(CopyAssignment);
  10587. return CopyAssignment;
  10588. }
  10589. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10590. /// which is deprecated because the class has a user-declared copy constructor,
  10591. /// copy assignment operator, or destructor.
  10592. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10593. assert(CopyOp->isImplicit());
  10594. CXXRecordDecl *RD = CopyOp->getParent();
  10595. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10596. // In Microsoft mode, assignment operations don't affect constructors and
  10597. // vice versa.
  10598. if (RD->hasUserDeclaredDestructor()) {
  10599. UserDeclaredOperation = RD->getDestructor();
  10600. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10601. RD->hasUserDeclaredCopyConstructor() &&
  10602. !S.getLangOpts().MSVCCompat) {
  10603. // Find any user-declared copy constructor.
  10604. for (auto *I : RD->ctors()) {
  10605. if (I->isCopyConstructor()) {
  10606. UserDeclaredOperation = I;
  10607. break;
  10608. }
  10609. }
  10610. assert(UserDeclaredOperation);
  10611. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10612. RD->hasUserDeclaredCopyAssignment() &&
  10613. !S.getLangOpts().MSVCCompat) {
  10614. // Find any user-declared move assignment operator.
  10615. for (auto *I : RD->methods()) {
  10616. if (I->isCopyAssignmentOperator()) {
  10617. UserDeclaredOperation = I;
  10618. break;
  10619. }
  10620. }
  10621. assert(UserDeclaredOperation);
  10622. }
  10623. if (UserDeclaredOperation) {
  10624. S.Diag(UserDeclaredOperation->getLocation(),
  10625. diag::warn_deprecated_copy_operation)
  10626. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10627. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10628. }
  10629. }
  10630. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10631. CXXMethodDecl *CopyAssignOperator) {
  10632. assert((CopyAssignOperator->isDefaulted() &&
  10633. CopyAssignOperator->isOverloadedOperator() &&
  10634. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10635. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10636. !CopyAssignOperator->isDeleted()) &&
  10637. "DefineImplicitCopyAssignment called for wrong function");
  10638. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10639. return;
  10640. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10641. if (ClassDecl->isInvalidDecl()) {
  10642. CopyAssignOperator->setInvalidDecl();
  10643. return;
  10644. }
  10645. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10646. // The exception specification is needed because we are defining the
  10647. // function.
  10648. ResolveExceptionSpec(CurrentLocation,
  10649. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10650. // Add a context note for diagnostics produced after this point.
  10651. Scope.addContextNote(CurrentLocation);
  10652. // C++11 [class.copy]p18:
  10653. // The [definition of an implicitly declared copy assignment operator] is
  10654. // deprecated if the class has a user-declared copy constructor or a
  10655. // user-declared destructor.
  10656. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10657. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10658. // C++0x [class.copy]p30:
  10659. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10660. // for a non-union class X performs memberwise copy assignment of its
  10661. // subobjects. The direct base classes of X are assigned first, in the
  10662. // order of their declaration in the base-specifier-list, and then the
  10663. // immediate non-static data members of X are assigned, in the order in
  10664. // which they were declared in the class definition.
  10665. // The statements that form the synthesized function body.
  10666. SmallVector<Stmt*, 8> Statements;
  10667. // The parameter for the "other" object, which we are copying from.
  10668. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10669. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10670. QualType OtherRefType = Other->getType();
  10671. if (const LValueReferenceType *OtherRef
  10672. = OtherRefType->getAs<LValueReferenceType>()) {
  10673. OtherRefType = OtherRef->getPointeeType();
  10674. OtherQuals = OtherRefType.getQualifiers();
  10675. }
  10676. // Our location for everything implicitly-generated.
  10677. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10678. ? CopyAssignOperator->getEndLoc()
  10679. : CopyAssignOperator->getLocation();
  10680. // Builds a DeclRefExpr for the "other" object.
  10681. RefBuilder OtherRef(Other, OtherRefType);
  10682. // Builds the "this" pointer.
  10683. ThisBuilder This;
  10684. // Assign base classes.
  10685. bool Invalid = false;
  10686. for (auto &Base : ClassDecl->bases()) {
  10687. // Form the assignment:
  10688. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10689. QualType BaseType = Base.getType().getUnqualifiedType();
  10690. if (!BaseType->isRecordType()) {
  10691. Invalid = true;
  10692. continue;
  10693. }
  10694. CXXCastPath BasePath;
  10695. BasePath.push_back(&Base);
  10696. // Construct the "from" expression, which is an implicit cast to the
  10697. // appropriately-qualified base type.
  10698. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10699. VK_LValue, BasePath);
  10700. // Dereference "this".
  10701. DerefBuilder DerefThis(This);
  10702. CastBuilder To(DerefThis,
  10703. Context.getQualifiedType(
  10704. BaseType, CopyAssignOperator->getMethodQualifiers()),
  10705. VK_LValue, BasePath);
  10706. // Build the copy.
  10707. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10708. To, From,
  10709. /*CopyingBaseSubobject=*/true,
  10710. /*Copying=*/true);
  10711. if (Copy.isInvalid()) {
  10712. CopyAssignOperator->setInvalidDecl();
  10713. return;
  10714. }
  10715. // Success! Record the copy.
  10716. Statements.push_back(Copy.getAs<Expr>());
  10717. }
  10718. // Assign non-static members.
  10719. for (auto *Field : ClassDecl->fields()) {
  10720. // FIXME: We should form some kind of AST representation for the implied
  10721. // memcpy in a union copy operation.
  10722. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10723. continue;
  10724. if (Field->isInvalidDecl()) {
  10725. Invalid = true;
  10726. continue;
  10727. }
  10728. // Check for members of reference type; we can't copy those.
  10729. if (Field->getType()->isReferenceType()) {
  10730. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10731. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10732. Diag(Field->getLocation(), diag::note_declared_at);
  10733. Invalid = true;
  10734. continue;
  10735. }
  10736. // Check for members of const-qualified, non-class type.
  10737. QualType BaseType = Context.getBaseElementType(Field->getType());
  10738. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10739. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10740. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10741. Diag(Field->getLocation(), diag::note_declared_at);
  10742. Invalid = true;
  10743. continue;
  10744. }
  10745. // Suppress assigning zero-width bitfields.
  10746. if (Field->isZeroLengthBitField(Context))
  10747. continue;
  10748. QualType FieldType = Field->getType().getNonReferenceType();
  10749. if (FieldType->isIncompleteArrayType()) {
  10750. assert(ClassDecl->hasFlexibleArrayMember() &&
  10751. "Incomplete array type is not valid");
  10752. continue;
  10753. }
  10754. // Build references to the field in the object we're copying from and to.
  10755. CXXScopeSpec SS; // Intentionally empty
  10756. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10757. LookupMemberName);
  10758. MemberLookup.addDecl(Field);
  10759. MemberLookup.resolveKind();
  10760. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10761. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10762. // Build the copy of this field.
  10763. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10764. To, From,
  10765. /*CopyingBaseSubobject=*/false,
  10766. /*Copying=*/true);
  10767. if (Copy.isInvalid()) {
  10768. CopyAssignOperator->setInvalidDecl();
  10769. return;
  10770. }
  10771. // Success! Record the copy.
  10772. Statements.push_back(Copy.getAs<Stmt>());
  10773. }
  10774. if (!Invalid) {
  10775. // Add a "return *this;"
  10776. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10777. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10778. if (Return.isInvalid())
  10779. Invalid = true;
  10780. else
  10781. Statements.push_back(Return.getAs<Stmt>());
  10782. }
  10783. if (Invalid) {
  10784. CopyAssignOperator->setInvalidDecl();
  10785. return;
  10786. }
  10787. StmtResult Body;
  10788. {
  10789. CompoundScopeRAII CompoundScope(*this);
  10790. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10791. /*isStmtExpr=*/false);
  10792. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10793. }
  10794. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10795. CopyAssignOperator->markUsed(Context);
  10796. if (ASTMutationListener *L = getASTMutationListener()) {
  10797. L->CompletedImplicitDefinition(CopyAssignOperator);
  10798. }
  10799. }
  10800. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10801. assert(ClassDecl->needsImplicitMoveAssignment());
  10802. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10803. if (DSM.isAlreadyBeingDeclared())
  10804. return nullptr;
  10805. // Note: The following rules are largely analoguous to the move
  10806. // constructor rules.
  10807. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10808. if (Context.getLangOpts().OpenCLCPlusPlus)
  10809. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10810. QualType RetType = Context.getLValueReferenceType(ArgType);
  10811. ArgType = Context.getRValueReferenceType(ArgType);
  10812. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10813. CXXMoveAssignment,
  10814. false);
  10815. // An implicitly-declared move assignment operator is an inline public
  10816. // member of its class.
  10817. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10818. SourceLocation ClassLoc = ClassDecl->getLocation();
  10819. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10820. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  10821. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10822. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10823. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10824. SourceLocation());
  10825. MoveAssignment->setAccess(AS_public);
  10826. MoveAssignment->setDefaulted();
  10827. MoveAssignment->setImplicit();
  10828. if (getLangOpts().CUDA) {
  10829. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10830. MoveAssignment,
  10831. /* ConstRHS */ false,
  10832. /* Diagnose */ false);
  10833. }
  10834. // Build an exception specification pointing back at this member.
  10835. FunctionProtoType::ExtProtoInfo EPI =
  10836. getImplicitMethodEPI(*this, MoveAssignment);
  10837. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10838. // Add the parameter to the operator.
  10839. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10840. ClassLoc, ClassLoc,
  10841. /*Id=*/nullptr, ArgType,
  10842. /*TInfo=*/nullptr, SC_None,
  10843. nullptr);
  10844. MoveAssignment->setParams(FromParam);
  10845. MoveAssignment->setTrivial(
  10846. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10847. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10848. : ClassDecl->hasTrivialMoveAssignment());
  10849. // Note that we have added this copy-assignment operator.
  10850. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  10851. Scope *S = getScopeForContext(ClassDecl);
  10852. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10853. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10854. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10855. SetDeclDeleted(MoveAssignment, ClassLoc);
  10856. }
  10857. if (S)
  10858. PushOnScopeChains(MoveAssignment, S, false);
  10859. ClassDecl->addDecl(MoveAssignment);
  10860. return MoveAssignment;
  10861. }
  10862. /// Check if we're implicitly defining a move assignment operator for a class
  10863. /// with virtual bases. Such a move assignment might move-assign the virtual
  10864. /// base multiple times.
  10865. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10866. SourceLocation CurrentLocation) {
  10867. assert(!Class->isDependentContext() && "should not define dependent move");
  10868. // Only a virtual base could get implicitly move-assigned multiple times.
  10869. // Only a non-trivial move assignment can observe this. We only want to
  10870. // diagnose if we implicitly define an assignment operator that assigns
  10871. // two base classes, both of which move-assign the same virtual base.
  10872. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10873. Class->getNumBases() < 2)
  10874. return;
  10875. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10876. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10877. VBaseMap VBases;
  10878. for (auto &BI : Class->bases()) {
  10879. Worklist.push_back(&BI);
  10880. while (!Worklist.empty()) {
  10881. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10882. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10883. // If the base has no non-trivial move assignment operators,
  10884. // we don't care about moves from it.
  10885. if (!Base->hasNonTrivialMoveAssignment())
  10886. continue;
  10887. // If there's nothing virtual here, skip it.
  10888. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10889. continue;
  10890. // If we're not actually going to call a move assignment for this base,
  10891. // or the selected move assignment is trivial, skip it.
  10892. Sema::SpecialMemberOverloadResult SMOR =
  10893. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10894. /*ConstArg*/false, /*VolatileArg*/false,
  10895. /*RValueThis*/true, /*ConstThis*/false,
  10896. /*VolatileThis*/false);
  10897. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10898. !SMOR.getMethod()->isMoveAssignmentOperator())
  10899. continue;
  10900. if (BaseSpec->isVirtual()) {
  10901. // We're going to move-assign this virtual base, and its move
  10902. // assignment operator is not trivial. If this can happen for
  10903. // multiple distinct direct bases of Class, diagnose it. (If it
  10904. // only happens in one base, we'll diagnose it when synthesizing
  10905. // that base class's move assignment operator.)
  10906. CXXBaseSpecifier *&Existing =
  10907. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10908. .first->second;
  10909. if (Existing && Existing != &BI) {
  10910. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10911. << Class << Base;
  10912. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10913. << (Base->getCanonicalDecl() ==
  10914. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10915. << Base << Existing->getType() << Existing->getSourceRange();
  10916. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10917. << (Base->getCanonicalDecl() ==
  10918. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10919. << Base << BI.getType() << BaseSpec->getSourceRange();
  10920. // Only diagnose each vbase once.
  10921. Existing = nullptr;
  10922. }
  10923. } else {
  10924. // Only walk over bases that have defaulted move assignment operators.
  10925. // We assume that any user-provided move assignment operator handles
  10926. // the multiple-moves-of-vbase case itself somehow.
  10927. if (!SMOR.getMethod()->isDefaulted())
  10928. continue;
  10929. // We're going to move the base classes of Base. Add them to the list.
  10930. for (auto &BI : Base->bases())
  10931. Worklist.push_back(&BI);
  10932. }
  10933. }
  10934. }
  10935. }
  10936. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10937. CXXMethodDecl *MoveAssignOperator) {
  10938. assert((MoveAssignOperator->isDefaulted() &&
  10939. MoveAssignOperator->isOverloadedOperator() &&
  10940. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10941. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10942. !MoveAssignOperator->isDeleted()) &&
  10943. "DefineImplicitMoveAssignment called for wrong function");
  10944. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10945. return;
  10946. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10947. if (ClassDecl->isInvalidDecl()) {
  10948. MoveAssignOperator->setInvalidDecl();
  10949. return;
  10950. }
  10951. // C++0x [class.copy]p28:
  10952. // The implicitly-defined or move assignment operator for a non-union class
  10953. // X performs memberwise move assignment of its subobjects. The direct base
  10954. // classes of X are assigned first, in the order of their declaration in the
  10955. // base-specifier-list, and then the immediate non-static data members of X
  10956. // are assigned, in the order in which they were declared in the class
  10957. // definition.
  10958. // Issue a warning if our implicit move assignment operator will move
  10959. // from a virtual base more than once.
  10960. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10961. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10962. // The exception specification is needed because we are defining the
  10963. // function.
  10964. ResolveExceptionSpec(CurrentLocation,
  10965. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10966. // Add a context note for diagnostics produced after this point.
  10967. Scope.addContextNote(CurrentLocation);
  10968. // The statements that form the synthesized function body.
  10969. SmallVector<Stmt*, 8> Statements;
  10970. // The parameter for the "other" object, which we are move from.
  10971. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10972. QualType OtherRefType = Other->getType()->
  10973. getAs<RValueReferenceType>()->getPointeeType();
  10974. // Our location for everything implicitly-generated.
  10975. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10976. ? MoveAssignOperator->getEndLoc()
  10977. : MoveAssignOperator->getLocation();
  10978. // Builds a reference to the "other" object.
  10979. RefBuilder OtherRef(Other, OtherRefType);
  10980. // Cast to rvalue.
  10981. MoveCastBuilder MoveOther(OtherRef);
  10982. // Builds the "this" pointer.
  10983. ThisBuilder This;
  10984. // Assign base classes.
  10985. bool Invalid = false;
  10986. for (auto &Base : ClassDecl->bases()) {
  10987. // C++11 [class.copy]p28:
  10988. // It is unspecified whether subobjects representing virtual base classes
  10989. // are assigned more than once by the implicitly-defined copy assignment
  10990. // operator.
  10991. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10992. // class. For a move-assignment, this can result in the vbase being moved
  10993. // multiple times.
  10994. // Form the assignment:
  10995. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10996. QualType BaseType = Base.getType().getUnqualifiedType();
  10997. if (!BaseType->isRecordType()) {
  10998. Invalid = true;
  10999. continue;
  11000. }
  11001. CXXCastPath BasePath;
  11002. BasePath.push_back(&Base);
  11003. // Construct the "from" expression, which is an implicit cast to the
  11004. // appropriately-qualified base type.
  11005. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  11006. // Dereference "this".
  11007. DerefBuilder DerefThis(This);
  11008. // Implicitly cast "this" to the appropriately-qualified base type.
  11009. CastBuilder To(DerefThis,
  11010. Context.getQualifiedType(
  11011. BaseType, MoveAssignOperator->getMethodQualifiers()),
  11012. VK_LValue, BasePath);
  11013. // Build the move.
  11014. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  11015. To, From,
  11016. /*CopyingBaseSubobject=*/true,
  11017. /*Copying=*/false);
  11018. if (Move.isInvalid()) {
  11019. MoveAssignOperator->setInvalidDecl();
  11020. return;
  11021. }
  11022. // Success! Record the move.
  11023. Statements.push_back(Move.getAs<Expr>());
  11024. }
  11025. // Assign non-static members.
  11026. for (auto *Field : ClassDecl->fields()) {
  11027. // FIXME: We should form some kind of AST representation for the implied
  11028. // memcpy in a union copy operation.
  11029. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  11030. continue;
  11031. if (Field->isInvalidDecl()) {
  11032. Invalid = true;
  11033. continue;
  11034. }
  11035. // Check for members of reference type; we can't move those.
  11036. if (Field->getType()->isReferenceType()) {
  11037. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  11038. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  11039. Diag(Field->getLocation(), diag::note_declared_at);
  11040. Invalid = true;
  11041. continue;
  11042. }
  11043. // Check for members of const-qualified, non-class type.
  11044. QualType BaseType = Context.getBaseElementType(Field->getType());
  11045. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  11046. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  11047. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  11048. Diag(Field->getLocation(), diag::note_declared_at);
  11049. Invalid = true;
  11050. continue;
  11051. }
  11052. // Suppress assigning zero-width bitfields.
  11053. if (Field->isZeroLengthBitField(Context))
  11054. continue;
  11055. QualType FieldType = Field->getType().getNonReferenceType();
  11056. if (FieldType->isIncompleteArrayType()) {
  11057. assert(ClassDecl->hasFlexibleArrayMember() &&
  11058. "Incomplete array type is not valid");
  11059. continue;
  11060. }
  11061. // Build references to the field in the object we're copying from and to.
  11062. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  11063. LookupMemberName);
  11064. MemberLookup.addDecl(Field);
  11065. MemberLookup.resolveKind();
  11066. MemberBuilder From(MoveOther, OtherRefType,
  11067. /*IsArrow=*/false, MemberLookup);
  11068. MemberBuilder To(This, getCurrentThisType(),
  11069. /*IsArrow=*/true, MemberLookup);
  11070. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  11071. "Member reference with rvalue base must be rvalue except for reference "
  11072. "members, which aren't allowed for move assignment.");
  11073. // Build the move of this field.
  11074. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  11075. To, From,
  11076. /*CopyingBaseSubobject=*/false,
  11077. /*Copying=*/false);
  11078. if (Move.isInvalid()) {
  11079. MoveAssignOperator->setInvalidDecl();
  11080. return;
  11081. }
  11082. // Success! Record the copy.
  11083. Statements.push_back(Move.getAs<Stmt>());
  11084. }
  11085. if (!Invalid) {
  11086. // Add a "return *this;"
  11087. ExprResult ThisObj =
  11088. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  11089. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  11090. if (Return.isInvalid())
  11091. Invalid = true;
  11092. else
  11093. Statements.push_back(Return.getAs<Stmt>());
  11094. }
  11095. if (Invalid) {
  11096. MoveAssignOperator->setInvalidDecl();
  11097. return;
  11098. }
  11099. StmtResult Body;
  11100. {
  11101. CompoundScopeRAII CompoundScope(*this);
  11102. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  11103. /*isStmtExpr=*/false);
  11104. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  11105. }
  11106. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  11107. MoveAssignOperator->markUsed(Context);
  11108. if (ASTMutationListener *L = getASTMutationListener()) {
  11109. L->CompletedImplicitDefinition(MoveAssignOperator);
  11110. }
  11111. }
  11112. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  11113. CXXRecordDecl *ClassDecl) {
  11114. // C++ [class.copy]p4:
  11115. // If the class definition does not explicitly declare a copy
  11116. // constructor, one is declared implicitly.
  11117. assert(ClassDecl->needsImplicitCopyConstructor());
  11118. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  11119. if (DSM.isAlreadyBeingDeclared())
  11120. return nullptr;
  11121. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11122. QualType ArgType = ClassType;
  11123. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  11124. if (Const)
  11125. ArgType = ArgType.withConst();
  11126. if (Context.getLangOpts().OpenCLCPlusPlus)
  11127. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  11128. ArgType = Context.getLValueReferenceType(ArgType);
  11129. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11130. CXXCopyConstructor,
  11131. Const);
  11132. DeclarationName Name
  11133. = Context.DeclarationNames.getCXXConstructorName(
  11134. Context.getCanonicalType(ClassType));
  11135. SourceLocation ClassLoc = ClassDecl->getLocation();
  11136. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11137. // An implicitly-declared copy constructor is an inline public
  11138. // member of its class.
  11139. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  11140. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11141. ExplicitSpecifier(),
  11142. /*isInline=*/true,
  11143. /*isImplicitlyDeclared=*/true,
  11144. Constexpr ? CSK_constexpr : CSK_unspecified);
  11145. CopyConstructor->setAccess(AS_public);
  11146. CopyConstructor->setDefaulted();
  11147. if (getLangOpts().CUDA) {
  11148. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  11149. CopyConstructor,
  11150. /* ConstRHS */ Const,
  11151. /* Diagnose */ false);
  11152. }
  11153. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  11154. // Add the parameter to the constructor.
  11155. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  11156. ClassLoc, ClassLoc,
  11157. /*IdentifierInfo=*/nullptr,
  11158. ArgType, /*TInfo=*/nullptr,
  11159. SC_None, nullptr);
  11160. CopyConstructor->setParams(FromParam);
  11161. CopyConstructor->setTrivial(
  11162. ClassDecl->needsOverloadResolutionForCopyConstructor()
  11163. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  11164. : ClassDecl->hasTrivialCopyConstructor());
  11165. CopyConstructor->setTrivialForCall(
  11166. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11167. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  11168. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  11169. TAH_ConsiderTrivialABI)
  11170. : ClassDecl->hasTrivialCopyConstructorForCall()));
  11171. // Note that we have declared this constructor.
  11172. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  11173. Scope *S = getScopeForContext(ClassDecl);
  11174. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  11175. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  11176. ClassDecl->setImplicitCopyConstructorIsDeleted();
  11177. SetDeclDeleted(CopyConstructor, ClassLoc);
  11178. }
  11179. if (S)
  11180. PushOnScopeChains(CopyConstructor, S, false);
  11181. ClassDecl->addDecl(CopyConstructor);
  11182. return CopyConstructor;
  11183. }
  11184. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  11185. CXXConstructorDecl *CopyConstructor) {
  11186. assert((CopyConstructor->isDefaulted() &&
  11187. CopyConstructor->isCopyConstructor() &&
  11188. !CopyConstructor->doesThisDeclarationHaveABody() &&
  11189. !CopyConstructor->isDeleted()) &&
  11190. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  11191. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  11192. return;
  11193. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  11194. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  11195. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  11196. // The exception specification is needed because we are defining the
  11197. // function.
  11198. ResolveExceptionSpec(CurrentLocation,
  11199. CopyConstructor->getType()->castAs<FunctionProtoType>());
  11200. MarkVTableUsed(CurrentLocation, ClassDecl);
  11201. // Add a context note for diagnostics produced after this point.
  11202. Scope.addContextNote(CurrentLocation);
  11203. // C++11 [class.copy]p7:
  11204. // The [definition of an implicitly declared copy constructor] is
  11205. // deprecated if the class has a user-declared copy assignment operator
  11206. // or a user-declared destructor.
  11207. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  11208. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  11209. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  11210. CopyConstructor->setInvalidDecl();
  11211. } else {
  11212. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  11213. ? CopyConstructor->getEndLoc()
  11214. : CopyConstructor->getLocation();
  11215. Sema::CompoundScopeRAII CompoundScope(*this);
  11216. CopyConstructor->setBody(
  11217. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  11218. CopyConstructor->markUsed(Context);
  11219. }
  11220. if (ASTMutationListener *L = getASTMutationListener()) {
  11221. L->CompletedImplicitDefinition(CopyConstructor);
  11222. }
  11223. }
  11224. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  11225. CXXRecordDecl *ClassDecl) {
  11226. assert(ClassDecl->needsImplicitMoveConstructor());
  11227. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  11228. if (DSM.isAlreadyBeingDeclared())
  11229. return nullptr;
  11230. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11231. QualType ArgType = ClassType;
  11232. if (Context.getLangOpts().OpenCLCPlusPlus)
  11233. ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
  11234. ArgType = Context.getRValueReferenceType(ArgType);
  11235. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11236. CXXMoveConstructor,
  11237. false);
  11238. DeclarationName Name
  11239. = Context.DeclarationNames.getCXXConstructorName(
  11240. Context.getCanonicalType(ClassType));
  11241. SourceLocation ClassLoc = ClassDecl->getLocation();
  11242. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11243. // C++11 [class.copy]p11:
  11244. // An implicitly-declared copy/move constructor is an inline public
  11245. // member of its class.
  11246. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  11247. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11248. ExplicitSpecifier(),
  11249. /*isInline=*/true,
  11250. /*isImplicitlyDeclared=*/true,
  11251. Constexpr ? CSK_constexpr : CSK_unspecified);
  11252. MoveConstructor->setAccess(AS_public);
  11253. MoveConstructor->setDefaulted();
  11254. if (getLangOpts().CUDA) {
  11255. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  11256. MoveConstructor,
  11257. /* ConstRHS */ false,
  11258. /* Diagnose */ false);
  11259. }
  11260. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  11261. // Add the parameter to the constructor.
  11262. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  11263. ClassLoc, ClassLoc,
  11264. /*IdentifierInfo=*/nullptr,
  11265. ArgType, /*TInfo=*/nullptr,
  11266. SC_None, nullptr);
  11267. MoveConstructor->setParams(FromParam);
  11268. MoveConstructor->setTrivial(
  11269. ClassDecl->needsOverloadResolutionForMoveConstructor()
  11270. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  11271. : ClassDecl->hasTrivialMoveConstructor());
  11272. MoveConstructor->setTrivialForCall(
  11273. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11274. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  11275. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  11276. TAH_ConsiderTrivialABI)
  11277. : ClassDecl->hasTrivialMoveConstructorForCall()));
  11278. // Note that we have declared this constructor.
  11279. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  11280. Scope *S = getScopeForContext(ClassDecl);
  11281. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  11282. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  11283. ClassDecl->setImplicitMoveConstructorIsDeleted();
  11284. SetDeclDeleted(MoveConstructor, ClassLoc);
  11285. }
  11286. if (S)
  11287. PushOnScopeChains(MoveConstructor, S, false);
  11288. ClassDecl->addDecl(MoveConstructor);
  11289. return MoveConstructor;
  11290. }
  11291. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  11292. CXXConstructorDecl *MoveConstructor) {
  11293. assert((MoveConstructor->isDefaulted() &&
  11294. MoveConstructor->isMoveConstructor() &&
  11295. !MoveConstructor->doesThisDeclarationHaveABody() &&
  11296. !MoveConstructor->isDeleted()) &&
  11297. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  11298. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  11299. return;
  11300. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  11301. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  11302. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  11303. // The exception specification is needed because we are defining the
  11304. // function.
  11305. ResolveExceptionSpec(CurrentLocation,
  11306. MoveConstructor->getType()->castAs<FunctionProtoType>());
  11307. MarkVTableUsed(CurrentLocation, ClassDecl);
  11308. // Add a context note for diagnostics produced after this point.
  11309. Scope.addContextNote(CurrentLocation);
  11310. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  11311. MoveConstructor->setInvalidDecl();
  11312. } else {
  11313. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  11314. ? MoveConstructor->getEndLoc()
  11315. : MoveConstructor->getLocation();
  11316. Sema::CompoundScopeRAII CompoundScope(*this);
  11317. MoveConstructor->setBody(ActOnCompoundStmt(
  11318. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  11319. MoveConstructor->markUsed(Context);
  11320. }
  11321. if (ASTMutationListener *L = getASTMutationListener()) {
  11322. L->CompletedImplicitDefinition(MoveConstructor);
  11323. }
  11324. }
  11325. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  11326. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  11327. }
  11328. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  11329. SourceLocation CurrentLocation,
  11330. CXXConversionDecl *Conv) {
  11331. SynthesizedFunctionScope Scope(*this, Conv);
  11332. assert(!Conv->getReturnType()->isUndeducedType());
  11333. CXXRecordDecl *Lambda = Conv->getParent();
  11334. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  11335. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  11336. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  11337. CallOp = InstantiateFunctionDeclaration(
  11338. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11339. if (!CallOp)
  11340. return;
  11341. Invoker = InstantiateFunctionDeclaration(
  11342. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11343. if (!Invoker)
  11344. return;
  11345. }
  11346. if (CallOp->isInvalidDecl())
  11347. return;
  11348. // Mark the call operator referenced (and add to pending instantiations
  11349. // if necessary).
  11350. // For both the conversion and static-invoker template specializations
  11351. // we construct their body's in this function, so no need to add them
  11352. // to the PendingInstantiations.
  11353. MarkFunctionReferenced(CurrentLocation, CallOp);
  11354. // Fill in the __invoke function with a dummy implementation. IR generation
  11355. // will fill in the actual details. Update its type in case it contained
  11356. // an 'auto'.
  11357. Invoker->markUsed(Context);
  11358. Invoker->setReferenced();
  11359. Invoker->setType(Conv->getReturnType()->getPointeeType());
  11360. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  11361. // Construct the body of the conversion function { return __invoke; }.
  11362. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  11363. VK_LValue, Conv->getLocation());
  11364. assert(FunctionRef && "Can't refer to __invoke function?");
  11365. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  11366. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  11367. Conv->getLocation()));
  11368. Conv->markUsed(Context);
  11369. Conv->setReferenced();
  11370. if (ASTMutationListener *L = getASTMutationListener()) {
  11371. L->CompletedImplicitDefinition(Conv);
  11372. L->CompletedImplicitDefinition(Invoker);
  11373. }
  11374. }
  11375. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  11376. SourceLocation CurrentLocation,
  11377. CXXConversionDecl *Conv)
  11378. {
  11379. assert(!Conv->getParent()->isGenericLambda());
  11380. SynthesizedFunctionScope Scope(*this, Conv);
  11381. // Copy-initialize the lambda object as needed to capture it.
  11382. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11383. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11384. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11385. Conv->getLocation(),
  11386. Conv, DerefThis);
  11387. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11388. // behavior. Note that only the general conversion function does this
  11389. // (since it's unusable otherwise); in the case where we inline the
  11390. // block literal, it has block literal lifetime semantics.
  11391. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11392. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11393. CK_CopyAndAutoreleaseBlockObject,
  11394. BuildBlock.get(), nullptr, VK_RValue);
  11395. if (BuildBlock.isInvalid()) {
  11396. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11397. Conv->setInvalidDecl();
  11398. return;
  11399. }
  11400. // Create the return statement that returns the block from the conversion
  11401. // function.
  11402. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11403. if (Return.isInvalid()) {
  11404. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11405. Conv->setInvalidDecl();
  11406. return;
  11407. }
  11408. // Set the body of the conversion function.
  11409. Stmt *ReturnS = Return.get();
  11410. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11411. Conv->getLocation()));
  11412. Conv->markUsed(Context);
  11413. // We're done; notify the mutation listener, if any.
  11414. if (ASTMutationListener *L = getASTMutationListener()) {
  11415. L->CompletedImplicitDefinition(Conv);
  11416. }
  11417. }
  11418. /// Determine whether the given list arguments contains exactly one
  11419. /// "real" (non-default) argument.
  11420. static bool hasOneRealArgument(MultiExprArg Args) {
  11421. switch (Args.size()) {
  11422. case 0:
  11423. return false;
  11424. default:
  11425. if (!Args[1]->isDefaultArgument())
  11426. return false;
  11427. LLVM_FALLTHROUGH;
  11428. case 1:
  11429. return !Args[0]->isDefaultArgument();
  11430. }
  11431. return false;
  11432. }
  11433. ExprResult
  11434. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11435. NamedDecl *FoundDecl,
  11436. CXXConstructorDecl *Constructor,
  11437. MultiExprArg ExprArgs,
  11438. bool HadMultipleCandidates,
  11439. bool IsListInitialization,
  11440. bool IsStdInitListInitialization,
  11441. bool RequiresZeroInit,
  11442. unsigned ConstructKind,
  11443. SourceRange ParenRange) {
  11444. bool Elidable = false;
  11445. // C++0x [class.copy]p34:
  11446. // When certain criteria are met, an implementation is allowed to
  11447. // omit the copy/move construction of a class object, even if the
  11448. // copy/move constructor and/or destructor for the object have
  11449. // side effects. [...]
  11450. // - when a temporary class object that has not been bound to a
  11451. // reference (12.2) would be copied/moved to a class object
  11452. // with the same cv-unqualified type, the copy/move operation
  11453. // can be omitted by constructing the temporary object
  11454. // directly into the target of the omitted copy/move
  11455. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11456. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11457. Expr *SubExpr = ExprArgs[0];
  11458. Elidable = SubExpr->isTemporaryObject(
  11459. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11460. }
  11461. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11462. FoundDecl, Constructor,
  11463. Elidable, ExprArgs, HadMultipleCandidates,
  11464. IsListInitialization,
  11465. IsStdInitListInitialization, RequiresZeroInit,
  11466. ConstructKind, ParenRange);
  11467. }
  11468. ExprResult
  11469. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11470. NamedDecl *FoundDecl,
  11471. CXXConstructorDecl *Constructor,
  11472. bool Elidable,
  11473. MultiExprArg ExprArgs,
  11474. bool HadMultipleCandidates,
  11475. bool IsListInitialization,
  11476. bool IsStdInitListInitialization,
  11477. bool RequiresZeroInit,
  11478. unsigned ConstructKind,
  11479. SourceRange ParenRange) {
  11480. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11481. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11482. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11483. return ExprError();
  11484. }
  11485. return BuildCXXConstructExpr(
  11486. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11487. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11488. RequiresZeroInit, ConstructKind, ParenRange);
  11489. }
  11490. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11491. /// including handling of its default argument expressions.
  11492. ExprResult
  11493. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11494. CXXConstructorDecl *Constructor,
  11495. bool Elidable,
  11496. MultiExprArg ExprArgs,
  11497. bool HadMultipleCandidates,
  11498. bool IsListInitialization,
  11499. bool IsStdInitListInitialization,
  11500. bool RequiresZeroInit,
  11501. unsigned ConstructKind,
  11502. SourceRange ParenRange) {
  11503. assert(declaresSameEntity(
  11504. Constructor->getParent(),
  11505. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11506. "given constructor for wrong type");
  11507. MarkFunctionReferenced(ConstructLoc, Constructor);
  11508. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11509. return ExprError();
  11510. return CXXConstructExpr::Create(
  11511. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11512. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11513. IsStdInitListInitialization, RequiresZeroInit,
  11514. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11515. ParenRange);
  11516. }
  11517. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11518. assert(Field->hasInClassInitializer());
  11519. // If we already have the in-class initializer nothing needs to be done.
  11520. if (Field->getInClassInitializer())
  11521. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11522. // If we might have already tried and failed to instantiate, don't try again.
  11523. if (Field->isInvalidDecl())
  11524. return ExprError();
  11525. // Maybe we haven't instantiated the in-class initializer. Go check the
  11526. // pattern FieldDecl to see if it has one.
  11527. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11528. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11529. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11530. DeclContext::lookup_result Lookup =
  11531. ClassPattern->lookup(Field->getDeclName());
  11532. // Lookup can return at most two results: the pattern for the field, or the
  11533. // injected class name of the parent record. No other member can have the
  11534. // same name as the field.
  11535. // In modules mode, lookup can return multiple results (coming from
  11536. // different modules).
  11537. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11538. "more than two lookup results for field name");
  11539. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11540. if (!Pattern) {
  11541. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11542. "cannot have other non-field member with same name");
  11543. for (auto L : Lookup)
  11544. if (isa<FieldDecl>(L)) {
  11545. Pattern = cast<FieldDecl>(L);
  11546. break;
  11547. }
  11548. assert(Pattern && "We must have set the Pattern!");
  11549. }
  11550. if (!Pattern->hasInClassInitializer() ||
  11551. InstantiateInClassInitializer(Loc, Field, Pattern,
  11552. getTemplateInstantiationArgs(Field))) {
  11553. // Don't diagnose this again.
  11554. Field->setInvalidDecl();
  11555. return ExprError();
  11556. }
  11557. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11558. }
  11559. // DR1351:
  11560. // If the brace-or-equal-initializer of a non-static data member
  11561. // invokes a defaulted default constructor of its class or of an
  11562. // enclosing class in a potentially evaluated subexpression, the
  11563. // program is ill-formed.
  11564. //
  11565. // This resolution is unworkable: the exception specification of the
  11566. // default constructor can be needed in an unevaluated context, in
  11567. // particular, in the operand of a noexcept-expression, and we can be
  11568. // unable to compute an exception specification for an enclosed class.
  11569. //
  11570. // Any attempt to resolve the exception specification of a defaulted default
  11571. // constructor before the initializer is lexically complete will ultimately
  11572. // come here at which point we can diagnose it.
  11573. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11574. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11575. << OutermostClass << Field;
  11576. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11577. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11578. if (!isSFINAEContext())
  11579. Field->setInvalidDecl();
  11580. return ExprError();
  11581. }
  11582. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11583. if (VD->isInvalidDecl()) return;
  11584. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11585. if (ClassDecl->isInvalidDecl()) return;
  11586. if (ClassDecl->hasIrrelevantDestructor()) return;
  11587. if (ClassDecl->isDependentContext()) return;
  11588. if (VD->isNoDestroy(getASTContext()))
  11589. return;
  11590. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11591. // If this is an array, we'll require the destructor during initialization, so
  11592. // we can skip over this. We still want to emit exit-time destructor warnings
  11593. // though.
  11594. if (!VD->getType()->isArrayType()) {
  11595. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11596. CheckDestructorAccess(VD->getLocation(), Destructor,
  11597. PDiag(diag::err_access_dtor_var)
  11598. << VD->getDeclName() << VD->getType());
  11599. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11600. }
  11601. if (Destructor->isTrivial()) return;
  11602. // If the destructor is constexpr, check whether the variable has constant
  11603. // destruction now.
  11604. if (Destructor->isConstexpr() && VD->getInit() &&
  11605. !VD->getInit()->isValueDependent() && VD->evaluateValue()) {
  11606. SmallVector<PartialDiagnosticAt, 8> Notes;
  11607. if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) {
  11608. Diag(VD->getLocation(),
  11609. diag::err_constexpr_var_requires_const_destruction) << VD;
  11610. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  11611. Diag(Notes[I].first, Notes[I].second);
  11612. }
  11613. }
  11614. if (!VD->hasGlobalStorage()) return;
  11615. // Emit warning for non-trivial dtor in global scope (a real global,
  11616. // class-static, function-static).
  11617. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11618. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11619. if (!VD->isStaticLocal())
  11620. Diag(VD->getLocation(), diag::warn_global_destructor);
  11621. }
  11622. /// Given a constructor and the set of arguments provided for the
  11623. /// constructor, convert the arguments and add any required default arguments
  11624. /// to form a proper call to this constructor.
  11625. ///
  11626. /// \returns true if an error occurred, false otherwise.
  11627. bool
  11628. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11629. MultiExprArg ArgsPtr,
  11630. SourceLocation Loc,
  11631. SmallVectorImpl<Expr*> &ConvertedArgs,
  11632. bool AllowExplicit,
  11633. bool IsListInitialization) {
  11634. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11635. unsigned NumArgs = ArgsPtr.size();
  11636. Expr **Args = ArgsPtr.data();
  11637. const FunctionProtoType *Proto
  11638. = Constructor->getType()->getAs<FunctionProtoType>();
  11639. assert(Proto && "Constructor without a prototype?");
  11640. unsigned NumParams = Proto->getNumParams();
  11641. // If too few arguments are available, we'll fill in the rest with defaults.
  11642. if (NumArgs < NumParams)
  11643. ConvertedArgs.reserve(NumParams);
  11644. else
  11645. ConvertedArgs.reserve(NumArgs);
  11646. VariadicCallType CallType =
  11647. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11648. SmallVector<Expr *, 8> AllArgs;
  11649. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11650. Proto, 0,
  11651. llvm::makeArrayRef(Args, NumArgs),
  11652. AllArgs,
  11653. CallType, AllowExplicit,
  11654. IsListInitialization);
  11655. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11656. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11657. CheckConstructorCall(Constructor,
  11658. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11659. Proto, Loc);
  11660. return Invalid;
  11661. }
  11662. static inline bool
  11663. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11664. const FunctionDecl *FnDecl) {
  11665. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11666. if (isa<NamespaceDecl>(DC)) {
  11667. return SemaRef.Diag(FnDecl->getLocation(),
  11668. diag::err_operator_new_delete_declared_in_namespace)
  11669. << FnDecl->getDeclName();
  11670. }
  11671. if (isa<TranslationUnitDecl>(DC) &&
  11672. FnDecl->getStorageClass() == SC_Static) {
  11673. return SemaRef.Diag(FnDecl->getLocation(),
  11674. diag::err_operator_new_delete_declared_static)
  11675. << FnDecl->getDeclName();
  11676. }
  11677. return false;
  11678. }
  11679. static QualType
  11680. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11681. QualType QTy = PtrTy->getPointeeType();
  11682. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11683. return SemaRef.Context.getPointerType(QTy);
  11684. }
  11685. static inline bool
  11686. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11687. CanQualType ExpectedResultType,
  11688. CanQualType ExpectedFirstParamType,
  11689. unsigned DependentParamTypeDiag,
  11690. unsigned InvalidParamTypeDiag) {
  11691. QualType ResultType =
  11692. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11693. // Check that the result type is not dependent.
  11694. if (ResultType->isDependentType())
  11695. return SemaRef.Diag(FnDecl->getLocation(),
  11696. diag::err_operator_new_delete_dependent_result_type)
  11697. << FnDecl->getDeclName() << ExpectedResultType;
  11698. // The operator is valid on any address space for OpenCL.
  11699. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11700. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11701. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11702. }
  11703. }
  11704. // Check that the result type is what we expect.
  11705. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11706. return SemaRef.Diag(FnDecl->getLocation(),
  11707. diag::err_operator_new_delete_invalid_result_type)
  11708. << FnDecl->getDeclName() << ExpectedResultType;
  11709. // A function template must have at least 2 parameters.
  11710. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11711. return SemaRef.Diag(FnDecl->getLocation(),
  11712. diag::err_operator_new_delete_template_too_few_parameters)
  11713. << FnDecl->getDeclName();
  11714. // The function decl must have at least 1 parameter.
  11715. if (FnDecl->getNumParams() == 0)
  11716. return SemaRef.Diag(FnDecl->getLocation(),
  11717. diag::err_operator_new_delete_too_few_parameters)
  11718. << FnDecl->getDeclName();
  11719. // Check the first parameter type is not dependent.
  11720. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11721. if (FirstParamType->isDependentType())
  11722. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11723. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11724. // Check that the first parameter type is what we expect.
  11725. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11726. // The operator is valid on any address space for OpenCL.
  11727. if (auto *PtrTy =
  11728. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11729. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11730. }
  11731. }
  11732. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11733. ExpectedFirstParamType)
  11734. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11735. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11736. return false;
  11737. }
  11738. static bool
  11739. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11740. // C++ [basic.stc.dynamic.allocation]p1:
  11741. // A program is ill-formed if an allocation function is declared in a
  11742. // namespace scope other than global scope or declared static in global
  11743. // scope.
  11744. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11745. return true;
  11746. CanQualType SizeTy =
  11747. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11748. // C++ [basic.stc.dynamic.allocation]p1:
  11749. // The return type shall be void*. The first parameter shall have type
  11750. // std::size_t.
  11751. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11752. SizeTy,
  11753. diag::err_operator_new_dependent_param_type,
  11754. diag::err_operator_new_param_type))
  11755. return true;
  11756. // C++ [basic.stc.dynamic.allocation]p1:
  11757. // The first parameter shall not have an associated default argument.
  11758. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11759. return SemaRef.Diag(FnDecl->getLocation(),
  11760. diag::err_operator_new_default_arg)
  11761. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11762. return false;
  11763. }
  11764. static bool
  11765. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11766. // C++ [basic.stc.dynamic.deallocation]p1:
  11767. // A program is ill-formed if deallocation functions are declared in a
  11768. // namespace scope other than global scope or declared static in global
  11769. // scope.
  11770. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11771. return true;
  11772. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11773. // C++ P0722:
  11774. // Within a class C, the first parameter of a destroying operator delete
  11775. // shall be of type C *. The first parameter of any other deallocation
  11776. // function shall be of type void *.
  11777. CanQualType ExpectedFirstParamType =
  11778. MD && MD->isDestroyingOperatorDelete()
  11779. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11780. SemaRef.Context.getRecordType(MD->getParent())))
  11781. : SemaRef.Context.VoidPtrTy;
  11782. // C++ [basic.stc.dynamic.deallocation]p2:
  11783. // Each deallocation function shall return void
  11784. if (CheckOperatorNewDeleteTypes(
  11785. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11786. diag::err_operator_delete_dependent_param_type,
  11787. diag::err_operator_delete_param_type))
  11788. return true;
  11789. // C++ P0722:
  11790. // A destroying operator delete shall be a usual deallocation function.
  11791. if (MD && !MD->getParent()->isDependentContext() &&
  11792. MD->isDestroyingOperatorDelete() &&
  11793. !SemaRef.isUsualDeallocationFunction(MD)) {
  11794. SemaRef.Diag(MD->getLocation(),
  11795. diag::err_destroying_operator_delete_not_usual);
  11796. return true;
  11797. }
  11798. return false;
  11799. }
  11800. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11801. /// of this overloaded operator is well-formed. If so, returns false;
  11802. /// otherwise, emits appropriate diagnostics and returns true.
  11803. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11804. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11805. "Expected an overloaded operator declaration");
  11806. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11807. // C++ [over.oper]p5:
  11808. // The allocation and deallocation functions, operator new,
  11809. // operator new[], operator delete and operator delete[], are
  11810. // described completely in 3.7.3. The attributes and restrictions
  11811. // found in the rest of this subclause do not apply to them unless
  11812. // explicitly stated in 3.7.3.
  11813. if (Op == OO_Delete || Op == OO_Array_Delete)
  11814. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11815. if (Op == OO_New || Op == OO_Array_New)
  11816. return CheckOperatorNewDeclaration(*this, FnDecl);
  11817. // C++ [over.oper]p6:
  11818. // An operator function shall either be a non-static member
  11819. // function or be a non-member function and have at least one
  11820. // parameter whose type is a class, a reference to a class, an
  11821. // enumeration, or a reference to an enumeration.
  11822. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11823. if (MethodDecl->isStatic())
  11824. return Diag(FnDecl->getLocation(),
  11825. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11826. } else {
  11827. bool ClassOrEnumParam = false;
  11828. for (auto Param : FnDecl->parameters()) {
  11829. QualType ParamType = Param->getType().getNonReferenceType();
  11830. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11831. ParamType->isEnumeralType()) {
  11832. ClassOrEnumParam = true;
  11833. break;
  11834. }
  11835. }
  11836. if (!ClassOrEnumParam)
  11837. return Diag(FnDecl->getLocation(),
  11838. diag::err_operator_overload_needs_class_or_enum)
  11839. << FnDecl->getDeclName();
  11840. }
  11841. // C++ [over.oper]p8:
  11842. // An operator function cannot have default arguments (8.3.6),
  11843. // except where explicitly stated below.
  11844. //
  11845. // Only the function-call operator allows default arguments
  11846. // (C++ [over.call]p1).
  11847. if (Op != OO_Call) {
  11848. for (auto Param : FnDecl->parameters()) {
  11849. if (Param->hasDefaultArg())
  11850. return Diag(Param->getLocation(),
  11851. diag::err_operator_overload_default_arg)
  11852. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11853. }
  11854. }
  11855. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11856. { false, false, false }
  11857. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11858. , { Unary, Binary, MemberOnly }
  11859. #include "clang/Basic/OperatorKinds.def"
  11860. };
  11861. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11862. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11863. bool MustBeMemberOperator = OperatorUses[Op][2];
  11864. // C++ [over.oper]p8:
  11865. // [...] Operator functions cannot have more or fewer parameters
  11866. // than the number required for the corresponding operator, as
  11867. // described in the rest of this subclause.
  11868. unsigned NumParams = FnDecl->getNumParams()
  11869. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11870. if (Op != OO_Call &&
  11871. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11872. (NumParams == 2 && !CanBeBinaryOperator) ||
  11873. (NumParams < 1) || (NumParams > 2))) {
  11874. // We have the wrong number of parameters.
  11875. unsigned ErrorKind;
  11876. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11877. ErrorKind = 2; // 2 -> unary or binary.
  11878. } else if (CanBeUnaryOperator) {
  11879. ErrorKind = 0; // 0 -> unary
  11880. } else {
  11881. assert(CanBeBinaryOperator &&
  11882. "All non-call overloaded operators are unary or binary!");
  11883. ErrorKind = 1; // 1 -> binary
  11884. }
  11885. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11886. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11887. }
  11888. // Overloaded operators other than operator() cannot be variadic.
  11889. if (Op != OO_Call &&
  11890. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11891. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11892. << FnDecl->getDeclName();
  11893. }
  11894. // Some operators must be non-static member functions.
  11895. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11896. return Diag(FnDecl->getLocation(),
  11897. diag::err_operator_overload_must_be_member)
  11898. << FnDecl->getDeclName();
  11899. }
  11900. // C++ [over.inc]p1:
  11901. // The user-defined function called operator++ implements the
  11902. // prefix and postfix ++ operator. If this function is a member
  11903. // function with no parameters, or a non-member function with one
  11904. // parameter of class or enumeration type, it defines the prefix
  11905. // increment operator ++ for objects of that type. If the function
  11906. // is a member function with one parameter (which shall be of type
  11907. // int) or a non-member function with two parameters (the second
  11908. // of which shall be of type int), it defines the postfix
  11909. // increment operator ++ for objects of that type.
  11910. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11911. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11912. QualType ParamType = LastParam->getType();
  11913. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11914. !ParamType->isDependentType())
  11915. return Diag(LastParam->getLocation(),
  11916. diag::err_operator_overload_post_incdec_must_be_int)
  11917. << LastParam->getType() << (Op == OO_MinusMinus);
  11918. }
  11919. return false;
  11920. }
  11921. static bool
  11922. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11923. FunctionTemplateDecl *TpDecl) {
  11924. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11925. // Must have one or two template parameters.
  11926. if (TemplateParams->size() == 1) {
  11927. NonTypeTemplateParmDecl *PmDecl =
  11928. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11929. // The template parameter must be a char parameter pack.
  11930. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11931. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11932. return false;
  11933. } else if (TemplateParams->size() == 2) {
  11934. TemplateTypeParmDecl *PmType =
  11935. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11936. NonTypeTemplateParmDecl *PmArgs =
  11937. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11938. // The second template parameter must be a parameter pack with the
  11939. // first template parameter as its type.
  11940. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11941. PmArgs->isTemplateParameterPack()) {
  11942. const TemplateTypeParmType *TArgs =
  11943. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11944. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11945. TArgs->getIndex() == PmType->getIndex()) {
  11946. if (!SemaRef.inTemplateInstantiation())
  11947. SemaRef.Diag(TpDecl->getLocation(),
  11948. diag::ext_string_literal_operator_template);
  11949. return false;
  11950. }
  11951. }
  11952. }
  11953. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11954. diag::err_literal_operator_template)
  11955. << TpDecl->getTemplateParameters()->getSourceRange();
  11956. return true;
  11957. }
  11958. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11959. /// of this literal operator function is well-formed. If so, returns
  11960. /// false; otherwise, emits appropriate diagnostics and returns true.
  11961. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11962. if (isa<CXXMethodDecl>(FnDecl)) {
  11963. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11964. << FnDecl->getDeclName();
  11965. return true;
  11966. }
  11967. if (FnDecl->isExternC()) {
  11968. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11969. if (const LinkageSpecDecl *LSD =
  11970. FnDecl->getDeclContext()->getExternCContext())
  11971. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11972. return true;
  11973. }
  11974. // This might be the definition of a literal operator template.
  11975. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11976. // This might be a specialization of a literal operator template.
  11977. if (!TpDecl)
  11978. TpDecl = FnDecl->getPrimaryTemplate();
  11979. // template <char...> type operator "" name() and
  11980. // template <class T, T...> type operator "" name() are the only valid
  11981. // template signatures, and the only valid signatures with no parameters.
  11982. if (TpDecl) {
  11983. if (FnDecl->param_size() != 0) {
  11984. Diag(FnDecl->getLocation(),
  11985. diag::err_literal_operator_template_with_params);
  11986. return true;
  11987. }
  11988. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11989. return true;
  11990. } else if (FnDecl->param_size() == 1) {
  11991. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11992. QualType ParamType = Param->getType().getUnqualifiedType();
  11993. // Only unsigned long long int, long double, any character type, and const
  11994. // char * are allowed as the only parameters.
  11995. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11996. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11997. Context.hasSameType(ParamType, Context.CharTy) ||
  11998. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11999. Context.hasSameType(ParamType, Context.Char8Ty) ||
  12000. Context.hasSameType(ParamType, Context.Char16Ty) ||
  12001. Context.hasSameType(ParamType, Context.Char32Ty)) {
  12002. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  12003. QualType InnerType = Ptr->getPointeeType();
  12004. // Pointer parameter must be a const char *.
  12005. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  12006. Context.CharTy) &&
  12007. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  12008. Diag(Param->getSourceRange().getBegin(),
  12009. diag::err_literal_operator_param)
  12010. << ParamType << "'const char *'" << Param->getSourceRange();
  12011. return true;
  12012. }
  12013. } else if (ParamType->isRealFloatingType()) {
  12014. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  12015. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  12016. return true;
  12017. } else if (ParamType->isIntegerType()) {
  12018. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  12019. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  12020. return true;
  12021. } else {
  12022. Diag(Param->getSourceRange().getBegin(),
  12023. diag::err_literal_operator_invalid_param)
  12024. << ParamType << Param->getSourceRange();
  12025. return true;
  12026. }
  12027. } else if (FnDecl->param_size() == 2) {
  12028. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  12029. // First, verify that the first parameter is correct.
  12030. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  12031. // Two parameter function must have a pointer to const as a
  12032. // first parameter; let's strip those qualifiers.
  12033. const PointerType *PT = FirstParamType->getAs<PointerType>();
  12034. if (!PT) {
  12035. Diag((*Param)->getSourceRange().getBegin(),
  12036. diag::err_literal_operator_param)
  12037. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12038. return true;
  12039. }
  12040. QualType PointeeType = PT->getPointeeType();
  12041. // First parameter must be const
  12042. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  12043. Diag((*Param)->getSourceRange().getBegin(),
  12044. diag::err_literal_operator_param)
  12045. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12046. return true;
  12047. }
  12048. QualType InnerType = PointeeType.getUnqualifiedType();
  12049. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  12050. // const char32_t* are allowed as the first parameter to a two-parameter
  12051. // function
  12052. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  12053. Context.hasSameType(InnerType, Context.WideCharTy) ||
  12054. Context.hasSameType(InnerType, Context.Char8Ty) ||
  12055. Context.hasSameType(InnerType, Context.Char16Ty) ||
  12056. Context.hasSameType(InnerType, Context.Char32Ty))) {
  12057. Diag((*Param)->getSourceRange().getBegin(),
  12058. diag::err_literal_operator_param)
  12059. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12060. return true;
  12061. }
  12062. // Move on to the second and final parameter.
  12063. ++Param;
  12064. // The second parameter must be a std::size_t.
  12065. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  12066. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  12067. Diag((*Param)->getSourceRange().getBegin(),
  12068. diag::err_literal_operator_param)
  12069. << SecondParamType << Context.getSizeType()
  12070. << (*Param)->getSourceRange();
  12071. return true;
  12072. }
  12073. } else {
  12074. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  12075. return true;
  12076. }
  12077. // Parameters are good.
  12078. // A parameter-declaration-clause containing a default argument is not
  12079. // equivalent to any of the permitted forms.
  12080. for (auto Param : FnDecl->parameters()) {
  12081. if (Param->hasDefaultArg()) {
  12082. Diag(Param->getDefaultArgRange().getBegin(),
  12083. diag::err_literal_operator_default_argument)
  12084. << Param->getDefaultArgRange();
  12085. break;
  12086. }
  12087. }
  12088. StringRef LiteralName
  12089. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  12090. if (LiteralName[0] != '_' &&
  12091. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  12092. // C++11 [usrlit.suffix]p1:
  12093. // Literal suffix identifiers that do not start with an underscore
  12094. // are reserved for future standardization.
  12095. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  12096. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  12097. }
  12098. return false;
  12099. }
  12100. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  12101. /// linkage specification, including the language and (if present)
  12102. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  12103. /// language string literal. LBraceLoc, if valid, provides the location of
  12104. /// the '{' brace. Otherwise, this linkage specification does not
  12105. /// have any braces.
  12106. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  12107. Expr *LangStr,
  12108. SourceLocation LBraceLoc) {
  12109. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  12110. if (!Lit->isAscii()) {
  12111. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  12112. << LangStr->getSourceRange();
  12113. return nullptr;
  12114. }
  12115. StringRef Lang = Lit->getString();
  12116. LinkageSpecDecl::LanguageIDs Language;
  12117. if (Lang == "C")
  12118. Language = LinkageSpecDecl::lang_c;
  12119. else if (Lang == "C++")
  12120. Language = LinkageSpecDecl::lang_cxx;
  12121. else if (Lang == "C++11")
  12122. Language = LinkageSpecDecl::lang_cxx_11;
  12123. else if (Lang == "C++14")
  12124. Language = LinkageSpecDecl::lang_cxx_14;
  12125. else {
  12126. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  12127. << LangStr->getSourceRange();
  12128. return nullptr;
  12129. }
  12130. // FIXME: Add all the various semantics of linkage specifications
  12131. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  12132. LangStr->getExprLoc(), Language,
  12133. LBraceLoc.isValid());
  12134. CurContext->addDecl(D);
  12135. PushDeclContext(S, D);
  12136. return D;
  12137. }
  12138. /// ActOnFinishLinkageSpecification - Complete the definition of
  12139. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  12140. /// valid, it's the position of the closing '}' brace in a linkage
  12141. /// specification that uses braces.
  12142. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  12143. Decl *LinkageSpec,
  12144. SourceLocation RBraceLoc) {
  12145. if (RBraceLoc.isValid()) {
  12146. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  12147. LSDecl->setRBraceLoc(RBraceLoc);
  12148. }
  12149. PopDeclContext();
  12150. return LinkageSpec;
  12151. }
  12152. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  12153. const ParsedAttributesView &AttrList,
  12154. SourceLocation SemiLoc) {
  12155. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  12156. // Attribute declarations appertain to empty declaration so we handle
  12157. // them here.
  12158. ProcessDeclAttributeList(S, ED, AttrList);
  12159. CurContext->addDecl(ED);
  12160. return ED;
  12161. }
  12162. /// Perform semantic analysis for the variable declaration that
  12163. /// occurs within a C++ catch clause, returning the newly-created
  12164. /// variable.
  12165. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  12166. TypeSourceInfo *TInfo,
  12167. SourceLocation StartLoc,
  12168. SourceLocation Loc,
  12169. IdentifierInfo *Name) {
  12170. bool Invalid = false;
  12171. QualType ExDeclType = TInfo->getType();
  12172. // Arrays and functions decay.
  12173. if (ExDeclType->isArrayType())
  12174. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  12175. else if (ExDeclType->isFunctionType())
  12176. ExDeclType = Context.getPointerType(ExDeclType);
  12177. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  12178. // The exception-declaration shall not denote a pointer or reference to an
  12179. // incomplete type, other than [cv] void*.
  12180. // N2844 forbids rvalue references.
  12181. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  12182. Diag(Loc, diag::err_catch_rvalue_ref);
  12183. Invalid = true;
  12184. }
  12185. if (ExDeclType->isVariablyModifiedType()) {
  12186. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  12187. Invalid = true;
  12188. }
  12189. QualType BaseType = ExDeclType;
  12190. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  12191. unsigned DK = diag::err_catch_incomplete;
  12192. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  12193. BaseType = Ptr->getPointeeType();
  12194. Mode = 1;
  12195. DK = diag::err_catch_incomplete_ptr;
  12196. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  12197. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  12198. BaseType = Ref->getPointeeType();
  12199. Mode = 2;
  12200. DK = diag::err_catch_incomplete_ref;
  12201. }
  12202. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  12203. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  12204. Invalid = true;
  12205. if (!Invalid && !ExDeclType->isDependentType() &&
  12206. RequireNonAbstractType(Loc, ExDeclType,
  12207. diag::err_abstract_type_in_decl,
  12208. AbstractVariableType))
  12209. Invalid = true;
  12210. // Only the non-fragile NeXT runtime currently supports C++ catches
  12211. // of ObjC types, and no runtime supports catching ObjC types by value.
  12212. if (!Invalid && getLangOpts().ObjC) {
  12213. QualType T = ExDeclType;
  12214. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  12215. T = RT->getPointeeType();
  12216. if (T->isObjCObjectType()) {
  12217. Diag(Loc, diag::err_objc_object_catch);
  12218. Invalid = true;
  12219. } else if (T->isObjCObjectPointerType()) {
  12220. // FIXME: should this be a test for macosx-fragile specifically?
  12221. if (getLangOpts().ObjCRuntime.isFragile())
  12222. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  12223. }
  12224. }
  12225. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  12226. ExDeclType, TInfo, SC_None);
  12227. ExDecl->setExceptionVariable(true);
  12228. // In ARC, infer 'retaining' for variables of retainable type.
  12229. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  12230. Invalid = true;
  12231. if (!Invalid && !ExDeclType->isDependentType()) {
  12232. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  12233. // Insulate this from anything else we might currently be parsing.
  12234. EnterExpressionEvaluationContext scope(
  12235. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12236. // C++ [except.handle]p16:
  12237. // The object declared in an exception-declaration or, if the
  12238. // exception-declaration does not specify a name, a temporary (12.2) is
  12239. // copy-initialized (8.5) from the exception object. [...]
  12240. // The object is destroyed when the handler exits, after the destruction
  12241. // of any automatic objects initialized within the handler.
  12242. //
  12243. // We just pretend to initialize the object with itself, then make sure
  12244. // it can be destroyed later.
  12245. QualType initType = Context.getExceptionObjectType(ExDeclType);
  12246. InitializedEntity entity =
  12247. InitializedEntity::InitializeVariable(ExDecl);
  12248. InitializationKind initKind =
  12249. InitializationKind::CreateCopy(Loc, SourceLocation());
  12250. Expr *opaqueValue =
  12251. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  12252. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  12253. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  12254. if (result.isInvalid())
  12255. Invalid = true;
  12256. else {
  12257. // If the constructor used was non-trivial, set this as the
  12258. // "initializer".
  12259. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  12260. if (!construct->getConstructor()->isTrivial()) {
  12261. Expr *init = MaybeCreateExprWithCleanups(construct);
  12262. ExDecl->setInit(init);
  12263. }
  12264. // And make sure it's destructable.
  12265. FinalizeVarWithDestructor(ExDecl, recordType);
  12266. }
  12267. }
  12268. }
  12269. if (Invalid)
  12270. ExDecl->setInvalidDecl();
  12271. return ExDecl;
  12272. }
  12273. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  12274. /// handler.
  12275. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  12276. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12277. bool Invalid = D.isInvalidType();
  12278. // Check for unexpanded parameter packs.
  12279. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12280. UPPC_ExceptionType)) {
  12281. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  12282. D.getIdentifierLoc());
  12283. Invalid = true;
  12284. }
  12285. IdentifierInfo *II = D.getIdentifier();
  12286. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  12287. LookupOrdinaryName,
  12288. ForVisibleRedeclaration)) {
  12289. // The scope should be freshly made just for us. There is just no way
  12290. // it contains any previous declaration, except for function parameters in
  12291. // a function-try-block's catch statement.
  12292. assert(!S->isDeclScope(PrevDecl));
  12293. if (isDeclInScope(PrevDecl, CurContext, S)) {
  12294. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  12295. << D.getIdentifier();
  12296. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12297. Invalid = true;
  12298. } else if (PrevDecl->isTemplateParameter())
  12299. // Maybe we will complain about the shadowed template parameter.
  12300. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12301. }
  12302. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  12303. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  12304. << D.getCXXScopeSpec().getRange();
  12305. Invalid = true;
  12306. }
  12307. VarDecl *ExDecl = BuildExceptionDeclaration(
  12308. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  12309. if (Invalid)
  12310. ExDecl->setInvalidDecl();
  12311. // Add the exception declaration into this scope.
  12312. if (II)
  12313. PushOnScopeChains(ExDecl, S);
  12314. else
  12315. CurContext->addDecl(ExDecl);
  12316. ProcessDeclAttributes(S, ExDecl, D);
  12317. return ExDecl;
  12318. }
  12319. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12320. Expr *AssertExpr,
  12321. Expr *AssertMessageExpr,
  12322. SourceLocation RParenLoc) {
  12323. StringLiteral *AssertMessage =
  12324. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  12325. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  12326. return nullptr;
  12327. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  12328. AssertMessage, RParenLoc, false);
  12329. }
  12330. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12331. Expr *AssertExpr,
  12332. StringLiteral *AssertMessage,
  12333. SourceLocation RParenLoc,
  12334. bool Failed) {
  12335. assert(AssertExpr != nullptr && "Expected non-null condition");
  12336. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  12337. !Failed) {
  12338. // In a static_assert-declaration, the constant-expression shall be a
  12339. // constant expression that can be contextually converted to bool.
  12340. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  12341. if (Converted.isInvalid())
  12342. Failed = true;
  12343. ExprResult FullAssertExpr =
  12344. ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
  12345. /*DiscardedValue*/ false,
  12346. /*IsConstexpr*/ true);
  12347. if (FullAssertExpr.isInvalid())
  12348. Failed = true;
  12349. else
  12350. AssertExpr = FullAssertExpr.get();
  12351. llvm::APSInt Cond;
  12352. if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
  12353. diag::err_static_assert_expression_is_not_constant,
  12354. /*AllowFold=*/false).isInvalid())
  12355. Failed = true;
  12356. if (!Failed && !Cond) {
  12357. SmallString<256> MsgBuffer;
  12358. llvm::raw_svector_ostream Msg(MsgBuffer);
  12359. if (AssertMessage)
  12360. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  12361. Expr *InnerCond = nullptr;
  12362. std::string InnerCondDescription;
  12363. std::tie(InnerCond, InnerCondDescription) =
  12364. findFailedBooleanCondition(Converted.get());
  12365. if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  12366. && !isa<IntegerLiteral>(InnerCond)) {
  12367. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  12368. << InnerCondDescription << !AssertMessage
  12369. << Msg.str() << InnerCond->getSourceRange();
  12370. } else {
  12371. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  12372. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  12373. }
  12374. Failed = true;
  12375. }
  12376. } else {
  12377. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  12378. /*DiscardedValue*/false,
  12379. /*IsConstexpr*/true);
  12380. if (FullAssertExpr.isInvalid())
  12381. Failed = true;
  12382. else
  12383. AssertExpr = FullAssertExpr.get();
  12384. }
  12385. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  12386. AssertExpr, AssertMessage, RParenLoc,
  12387. Failed);
  12388. CurContext->addDecl(Decl);
  12389. return Decl;
  12390. }
  12391. /// Perform semantic analysis of the given friend type declaration.
  12392. ///
  12393. /// \returns A friend declaration that.
  12394. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  12395. SourceLocation FriendLoc,
  12396. TypeSourceInfo *TSInfo) {
  12397. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  12398. QualType T = TSInfo->getType();
  12399. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  12400. // C++03 [class.friend]p2:
  12401. // An elaborated-type-specifier shall be used in a friend declaration
  12402. // for a class.*
  12403. //
  12404. // * The class-key of the elaborated-type-specifier is required.
  12405. if (!CodeSynthesisContexts.empty()) {
  12406. // Do not complain about the form of friend template types during any kind
  12407. // of code synthesis. For template instantiation, we will have complained
  12408. // when the template was defined.
  12409. } else {
  12410. if (!T->isElaboratedTypeSpecifier()) {
  12411. // If we evaluated the type to a record type, suggest putting
  12412. // a tag in front.
  12413. if (const RecordType *RT = T->getAs<RecordType>()) {
  12414. RecordDecl *RD = RT->getDecl();
  12415. SmallString<16> InsertionText(" ");
  12416. InsertionText += RD->getKindName();
  12417. Diag(TypeRange.getBegin(),
  12418. getLangOpts().CPlusPlus11 ?
  12419. diag::warn_cxx98_compat_unelaborated_friend_type :
  12420. diag::ext_unelaborated_friend_type)
  12421. << (unsigned) RD->getTagKind()
  12422. << T
  12423. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12424. InsertionText);
  12425. } else {
  12426. Diag(FriendLoc,
  12427. getLangOpts().CPlusPlus11 ?
  12428. diag::warn_cxx98_compat_nonclass_type_friend :
  12429. diag::ext_nonclass_type_friend)
  12430. << T
  12431. << TypeRange;
  12432. }
  12433. } else if (T->getAs<EnumType>()) {
  12434. Diag(FriendLoc,
  12435. getLangOpts().CPlusPlus11 ?
  12436. diag::warn_cxx98_compat_enum_friend :
  12437. diag::ext_enum_friend)
  12438. << T
  12439. << TypeRange;
  12440. }
  12441. // C++11 [class.friend]p3:
  12442. // A friend declaration that does not declare a function shall have one
  12443. // of the following forms:
  12444. // friend elaborated-type-specifier ;
  12445. // friend simple-type-specifier ;
  12446. // friend typename-specifier ;
  12447. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12448. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12449. }
  12450. // If the type specifier in a friend declaration designates a (possibly
  12451. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12452. // the friend declaration is ignored.
  12453. return FriendDecl::Create(Context, CurContext,
  12454. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12455. FriendLoc);
  12456. }
  12457. /// Handle a friend tag declaration where the scope specifier was
  12458. /// templated.
  12459. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12460. unsigned TagSpec, SourceLocation TagLoc,
  12461. CXXScopeSpec &SS, IdentifierInfo *Name,
  12462. SourceLocation NameLoc,
  12463. const ParsedAttributesView &Attr,
  12464. MultiTemplateParamsArg TempParamLists) {
  12465. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12466. bool IsMemberSpecialization = false;
  12467. bool Invalid = false;
  12468. if (TemplateParameterList *TemplateParams =
  12469. MatchTemplateParametersToScopeSpecifier(
  12470. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12471. IsMemberSpecialization, Invalid)) {
  12472. if (TemplateParams->size() > 0) {
  12473. // This is a declaration of a class template.
  12474. if (Invalid)
  12475. return nullptr;
  12476. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12477. NameLoc, Attr, TemplateParams, AS_public,
  12478. /*ModulePrivateLoc=*/SourceLocation(),
  12479. FriendLoc, TempParamLists.size() - 1,
  12480. TempParamLists.data()).get();
  12481. } else {
  12482. // The "template<>" header is extraneous.
  12483. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12484. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12485. IsMemberSpecialization = true;
  12486. }
  12487. }
  12488. if (Invalid) return nullptr;
  12489. bool isAllExplicitSpecializations = true;
  12490. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12491. if (TempParamLists[I]->size()) {
  12492. isAllExplicitSpecializations = false;
  12493. break;
  12494. }
  12495. }
  12496. // FIXME: don't ignore attributes.
  12497. // If it's explicit specializations all the way down, just forget
  12498. // about the template header and build an appropriate non-templated
  12499. // friend. TODO: for source fidelity, remember the headers.
  12500. if (isAllExplicitSpecializations) {
  12501. if (SS.isEmpty()) {
  12502. bool Owned = false;
  12503. bool IsDependent = false;
  12504. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12505. Attr, AS_public,
  12506. /*ModulePrivateLoc=*/SourceLocation(),
  12507. MultiTemplateParamsArg(), Owned, IsDependent,
  12508. /*ScopedEnumKWLoc=*/SourceLocation(),
  12509. /*ScopedEnumUsesClassTag=*/false,
  12510. /*UnderlyingType=*/TypeResult(),
  12511. /*IsTypeSpecifier=*/false,
  12512. /*IsTemplateParamOrArg=*/false);
  12513. }
  12514. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12515. ElaboratedTypeKeyword Keyword
  12516. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12517. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12518. *Name, NameLoc);
  12519. if (T.isNull())
  12520. return nullptr;
  12521. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12522. if (isa<DependentNameType>(T)) {
  12523. DependentNameTypeLoc TL =
  12524. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12525. TL.setElaboratedKeywordLoc(TagLoc);
  12526. TL.setQualifierLoc(QualifierLoc);
  12527. TL.setNameLoc(NameLoc);
  12528. } else {
  12529. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12530. TL.setElaboratedKeywordLoc(TagLoc);
  12531. TL.setQualifierLoc(QualifierLoc);
  12532. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12533. }
  12534. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12535. TSI, FriendLoc, TempParamLists);
  12536. Friend->setAccess(AS_public);
  12537. CurContext->addDecl(Friend);
  12538. return Friend;
  12539. }
  12540. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12541. // Handle the case of a templated-scope friend class. e.g.
  12542. // template <class T> class A<T>::B;
  12543. // FIXME: we don't support these right now.
  12544. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12545. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12546. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12547. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12548. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12549. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12550. TL.setElaboratedKeywordLoc(TagLoc);
  12551. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12552. TL.setNameLoc(NameLoc);
  12553. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12554. TSI, FriendLoc, TempParamLists);
  12555. Friend->setAccess(AS_public);
  12556. Friend->setUnsupportedFriend(true);
  12557. CurContext->addDecl(Friend);
  12558. return Friend;
  12559. }
  12560. /// Handle a friend type declaration. This works in tandem with
  12561. /// ActOnTag.
  12562. ///
  12563. /// Notes on friend class templates:
  12564. ///
  12565. /// We generally treat friend class declarations as if they were
  12566. /// declaring a class. So, for example, the elaborated type specifier
  12567. /// in a friend declaration is required to obey the restrictions of a
  12568. /// class-head (i.e. no typedefs in the scope chain), template
  12569. /// parameters are required to match up with simple template-ids, &c.
  12570. /// However, unlike when declaring a template specialization, it's
  12571. /// okay to refer to a template specialization without an empty
  12572. /// template parameter declaration, e.g.
  12573. /// friend class A<T>::B<unsigned>;
  12574. /// We permit this as a special case; if there are any template
  12575. /// parameters present at all, require proper matching, i.e.
  12576. /// template <> template \<class T> friend class A<int>::B;
  12577. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12578. MultiTemplateParamsArg TempParams) {
  12579. SourceLocation Loc = DS.getBeginLoc();
  12580. assert(DS.isFriendSpecified());
  12581. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12582. // C++ [class.friend]p3:
  12583. // A friend declaration that does not declare a function shall have one of
  12584. // the following forms:
  12585. // friend elaborated-type-specifier ;
  12586. // friend simple-type-specifier ;
  12587. // friend typename-specifier ;
  12588. //
  12589. // Any declaration with a type qualifier does not have that form. (It's
  12590. // legal to specify a qualified type as a friend, you just can't write the
  12591. // keywords.)
  12592. if (DS.getTypeQualifiers()) {
  12593. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12594. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12595. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12596. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12597. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12598. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12599. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12600. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12601. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12602. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12603. }
  12604. // Try to convert the decl specifier to a type. This works for
  12605. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12606. // for a TUK_Friend.
  12607. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12608. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12609. QualType T = TSI->getType();
  12610. if (TheDeclarator.isInvalidType())
  12611. return nullptr;
  12612. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12613. return nullptr;
  12614. // This is definitely an error in C++98. It's probably meant to
  12615. // be forbidden in C++0x, too, but the specification is just
  12616. // poorly written.
  12617. //
  12618. // The problem is with declarations like the following:
  12619. // template <T> friend A<T>::foo;
  12620. // where deciding whether a class C is a friend or not now hinges
  12621. // on whether there exists an instantiation of A that causes
  12622. // 'foo' to equal C. There are restrictions on class-heads
  12623. // (which we declare (by fiat) elaborated friend declarations to
  12624. // be) that makes this tractable.
  12625. //
  12626. // FIXME: handle "template <> friend class A<T>;", which
  12627. // is possibly well-formed? Who even knows?
  12628. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12629. Diag(Loc, diag::err_tagless_friend_type_template)
  12630. << DS.getSourceRange();
  12631. return nullptr;
  12632. }
  12633. // C++98 [class.friend]p1: A friend of a class is a function
  12634. // or class that is not a member of the class . . .
  12635. // This is fixed in DR77, which just barely didn't make the C++03
  12636. // deadline. It's also a very silly restriction that seriously
  12637. // affects inner classes and which nobody else seems to implement;
  12638. // thus we never diagnose it, not even in -pedantic.
  12639. //
  12640. // But note that we could warn about it: it's always useless to
  12641. // friend one of your own members (it's not, however, worthless to
  12642. // friend a member of an arbitrary specialization of your template).
  12643. Decl *D;
  12644. if (!TempParams.empty())
  12645. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12646. TempParams,
  12647. TSI,
  12648. DS.getFriendSpecLoc());
  12649. else
  12650. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12651. if (!D)
  12652. return nullptr;
  12653. D->setAccess(AS_public);
  12654. CurContext->addDecl(D);
  12655. return D;
  12656. }
  12657. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12658. MultiTemplateParamsArg TemplateParams) {
  12659. const DeclSpec &DS = D.getDeclSpec();
  12660. assert(DS.isFriendSpecified());
  12661. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12662. SourceLocation Loc = D.getIdentifierLoc();
  12663. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12664. // C++ [class.friend]p1
  12665. // A friend of a class is a function or class....
  12666. // Note that this sees through typedefs, which is intended.
  12667. // It *doesn't* see through dependent types, which is correct
  12668. // according to [temp.arg.type]p3:
  12669. // If a declaration acquires a function type through a
  12670. // type dependent on a template-parameter and this causes
  12671. // a declaration that does not use the syntactic form of a
  12672. // function declarator to have a function type, the program
  12673. // is ill-formed.
  12674. if (!TInfo->getType()->isFunctionType()) {
  12675. Diag(Loc, diag::err_unexpected_friend);
  12676. // It might be worthwhile to try to recover by creating an
  12677. // appropriate declaration.
  12678. return nullptr;
  12679. }
  12680. // C++ [namespace.memdef]p3
  12681. // - If a friend declaration in a non-local class first declares a
  12682. // class or function, the friend class or function is a member
  12683. // of the innermost enclosing namespace.
  12684. // - The name of the friend is not found by simple name lookup
  12685. // until a matching declaration is provided in that namespace
  12686. // scope (either before or after the class declaration granting
  12687. // friendship).
  12688. // - If a friend function is called, its name may be found by the
  12689. // name lookup that considers functions from namespaces and
  12690. // classes associated with the types of the function arguments.
  12691. // - When looking for a prior declaration of a class or a function
  12692. // declared as a friend, scopes outside the innermost enclosing
  12693. // namespace scope are not considered.
  12694. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12695. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12696. assert(NameInfo.getName());
  12697. // Check for unexpanded parameter packs.
  12698. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12699. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12700. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12701. return nullptr;
  12702. // The context we found the declaration in, or in which we should
  12703. // create the declaration.
  12704. DeclContext *DC;
  12705. Scope *DCScope = S;
  12706. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12707. ForExternalRedeclaration);
  12708. // There are five cases here.
  12709. // - There's no scope specifier and we're in a local class. Only look
  12710. // for functions declared in the immediately-enclosing block scope.
  12711. // We recover from invalid scope qualifiers as if they just weren't there.
  12712. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12713. if ((SS.isInvalid() || !SS.isSet()) &&
  12714. (FunctionContainingLocalClass =
  12715. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12716. // C++11 [class.friend]p11:
  12717. // If a friend declaration appears in a local class and the name
  12718. // specified is an unqualified name, a prior declaration is
  12719. // looked up without considering scopes that are outside the
  12720. // innermost enclosing non-class scope. For a friend function
  12721. // declaration, if there is no prior declaration, the program is
  12722. // ill-formed.
  12723. // Find the innermost enclosing non-class scope. This is the block
  12724. // scope containing the local class definition (or for a nested class,
  12725. // the outer local class).
  12726. DCScope = S->getFnParent();
  12727. // Look up the function name in the scope.
  12728. Previous.clear(LookupLocalFriendName);
  12729. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12730. if (!Previous.empty()) {
  12731. // All possible previous declarations must have the same context:
  12732. // either they were declared at block scope or they are members of
  12733. // one of the enclosing local classes.
  12734. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12735. } else {
  12736. // This is ill-formed, but provide the context that we would have
  12737. // declared the function in, if we were permitted to, for error recovery.
  12738. DC = FunctionContainingLocalClass;
  12739. }
  12740. adjustContextForLocalExternDecl(DC);
  12741. // C++ [class.friend]p6:
  12742. // A function can be defined in a friend declaration of a class if and
  12743. // only if the class is a non-local class (9.8), the function name is
  12744. // unqualified, and the function has namespace scope.
  12745. if (D.isFunctionDefinition()) {
  12746. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12747. }
  12748. // - There's no scope specifier, in which case we just go to the
  12749. // appropriate scope and look for a function or function template
  12750. // there as appropriate.
  12751. } else if (SS.isInvalid() || !SS.isSet()) {
  12752. // C++11 [namespace.memdef]p3:
  12753. // If the name in a friend declaration is neither qualified nor
  12754. // a template-id and the declaration is a function or an
  12755. // elaborated-type-specifier, the lookup to determine whether
  12756. // the entity has been previously declared shall not consider
  12757. // any scopes outside the innermost enclosing namespace.
  12758. bool isTemplateId =
  12759. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12760. // Find the appropriate context according to the above.
  12761. DC = CurContext;
  12762. // Skip class contexts. If someone can cite chapter and verse
  12763. // for this behavior, that would be nice --- it's what GCC and
  12764. // EDG do, and it seems like a reasonable intent, but the spec
  12765. // really only says that checks for unqualified existing
  12766. // declarations should stop at the nearest enclosing namespace,
  12767. // not that they should only consider the nearest enclosing
  12768. // namespace.
  12769. while (DC->isRecord())
  12770. DC = DC->getParent();
  12771. DeclContext *LookupDC = DC;
  12772. while (LookupDC->isTransparentContext())
  12773. LookupDC = LookupDC->getParent();
  12774. while (true) {
  12775. LookupQualifiedName(Previous, LookupDC);
  12776. if (!Previous.empty()) {
  12777. DC = LookupDC;
  12778. break;
  12779. }
  12780. if (isTemplateId) {
  12781. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12782. } else {
  12783. if (LookupDC->isFileContext()) break;
  12784. }
  12785. LookupDC = LookupDC->getParent();
  12786. }
  12787. DCScope = getScopeForDeclContext(S, DC);
  12788. // - There's a non-dependent scope specifier, in which case we
  12789. // compute it and do a previous lookup there for a function
  12790. // or function template.
  12791. } else if (!SS.getScopeRep()->isDependent()) {
  12792. DC = computeDeclContext(SS);
  12793. if (!DC) return nullptr;
  12794. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12795. LookupQualifiedName(Previous, DC);
  12796. // C++ [class.friend]p1: A friend of a class is a function or
  12797. // class that is not a member of the class . . .
  12798. if (DC->Equals(CurContext))
  12799. Diag(DS.getFriendSpecLoc(),
  12800. getLangOpts().CPlusPlus11 ?
  12801. diag::warn_cxx98_compat_friend_is_member :
  12802. diag::err_friend_is_member);
  12803. if (D.isFunctionDefinition()) {
  12804. // C++ [class.friend]p6:
  12805. // A function can be defined in a friend declaration of a class if and
  12806. // only if the class is a non-local class (9.8), the function name is
  12807. // unqualified, and the function has namespace scope.
  12808. //
  12809. // FIXME: We should only do this if the scope specifier names the
  12810. // innermost enclosing namespace; otherwise the fixit changes the
  12811. // meaning of the code.
  12812. SemaDiagnosticBuilder DB
  12813. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12814. DB << SS.getScopeRep();
  12815. if (DC->isFileContext())
  12816. DB << FixItHint::CreateRemoval(SS.getRange());
  12817. SS.clear();
  12818. }
  12819. // - There's a scope specifier that does not match any template
  12820. // parameter lists, in which case we use some arbitrary context,
  12821. // create a method or method template, and wait for instantiation.
  12822. // - There's a scope specifier that does match some template
  12823. // parameter lists, which we don't handle right now.
  12824. } else {
  12825. if (D.isFunctionDefinition()) {
  12826. // C++ [class.friend]p6:
  12827. // A function can be defined in a friend declaration of a class if and
  12828. // only if the class is a non-local class (9.8), the function name is
  12829. // unqualified, and the function has namespace scope.
  12830. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12831. << SS.getScopeRep();
  12832. }
  12833. DC = CurContext;
  12834. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12835. }
  12836. if (!DC->isRecord()) {
  12837. int DiagArg = -1;
  12838. switch (D.getName().getKind()) {
  12839. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12840. case UnqualifiedIdKind::IK_ConstructorName:
  12841. DiagArg = 0;
  12842. break;
  12843. case UnqualifiedIdKind::IK_DestructorName:
  12844. DiagArg = 1;
  12845. break;
  12846. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12847. DiagArg = 2;
  12848. break;
  12849. case UnqualifiedIdKind::IK_DeductionGuideName:
  12850. DiagArg = 3;
  12851. break;
  12852. case UnqualifiedIdKind::IK_Identifier:
  12853. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12854. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12855. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12856. case UnqualifiedIdKind::IK_TemplateId:
  12857. break;
  12858. }
  12859. // This implies that it has to be an operator or function.
  12860. if (DiagArg >= 0) {
  12861. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12862. return nullptr;
  12863. }
  12864. }
  12865. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12866. // does not contain the declaration context, i.e., in an out-of-line
  12867. // definition of a class.
  12868. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12869. if (!DCScope) {
  12870. FakeDCScope.setEntity(DC);
  12871. DCScope = &FakeDCScope;
  12872. }
  12873. bool AddToScope = true;
  12874. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12875. TemplateParams, AddToScope);
  12876. if (!ND) return nullptr;
  12877. assert(ND->getLexicalDeclContext() == CurContext);
  12878. // If we performed typo correction, we might have added a scope specifier
  12879. // and changed the decl context.
  12880. DC = ND->getDeclContext();
  12881. // Add the function declaration to the appropriate lookup tables,
  12882. // adjusting the redeclarations list as necessary. We don't
  12883. // want to do this yet if the friending class is dependent.
  12884. //
  12885. // Also update the scope-based lookup if the target context's
  12886. // lookup context is in lexical scope.
  12887. if (!CurContext->isDependentContext()) {
  12888. DC = DC->getRedeclContext();
  12889. DC->makeDeclVisibleInContext(ND);
  12890. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12891. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12892. }
  12893. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12894. D.getIdentifierLoc(), ND,
  12895. DS.getFriendSpecLoc());
  12896. FrD->setAccess(AS_public);
  12897. CurContext->addDecl(FrD);
  12898. if (ND->isInvalidDecl()) {
  12899. FrD->setInvalidDecl();
  12900. } else {
  12901. if (DC->isRecord()) CheckFriendAccess(ND);
  12902. FunctionDecl *FD;
  12903. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12904. FD = FTD->getTemplatedDecl();
  12905. else
  12906. FD = cast<FunctionDecl>(ND);
  12907. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12908. // default argument expression, that declaration shall be a definition
  12909. // and shall be the only declaration of the function or function
  12910. // template in the translation unit.
  12911. if (functionDeclHasDefaultArgument(FD)) {
  12912. // We can't look at FD->getPreviousDecl() because it may not have been set
  12913. // if we're in a dependent context. If the function is known to be a
  12914. // redeclaration, we will have narrowed Previous down to the right decl.
  12915. if (D.isRedeclaration()) {
  12916. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12917. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12918. diag::note_previous_declaration);
  12919. } else if (!D.isFunctionDefinition())
  12920. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12921. }
  12922. // Mark templated-scope function declarations as unsupported.
  12923. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12924. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12925. << SS.getScopeRep() << SS.getRange()
  12926. << cast<CXXRecordDecl>(CurContext);
  12927. FrD->setUnsupportedFriend(true);
  12928. }
  12929. }
  12930. return ND;
  12931. }
  12932. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12933. AdjustDeclIfTemplate(Dcl);
  12934. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12935. if (!Fn) {
  12936. Diag(DelLoc, diag::err_deleted_non_function);
  12937. return;
  12938. }
  12939. // Deleted function does not have a body.
  12940. Fn->setWillHaveBody(false);
  12941. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12942. // Don't consider the implicit declaration we generate for explicit
  12943. // specializations. FIXME: Do not generate these implicit declarations.
  12944. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12945. Prev->getPreviousDecl()) &&
  12946. !Prev->isDefined()) {
  12947. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12948. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12949. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12950. : diag::note_previous_declaration);
  12951. }
  12952. // If the declaration wasn't the first, we delete the function anyway for
  12953. // recovery.
  12954. Fn = Fn->getCanonicalDecl();
  12955. }
  12956. // dllimport/dllexport cannot be deleted.
  12957. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12958. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12959. Fn->setInvalidDecl();
  12960. }
  12961. if (Fn->isDeleted())
  12962. return;
  12963. // See if we're deleting a function which is already known to override a
  12964. // non-deleted virtual function.
  12965. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12966. bool IssuedDiagnostic = false;
  12967. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12968. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12969. if (!IssuedDiagnostic) {
  12970. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12971. IssuedDiagnostic = true;
  12972. }
  12973. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12974. }
  12975. }
  12976. // If this function was implicitly deleted because it was defaulted,
  12977. // explain why it was deleted.
  12978. if (IssuedDiagnostic && MD->isDefaulted())
  12979. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12980. /*Diagnose*/true);
  12981. }
  12982. // C++11 [basic.start.main]p3:
  12983. // A program that defines main as deleted [...] is ill-formed.
  12984. if (Fn->isMain())
  12985. Diag(DelLoc, diag::err_deleted_main);
  12986. // C++11 [dcl.fct.def.delete]p4:
  12987. // A deleted function is implicitly inline.
  12988. Fn->setImplicitlyInline();
  12989. Fn->setDeletedAsWritten();
  12990. }
  12991. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12992. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12993. if (MD) {
  12994. if (MD->getParent()->isDependentType()) {
  12995. MD->setDefaulted();
  12996. MD->setExplicitlyDefaulted();
  12997. return;
  12998. }
  12999. CXXSpecialMember Member = getSpecialMember(MD);
  13000. if (Member == CXXInvalid) {
  13001. if (!MD->isInvalidDecl())
  13002. Diag(DefaultLoc, diag::err_default_special_members);
  13003. return;
  13004. }
  13005. MD->setDefaulted();
  13006. MD->setExplicitlyDefaulted();
  13007. // Unset that we will have a body for this function. We might not,
  13008. // if it turns out to be trivial, and we don't need this marking now
  13009. // that we've marked it as defaulted.
  13010. MD->setWillHaveBody(false);
  13011. // If this definition appears within the record, do the checking when
  13012. // the record is complete.
  13013. const FunctionDecl *Primary = MD;
  13014. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  13015. // Ask the template instantiation pattern that actually had the
  13016. // '= default' on it.
  13017. Primary = Pattern;
  13018. // If the method was defaulted on its first declaration, we will have
  13019. // already performed the checking in CheckCompletedCXXClass. Such a
  13020. // declaration doesn't trigger an implicit definition.
  13021. if (Primary->getCanonicalDecl()->isDefaulted())
  13022. return;
  13023. CheckExplicitlyDefaultedSpecialMember(MD);
  13024. if (!MD->isInvalidDecl())
  13025. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  13026. } else {
  13027. Diag(DefaultLoc, diag::err_default_special_members);
  13028. }
  13029. }
  13030. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  13031. for (Stmt *SubStmt : S->children()) {
  13032. if (!SubStmt)
  13033. continue;
  13034. if (isa<ReturnStmt>(SubStmt))
  13035. Self.Diag(SubStmt->getBeginLoc(),
  13036. diag::err_return_in_constructor_handler);
  13037. if (!isa<Expr>(SubStmt))
  13038. SearchForReturnInStmt(Self, SubStmt);
  13039. }
  13040. }
  13041. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  13042. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  13043. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  13044. SearchForReturnInStmt(*this, Handler);
  13045. }
  13046. }
  13047. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  13048. const CXXMethodDecl *Old) {
  13049. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  13050. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  13051. if (OldFT->hasExtParameterInfos()) {
  13052. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  13053. // A parameter of the overriding method should be annotated with noescape
  13054. // if the corresponding parameter of the overridden method is annotated.
  13055. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  13056. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  13057. Diag(New->getParamDecl(I)->getLocation(),
  13058. diag::warn_overriding_method_missing_noescape);
  13059. Diag(Old->getParamDecl(I)->getLocation(),
  13060. diag::note_overridden_marked_noescape);
  13061. }
  13062. }
  13063. // Virtual overrides must have the same code_seg.
  13064. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  13065. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  13066. if ((NewCSA || OldCSA) &&
  13067. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  13068. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  13069. Diag(Old->getLocation(), diag::note_previous_declaration);
  13070. return true;
  13071. }
  13072. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  13073. // If the calling conventions match, everything is fine
  13074. if (NewCC == OldCC)
  13075. return false;
  13076. // If the calling conventions mismatch because the new function is static,
  13077. // suppress the calling convention mismatch error; the error about static
  13078. // function override (err_static_overrides_virtual from
  13079. // Sema::CheckFunctionDeclaration) is more clear.
  13080. if (New->getStorageClass() == SC_Static)
  13081. return false;
  13082. Diag(New->getLocation(),
  13083. diag::err_conflicting_overriding_cc_attributes)
  13084. << New->getDeclName() << New->getType() << Old->getType();
  13085. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  13086. return true;
  13087. }
  13088. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  13089. const CXXMethodDecl *Old) {
  13090. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  13091. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  13092. if (Context.hasSameType(NewTy, OldTy) ||
  13093. NewTy->isDependentType() || OldTy->isDependentType())
  13094. return false;
  13095. // Check if the return types are covariant
  13096. QualType NewClassTy, OldClassTy;
  13097. /// Both types must be pointers or references to classes.
  13098. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  13099. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  13100. NewClassTy = NewPT->getPointeeType();
  13101. OldClassTy = OldPT->getPointeeType();
  13102. }
  13103. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  13104. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  13105. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  13106. NewClassTy = NewRT->getPointeeType();
  13107. OldClassTy = OldRT->getPointeeType();
  13108. }
  13109. }
  13110. }
  13111. // The return types aren't either both pointers or references to a class type.
  13112. if (NewClassTy.isNull()) {
  13113. Diag(New->getLocation(),
  13114. diag::err_different_return_type_for_overriding_virtual_function)
  13115. << New->getDeclName() << NewTy << OldTy
  13116. << New->getReturnTypeSourceRange();
  13117. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13118. << Old->getReturnTypeSourceRange();
  13119. return true;
  13120. }
  13121. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  13122. // C++14 [class.virtual]p8:
  13123. // If the class type in the covariant return type of D::f differs from
  13124. // that of B::f, the class type in the return type of D::f shall be
  13125. // complete at the point of declaration of D::f or shall be the class
  13126. // type D.
  13127. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  13128. if (!RT->isBeingDefined() &&
  13129. RequireCompleteType(New->getLocation(), NewClassTy,
  13130. diag::err_covariant_return_incomplete,
  13131. New->getDeclName()))
  13132. return true;
  13133. }
  13134. // Check if the new class derives from the old class.
  13135. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  13136. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  13137. << New->getDeclName() << NewTy << OldTy
  13138. << New->getReturnTypeSourceRange();
  13139. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13140. << Old->getReturnTypeSourceRange();
  13141. return true;
  13142. }
  13143. // Check if we the conversion from derived to base is valid.
  13144. if (CheckDerivedToBaseConversion(
  13145. NewClassTy, OldClassTy,
  13146. diag::err_covariant_return_inaccessible_base,
  13147. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  13148. New->getLocation(), New->getReturnTypeSourceRange(),
  13149. New->getDeclName(), nullptr)) {
  13150. // FIXME: this note won't trigger for delayed access control
  13151. // diagnostics, and it's impossible to get an undelayed error
  13152. // here from access control during the original parse because
  13153. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  13154. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13155. << Old->getReturnTypeSourceRange();
  13156. return true;
  13157. }
  13158. }
  13159. // The qualifiers of the return types must be the same.
  13160. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  13161. Diag(New->getLocation(),
  13162. diag::err_covariant_return_type_different_qualifications)
  13163. << New->getDeclName() << NewTy << OldTy
  13164. << New->getReturnTypeSourceRange();
  13165. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13166. << Old->getReturnTypeSourceRange();
  13167. return true;
  13168. }
  13169. // The new class type must have the same or less qualifiers as the old type.
  13170. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  13171. Diag(New->getLocation(),
  13172. diag::err_covariant_return_type_class_type_more_qualified)
  13173. << New->getDeclName() << NewTy << OldTy
  13174. << New->getReturnTypeSourceRange();
  13175. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13176. << Old->getReturnTypeSourceRange();
  13177. return true;
  13178. }
  13179. return false;
  13180. }
  13181. /// Mark the given method pure.
  13182. ///
  13183. /// \param Method the method to be marked pure.
  13184. ///
  13185. /// \param InitRange the source range that covers the "0" initializer.
  13186. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  13187. SourceLocation EndLoc = InitRange.getEnd();
  13188. if (EndLoc.isValid())
  13189. Method->setRangeEnd(EndLoc);
  13190. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  13191. Method->setPure();
  13192. return false;
  13193. }
  13194. if (!Method->isInvalidDecl())
  13195. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  13196. << Method->getDeclName() << InitRange;
  13197. return true;
  13198. }
  13199. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  13200. if (D->getFriendObjectKind())
  13201. Diag(D->getLocation(), diag::err_pure_friend);
  13202. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  13203. CheckPureMethod(M, ZeroLoc);
  13204. else
  13205. Diag(D->getLocation(), diag::err_illegal_initializer);
  13206. }
  13207. /// Determine whether the given declaration is a global variable or
  13208. /// static data member.
  13209. static bool isNonlocalVariable(const Decl *D) {
  13210. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  13211. return Var->hasGlobalStorage();
  13212. return false;
  13213. }
  13214. /// Invoked when we are about to parse an initializer for the declaration
  13215. /// 'Dcl'.
  13216. ///
  13217. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  13218. /// static data member of class X, names should be looked up in the scope of
  13219. /// class X. If the declaration had a scope specifier, a scope will have
  13220. /// been created and passed in for this purpose. Otherwise, S will be null.
  13221. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  13222. // If there is no declaration, there was an error parsing it.
  13223. if (!D || D->isInvalidDecl())
  13224. return;
  13225. // We will always have a nested name specifier here, but this declaration
  13226. // might not be out of line if the specifier names the current namespace:
  13227. // extern int n;
  13228. // int ::n = 0;
  13229. if (S && D->isOutOfLine())
  13230. EnterDeclaratorContext(S, D->getDeclContext());
  13231. // If we are parsing the initializer for a static data member, push a
  13232. // new expression evaluation context that is associated with this static
  13233. // data member.
  13234. if (isNonlocalVariable(D))
  13235. PushExpressionEvaluationContext(
  13236. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  13237. }
  13238. /// Invoked after we are finished parsing an initializer for the declaration D.
  13239. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  13240. // If there is no declaration, there was an error parsing it.
  13241. if (!D || D->isInvalidDecl())
  13242. return;
  13243. if (isNonlocalVariable(D))
  13244. PopExpressionEvaluationContext();
  13245. if (S && D->isOutOfLine())
  13246. ExitDeclaratorContext(S);
  13247. }
  13248. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  13249. /// C++ if/switch/while/for statement.
  13250. /// e.g: "if (int x = f()) {...}"
  13251. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  13252. // C++ 6.4p2:
  13253. // The declarator shall not specify a function or an array.
  13254. // The type-specifier-seq shall not contain typedef and shall not declare a
  13255. // new class or enumeration.
  13256. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  13257. "Parser allowed 'typedef' as storage class of condition decl.");
  13258. Decl *Dcl = ActOnDeclarator(S, D);
  13259. if (!Dcl)
  13260. return true;
  13261. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  13262. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  13263. << D.getSourceRange();
  13264. return true;
  13265. }
  13266. return Dcl;
  13267. }
  13268. void Sema::LoadExternalVTableUses() {
  13269. if (!ExternalSource)
  13270. return;
  13271. SmallVector<ExternalVTableUse, 4> VTables;
  13272. ExternalSource->ReadUsedVTables(VTables);
  13273. SmallVector<VTableUse, 4> NewUses;
  13274. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  13275. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  13276. = VTablesUsed.find(VTables[I].Record);
  13277. // Even if a definition wasn't required before, it may be required now.
  13278. if (Pos != VTablesUsed.end()) {
  13279. if (!Pos->second && VTables[I].DefinitionRequired)
  13280. Pos->second = true;
  13281. continue;
  13282. }
  13283. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  13284. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  13285. }
  13286. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  13287. }
  13288. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  13289. bool DefinitionRequired) {
  13290. // Ignore any vtable uses in unevaluated operands or for classes that do
  13291. // not have a vtable.
  13292. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  13293. CurContext->isDependentContext() || isUnevaluatedContext())
  13294. return;
  13295. // Do not mark as used if compiling for the device outside of the target
  13296. // region.
  13297. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  13298. !isInOpenMPDeclareTargetContext() &&
  13299. !isInOpenMPTargetExecutionDirective()) {
  13300. if (!DefinitionRequired)
  13301. MarkVirtualMembersReferenced(Loc, Class);
  13302. return;
  13303. }
  13304. // Try to insert this class into the map.
  13305. LoadExternalVTableUses();
  13306. Class = Class->getCanonicalDecl();
  13307. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  13308. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  13309. if (!Pos.second) {
  13310. // If we already had an entry, check to see if we are promoting this vtable
  13311. // to require a definition. If so, we need to reappend to the VTableUses
  13312. // list, since we may have already processed the first entry.
  13313. if (DefinitionRequired && !Pos.first->second) {
  13314. Pos.first->second = true;
  13315. } else {
  13316. // Otherwise, we can early exit.
  13317. return;
  13318. }
  13319. } else {
  13320. // The Microsoft ABI requires that we perform the destructor body
  13321. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  13322. // the deleting destructor is emitted with the vtable, not with the
  13323. // destructor definition as in the Itanium ABI.
  13324. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  13325. CXXDestructorDecl *DD = Class->getDestructor();
  13326. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  13327. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  13328. // If this is an out-of-line declaration, marking it referenced will
  13329. // not do anything. Manually call CheckDestructor to look up operator
  13330. // delete().
  13331. ContextRAII SavedContext(*this, DD);
  13332. CheckDestructor(DD);
  13333. } else {
  13334. MarkFunctionReferenced(Loc, Class->getDestructor());
  13335. }
  13336. }
  13337. }
  13338. }
  13339. // Local classes need to have their virtual members marked
  13340. // immediately. For all other classes, we mark their virtual members
  13341. // at the end of the translation unit.
  13342. if (Class->isLocalClass())
  13343. MarkVirtualMembersReferenced(Loc, Class);
  13344. else
  13345. VTableUses.push_back(std::make_pair(Class, Loc));
  13346. }
  13347. bool Sema::DefineUsedVTables() {
  13348. LoadExternalVTableUses();
  13349. if (VTableUses.empty())
  13350. return false;
  13351. // Note: The VTableUses vector could grow as a result of marking
  13352. // the members of a class as "used", so we check the size each
  13353. // time through the loop and prefer indices (which are stable) to
  13354. // iterators (which are not).
  13355. bool DefinedAnything = false;
  13356. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  13357. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  13358. if (!Class)
  13359. continue;
  13360. TemplateSpecializationKind ClassTSK =
  13361. Class->getTemplateSpecializationKind();
  13362. SourceLocation Loc = VTableUses[I].second;
  13363. bool DefineVTable = true;
  13364. // If this class has a key function, but that key function is
  13365. // defined in another translation unit, we don't need to emit the
  13366. // vtable even though we're using it.
  13367. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  13368. if (KeyFunction && !KeyFunction->hasBody()) {
  13369. // The key function is in another translation unit.
  13370. DefineVTable = false;
  13371. TemplateSpecializationKind TSK =
  13372. KeyFunction->getTemplateSpecializationKind();
  13373. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  13374. TSK != TSK_ImplicitInstantiation &&
  13375. "Instantiations don't have key functions");
  13376. (void)TSK;
  13377. } else if (!KeyFunction) {
  13378. // If we have a class with no key function that is the subject
  13379. // of an explicit instantiation declaration, suppress the
  13380. // vtable; it will live with the explicit instantiation
  13381. // definition.
  13382. bool IsExplicitInstantiationDeclaration =
  13383. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  13384. for (auto R : Class->redecls()) {
  13385. TemplateSpecializationKind TSK
  13386. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  13387. if (TSK == TSK_ExplicitInstantiationDeclaration)
  13388. IsExplicitInstantiationDeclaration = true;
  13389. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  13390. IsExplicitInstantiationDeclaration = false;
  13391. break;
  13392. }
  13393. }
  13394. if (IsExplicitInstantiationDeclaration)
  13395. DefineVTable = false;
  13396. }
  13397. // The exception specifications for all virtual members may be needed even
  13398. // if we are not providing an authoritative form of the vtable in this TU.
  13399. // We may choose to emit it available_externally anyway.
  13400. if (!DefineVTable) {
  13401. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13402. continue;
  13403. }
  13404. // Mark all of the virtual members of this class as referenced, so
  13405. // that we can build a vtable. Then, tell the AST consumer that a
  13406. // vtable for this class is required.
  13407. DefinedAnything = true;
  13408. MarkVirtualMembersReferenced(Loc, Class);
  13409. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13410. if (VTablesUsed[Canonical])
  13411. Consumer.HandleVTable(Class);
  13412. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13413. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13414. // that lack key functions, since the user won't be able to make one.
  13415. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13416. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13417. const FunctionDecl *KeyFunctionDef = nullptr;
  13418. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13419. KeyFunctionDef->isInlined())) {
  13420. Diag(Class->getLocation(),
  13421. ClassTSK == TSK_ExplicitInstantiationDefinition
  13422. ? diag::warn_weak_template_vtable
  13423. : diag::warn_weak_vtable)
  13424. << Class;
  13425. }
  13426. }
  13427. }
  13428. VTableUses.clear();
  13429. return DefinedAnything;
  13430. }
  13431. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13432. const CXXRecordDecl *RD) {
  13433. for (const auto *I : RD->methods())
  13434. if (I->isVirtual() && !I->isPure())
  13435. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13436. }
  13437. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13438. const CXXRecordDecl *RD,
  13439. bool ConstexprOnly) {
  13440. // Mark all functions which will appear in RD's vtable as used.
  13441. CXXFinalOverriderMap FinalOverriders;
  13442. RD->getFinalOverriders(FinalOverriders);
  13443. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13444. E = FinalOverriders.end();
  13445. I != E; ++I) {
  13446. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13447. OE = I->second.end();
  13448. OI != OE; ++OI) {
  13449. assert(OI->second.size() > 0 && "no final overrider");
  13450. CXXMethodDecl *Overrider = OI->second.front().Method;
  13451. // C++ [basic.def.odr]p2:
  13452. // [...] A virtual member function is used if it is not pure. [...]
  13453. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  13454. MarkFunctionReferenced(Loc, Overrider);
  13455. }
  13456. }
  13457. // Only classes that have virtual bases need a VTT.
  13458. if (RD->getNumVBases() == 0)
  13459. return;
  13460. for (const auto &I : RD->bases()) {
  13461. const auto *Base =
  13462. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  13463. if (Base->getNumVBases() == 0)
  13464. continue;
  13465. MarkVirtualMembersReferenced(Loc, Base);
  13466. }
  13467. }
  13468. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13469. /// Objective-C implementation whose ivars need be initialized.
  13470. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13471. if (!getLangOpts().CPlusPlus)
  13472. return;
  13473. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13474. SmallVector<ObjCIvarDecl*, 8> ivars;
  13475. CollectIvarsToConstructOrDestruct(OID, ivars);
  13476. if (ivars.empty())
  13477. return;
  13478. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13479. for (unsigned i = 0; i < ivars.size(); i++) {
  13480. FieldDecl *Field = ivars[i];
  13481. if (Field->isInvalidDecl())
  13482. continue;
  13483. CXXCtorInitializer *Member;
  13484. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13485. InitializationKind InitKind =
  13486. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13487. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13488. ExprResult MemberInit =
  13489. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13490. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13491. // Note, MemberInit could actually come back empty if no initialization
  13492. // is required (e.g., because it would call a trivial default constructor)
  13493. if (!MemberInit.get() || MemberInit.isInvalid())
  13494. continue;
  13495. Member =
  13496. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13497. SourceLocation(),
  13498. MemberInit.getAs<Expr>(),
  13499. SourceLocation());
  13500. AllToInit.push_back(Member);
  13501. // Be sure that the destructor is accessible and is marked as referenced.
  13502. if (const RecordType *RecordTy =
  13503. Context.getBaseElementType(Field->getType())
  13504. ->getAs<RecordType>()) {
  13505. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13506. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13507. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13508. CheckDestructorAccess(Field->getLocation(), Destructor,
  13509. PDiag(diag::err_access_dtor_ivar)
  13510. << Context.getBaseElementType(Field->getType()));
  13511. }
  13512. }
  13513. }
  13514. ObjCImplementation->setIvarInitializers(Context,
  13515. AllToInit.data(), AllToInit.size());
  13516. }
  13517. }
  13518. static
  13519. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13520. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13521. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13522. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13523. Sema &S) {
  13524. if (Ctor->isInvalidDecl())
  13525. return;
  13526. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13527. // Target may not be determinable yet, for instance if this is a dependent
  13528. // call in an uninstantiated template.
  13529. if (Target) {
  13530. const FunctionDecl *FNTarget = nullptr;
  13531. (void)Target->hasBody(FNTarget);
  13532. Target = const_cast<CXXConstructorDecl*>(
  13533. cast_or_null<CXXConstructorDecl>(FNTarget));
  13534. }
  13535. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13536. // Avoid dereferencing a null pointer here.
  13537. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13538. if (!Current.insert(Canonical).second)
  13539. return;
  13540. // We know that beyond here, we aren't chaining into a cycle.
  13541. if (!Target || !Target->isDelegatingConstructor() ||
  13542. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13543. Valid.insert(Current.begin(), Current.end());
  13544. Current.clear();
  13545. // We've hit a cycle.
  13546. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13547. Current.count(TCanonical)) {
  13548. // If we haven't diagnosed this cycle yet, do so now.
  13549. if (!Invalid.count(TCanonical)) {
  13550. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13551. diag::warn_delegating_ctor_cycle)
  13552. << Ctor;
  13553. // Don't add a note for a function delegating directly to itself.
  13554. if (TCanonical != Canonical)
  13555. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13556. CXXConstructorDecl *C = Target;
  13557. while (C->getCanonicalDecl() != Canonical) {
  13558. const FunctionDecl *FNTarget = nullptr;
  13559. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13560. assert(FNTarget && "Ctor cycle through bodiless function");
  13561. C = const_cast<CXXConstructorDecl*>(
  13562. cast<CXXConstructorDecl>(FNTarget));
  13563. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13564. }
  13565. }
  13566. Invalid.insert(Current.begin(), Current.end());
  13567. Current.clear();
  13568. } else {
  13569. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13570. }
  13571. }
  13572. void Sema::CheckDelegatingCtorCycles() {
  13573. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13574. for (DelegatingCtorDeclsType::iterator
  13575. I = DelegatingCtorDecls.begin(ExternalSource),
  13576. E = DelegatingCtorDecls.end();
  13577. I != E; ++I)
  13578. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13579. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13580. (*CI)->setInvalidDecl();
  13581. }
  13582. namespace {
  13583. /// AST visitor that finds references to the 'this' expression.
  13584. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13585. Sema &S;
  13586. public:
  13587. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13588. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13589. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13590. << E->isImplicit();
  13591. return false;
  13592. }
  13593. };
  13594. }
  13595. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13596. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13597. if (!TSInfo)
  13598. return false;
  13599. TypeLoc TL = TSInfo->getTypeLoc();
  13600. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13601. if (!ProtoTL)
  13602. return false;
  13603. // C++11 [expr.prim.general]p3:
  13604. // [The expression this] shall not appear before the optional
  13605. // cv-qualifier-seq and it shall not appear within the declaration of a
  13606. // static member function (although its type and value category are defined
  13607. // within a static member function as they are within a non-static member
  13608. // function). [ Note: this is because declaration matching does not occur
  13609. // until the complete declarator is known. - end note ]
  13610. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13611. FindCXXThisExpr Finder(*this);
  13612. // If the return type came after the cv-qualifier-seq, check it now.
  13613. if (Proto->hasTrailingReturn() &&
  13614. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13615. return true;
  13616. // Check the exception specification.
  13617. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13618. return true;
  13619. return checkThisInStaticMemberFunctionAttributes(Method);
  13620. }
  13621. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13622. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13623. if (!TSInfo)
  13624. return false;
  13625. TypeLoc TL = TSInfo->getTypeLoc();
  13626. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13627. if (!ProtoTL)
  13628. return false;
  13629. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13630. FindCXXThisExpr Finder(*this);
  13631. switch (Proto->getExceptionSpecType()) {
  13632. case EST_Unparsed:
  13633. case EST_Uninstantiated:
  13634. case EST_Unevaluated:
  13635. case EST_BasicNoexcept:
  13636. case EST_NoThrow:
  13637. case EST_DynamicNone:
  13638. case EST_MSAny:
  13639. case EST_None:
  13640. break;
  13641. case EST_DependentNoexcept:
  13642. case EST_NoexceptFalse:
  13643. case EST_NoexceptTrue:
  13644. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13645. return true;
  13646. LLVM_FALLTHROUGH;
  13647. case EST_Dynamic:
  13648. for (const auto &E : Proto->exceptions()) {
  13649. if (!Finder.TraverseType(E))
  13650. return true;
  13651. }
  13652. break;
  13653. }
  13654. return false;
  13655. }
  13656. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13657. FindCXXThisExpr Finder(*this);
  13658. // Check attributes.
  13659. for (const auto *A : Method->attrs()) {
  13660. // FIXME: This should be emitted by tblgen.
  13661. Expr *Arg = nullptr;
  13662. ArrayRef<Expr *> Args;
  13663. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13664. Arg = G->getArg();
  13665. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13666. Arg = G->getArg();
  13667. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13668. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13669. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13670. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13671. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13672. Arg = ETLF->getSuccessValue();
  13673. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13674. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13675. Arg = STLF->getSuccessValue();
  13676. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13677. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13678. Arg = LR->getArg();
  13679. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13680. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13681. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13682. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13683. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13684. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13685. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13686. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13687. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13688. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13689. if (Arg && !Finder.TraverseStmt(Arg))
  13690. return true;
  13691. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13692. if (!Finder.TraverseStmt(Args[I]))
  13693. return true;
  13694. }
  13695. }
  13696. return false;
  13697. }
  13698. void Sema::checkExceptionSpecification(
  13699. bool IsTopLevel, ExceptionSpecificationType EST,
  13700. ArrayRef<ParsedType> DynamicExceptions,
  13701. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13702. SmallVectorImpl<QualType> &Exceptions,
  13703. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13704. Exceptions.clear();
  13705. ESI.Type = EST;
  13706. if (EST == EST_Dynamic) {
  13707. Exceptions.reserve(DynamicExceptions.size());
  13708. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13709. // FIXME: Preserve type source info.
  13710. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13711. if (IsTopLevel) {
  13712. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13713. collectUnexpandedParameterPacks(ET, Unexpanded);
  13714. if (!Unexpanded.empty()) {
  13715. DiagnoseUnexpandedParameterPacks(
  13716. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13717. Unexpanded);
  13718. continue;
  13719. }
  13720. }
  13721. // Check that the type is valid for an exception spec, and
  13722. // drop it if not.
  13723. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13724. Exceptions.push_back(ET);
  13725. }
  13726. ESI.Exceptions = Exceptions;
  13727. return;
  13728. }
  13729. if (isComputedNoexcept(EST)) {
  13730. assert((NoexceptExpr->isTypeDependent() ||
  13731. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13732. Context.BoolTy) &&
  13733. "Parser should have made sure that the expression is boolean");
  13734. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13735. ESI.Type = EST_BasicNoexcept;
  13736. return;
  13737. }
  13738. ESI.NoexceptExpr = NoexceptExpr;
  13739. return;
  13740. }
  13741. }
  13742. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13743. ExceptionSpecificationType EST,
  13744. SourceRange SpecificationRange,
  13745. ArrayRef<ParsedType> DynamicExceptions,
  13746. ArrayRef<SourceRange> DynamicExceptionRanges,
  13747. Expr *NoexceptExpr) {
  13748. if (!MethodD)
  13749. return;
  13750. // Dig out the method we're referring to.
  13751. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13752. MethodD = FunTmpl->getTemplatedDecl();
  13753. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13754. if (!Method)
  13755. return;
  13756. // Check the exception specification.
  13757. llvm::SmallVector<QualType, 4> Exceptions;
  13758. FunctionProtoType::ExceptionSpecInfo ESI;
  13759. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13760. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13761. ESI);
  13762. // Update the exception specification on the function type.
  13763. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13764. if (Method->isStatic())
  13765. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13766. if (Method->isVirtual()) {
  13767. // Check overrides, which we previously had to delay.
  13768. for (const CXXMethodDecl *O : Method->overridden_methods())
  13769. CheckOverridingFunctionExceptionSpec(Method, O);
  13770. }
  13771. }
  13772. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13773. ///
  13774. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13775. SourceLocation DeclStart, Declarator &D,
  13776. Expr *BitWidth,
  13777. InClassInitStyle InitStyle,
  13778. AccessSpecifier AS,
  13779. const ParsedAttr &MSPropertyAttr) {
  13780. IdentifierInfo *II = D.getIdentifier();
  13781. if (!II) {
  13782. Diag(DeclStart, diag::err_anonymous_property);
  13783. return nullptr;
  13784. }
  13785. SourceLocation Loc = D.getIdentifierLoc();
  13786. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13787. QualType T = TInfo->getType();
  13788. if (getLangOpts().CPlusPlus) {
  13789. CheckExtraCXXDefaultArguments(D);
  13790. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13791. UPPC_DataMemberType)) {
  13792. D.setInvalidType();
  13793. T = Context.IntTy;
  13794. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13795. }
  13796. }
  13797. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13798. if (D.getDeclSpec().isInlineSpecified())
  13799. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13800. << getLangOpts().CPlusPlus17;
  13801. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13802. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13803. diag::err_invalid_thread)
  13804. << DeclSpec::getSpecifierName(TSCS);
  13805. // Check to see if this name was declared as a member previously
  13806. NamedDecl *PrevDecl = nullptr;
  13807. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13808. ForVisibleRedeclaration);
  13809. LookupName(Previous, S);
  13810. switch (Previous.getResultKind()) {
  13811. case LookupResult::Found:
  13812. case LookupResult::FoundUnresolvedValue:
  13813. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13814. break;
  13815. case LookupResult::FoundOverloaded:
  13816. PrevDecl = Previous.getRepresentativeDecl();
  13817. break;
  13818. case LookupResult::NotFound:
  13819. case LookupResult::NotFoundInCurrentInstantiation:
  13820. case LookupResult::Ambiguous:
  13821. break;
  13822. }
  13823. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13824. // Maybe we will complain about the shadowed template parameter.
  13825. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13826. // Just pretend that we didn't see the previous declaration.
  13827. PrevDecl = nullptr;
  13828. }
  13829. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13830. PrevDecl = nullptr;
  13831. SourceLocation TSSL = D.getBeginLoc();
  13832. MSPropertyDecl *NewPD =
  13833. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13834. MSPropertyAttr.getPropertyDataGetter(),
  13835. MSPropertyAttr.getPropertyDataSetter());
  13836. ProcessDeclAttributes(TUScope, NewPD, D);
  13837. NewPD->setAccess(AS);
  13838. if (NewPD->isInvalidDecl())
  13839. Record->setInvalidDecl();
  13840. if (D.getDeclSpec().isModulePrivateSpecified())
  13841. NewPD->setModulePrivate();
  13842. if (NewPD->isInvalidDecl() && PrevDecl) {
  13843. // Don't introduce NewFD into scope; there's already something
  13844. // with the same name in the same scope.
  13845. } else if (II) {
  13846. PushOnScopeChains(NewPD, S);
  13847. } else
  13848. Record->addDecl(NewPD);
  13849. return NewPD;
  13850. }