SemaDeclCXX.cpp 606 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995
  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. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  708. QualType R = TInfo->getType();
  709. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  710. UPPC_DeclarationType))
  711. D.setInvalidType();
  712. // The syntax only allows a single ref-qualifier prior to the decomposition
  713. // declarator. No other declarator chunks are permitted. Also check the type
  714. // specifier here.
  715. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  716. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  717. (D.getNumTypeObjects() == 1 &&
  718. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  719. Diag(Decomp.getLSquareLoc(),
  720. (D.hasGroupingParens() ||
  721. (D.getNumTypeObjects() &&
  722. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  723. ? diag::err_decomp_decl_parens
  724. : diag::err_decomp_decl_type)
  725. << R;
  726. // In most cases, there's no actual problem with an explicitly-specified
  727. // type, but a function type won't work here, and ActOnVariableDeclarator
  728. // shouldn't be called for such a type.
  729. if (R->isFunctionType())
  730. D.setInvalidType();
  731. }
  732. // Build the BindingDecls.
  733. SmallVector<BindingDecl*, 8> Bindings;
  734. // Build the BindingDecls.
  735. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  736. // Check for name conflicts.
  737. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  738. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  739. ForVisibleRedeclaration);
  740. LookupName(Previous, S,
  741. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  742. // It's not permitted to shadow a template parameter name.
  743. if (Previous.isSingleResult() &&
  744. Previous.getFoundDecl()->isTemplateParameter()) {
  745. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  746. Previous.getFoundDecl());
  747. Previous.clear();
  748. }
  749. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  750. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  751. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  752. /*AllowInlineNamespace*/false);
  753. if (!Previous.empty()) {
  754. auto *Old = Previous.getRepresentativeDecl();
  755. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  756. Diag(Old->getLocation(), diag::note_previous_definition);
  757. }
  758. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  759. PushOnScopeChains(BD, S, true);
  760. Bindings.push_back(BD);
  761. ParsingInitForAutoVars.insert(BD);
  762. }
  763. // There are no prior lookup results for the variable itself, because it
  764. // is unnamed.
  765. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  766. Decomp.getLSquareLoc());
  767. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  768. ForVisibleRedeclaration);
  769. // Build the variable that holds the non-decomposed object.
  770. bool AddToScope = true;
  771. NamedDecl *New =
  772. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  773. MultiTemplateParamsArg(), AddToScope, Bindings);
  774. if (AddToScope) {
  775. S->AddDecl(New);
  776. CurContext->addHiddenDecl(New);
  777. }
  778. if (isInOpenMPDeclareTargetContext())
  779. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  780. return New;
  781. }
  782. static bool checkSimpleDecomposition(
  783. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  784. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  785. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  786. if ((int64_t)Bindings.size() != NumElems) {
  787. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  788. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  789. << (NumElems < Bindings.size());
  790. return true;
  791. }
  792. unsigned I = 0;
  793. for (auto *B : Bindings) {
  794. SourceLocation Loc = B->getLocation();
  795. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  796. if (E.isInvalid())
  797. return true;
  798. E = GetInit(Loc, E.get(), I++);
  799. if (E.isInvalid())
  800. return true;
  801. B->setBinding(ElemType, E.get());
  802. }
  803. return false;
  804. }
  805. static bool checkArrayLikeDecomposition(Sema &S,
  806. ArrayRef<BindingDecl *> Bindings,
  807. ValueDecl *Src, QualType DecompType,
  808. const llvm::APSInt &NumElems,
  809. QualType ElemType) {
  810. return checkSimpleDecomposition(
  811. S, Bindings, Src, DecompType, NumElems, ElemType,
  812. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  813. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  814. if (E.isInvalid())
  815. return ExprError();
  816. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  817. });
  818. }
  819. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  820. ValueDecl *Src, QualType DecompType,
  821. const ConstantArrayType *CAT) {
  822. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  823. llvm::APSInt(CAT->getSize()),
  824. CAT->getElementType());
  825. }
  826. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  827. ValueDecl *Src, QualType DecompType,
  828. const VectorType *VT) {
  829. return checkArrayLikeDecomposition(
  830. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  831. S.Context.getQualifiedType(VT->getElementType(),
  832. DecompType.getQualifiers()));
  833. }
  834. static bool checkComplexDecomposition(Sema &S,
  835. ArrayRef<BindingDecl *> Bindings,
  836. ValueDecl *Src, QualType DecompType,
  837. const ComplexType *CT) {
  838. return checkSimpleDecomposition(
  839. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  840. S.Context.getQualifiedType(CT->getElementType(),
  841. DecompType.getQualifiers()),
  842. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  843. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  844. });
  845. }
  846. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  847. TemplateArgumentListInfo &Args) {
  848. SmallString<128> SS;
  849. llvm::raw_svector_ostream OS(SS);
  850. bool First = true;
  851. for (auto &Arg : Args.arguments()) {
  852. if (!First)
  853. OS << ", ";
  854. Arg.getArgument().print(PrintingPolicy, OS);
  855. First = false;
  856. }
  857. return OS.str();
  858. }
  859. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  860. SourceLocation Loc, StringRef Trait,
  861. TemplateArgumentListInfo &Args,
  862. unsigned DiagID) {
  863. auto DiagnoseMissing = [&] {
  864. if (DiagID)
  865. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  866. Args);
  867. return true;
  868. };
  869. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  870. NamespaceDecl *Std = S.getStdNamespace();
  871. if (!Std)
  872. return DiagnoseMissing();
  873. // Look up the trait itself, within namespace std. We can diagnose various
  874. // problems with this lookup even if we've been asked to not diagnose a
  875. // missing specialization, because this can only fail if the user has been
  876. // declaring their own names in namespace std or we don't support the
  877. // standard library implementation in use.
  878. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  879. Loc, Sema::LookupOrdinaryName);
  880. if (!S.LookupQualifiedName(Result, Std))
  881. return DiagnoseMissing();
  882. if (Result.isAmbiguous())
  883. return true;
  884. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  885. if (!TraitTD) {
  886. Result.suppressDiagnostics();
  887. NamedDecl *Found = *Result.begin();
  888. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  889. S.Diag(Found->getLocation(), diag::note_declared_at);
  890. return true;
  891. }
  892. // Build the template-id.
  893. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  894. if (TraitTy.isNull())
  895. return true;
  896. if (!S.isCompleteType(Loc, TraitTy)) {
  897. if (DiagID)
  898. S.RequireCompleteType(
  899. Loc, TraitTy, DiagID,
  900. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  901. return true;
  902. }
  903. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  904. assert(RD && "specialization of class template is not a class?");
  905. // Look up the member of the trait type.
  906. S.LookupQualifiedName(TraitMemberLookup, RD);
  907. return TraitMemberLookup.isAmbiguous();
  908. }
  909. static TemplateArgumentLoc
  910. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  911. uint64_t I) {
  912. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  913. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  914. }
  915. static TemplateArgumentLoc
  916. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  917. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  918. }
  919. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  920. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  921. llvm::APSInt &Size) {
  922. EnterExpressionEvaluationContext ContextRAII(
  923. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  924. DeclarationName Value = S.PP.getIdentifierInfo("value");
  925. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  926. // Form template argument list for tuple_size<T>.
  927. TemplateArgumentListInfo Args(Loc, Loc);
  928. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  929. // If there's no tuple_size specialization or the lookup of 'value' is empty,
  930. // it's not tuple-like.
  931. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
  932. R.empty())
  933. return IsTupleLike::NotTupleLike;
  934. // If we get this far, we've committed to the tuple interpretation, but
  935. // we can still fail if there actually isn't a usable ::value.
  936. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  937. LookupResult &R;
  938. TemplateArgumentListInfo &Args;
  939. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  940. : R(R), Args(Args) {}
  941. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  942. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  943. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  944. }
  945. } Diagnoser(R, Args);
  946. ExprResult E =
  947. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  948. if (E.isInvalid())
  949. return IsTupleLike::Error;
  950. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  951. if (E.isInvalid())
  952. return IsTupleLike::Error;
  953. return IsTupleLike::TupleLike;
  954. }
  955. /// \return std::tuple_element<I, T>::type.
  956. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  957. unsigned I, QualType T) {
  958. // Form template argument list for tuple_element<I, T>.
  959. TemplateArgumentListInfo Args(Loc, Loc);
  960. Args.addArgument(
  961. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  962. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  963. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  964. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  965. if (lookupStdTypeTraitMember(
  966. S, R, Loc, "tuple_element", Args,
  967. diag::err_decomp_decl_std_tuple_element_not_specialized))
  968. return QualType();
  969. auto *TD = R.getAsSingle<TypeDecl>();
  970. if (!TD) {
  971. R.suppressDiagnostics();
  972. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  973. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  974. if (!R.empty())
  975. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  976. return QualType();
  977. }
  978. return S.Context.getTypeDeclType(TD);
  979. }
  980. namespace {
  981. struct BindingDiagnosticTrap {
  982. Sema &S;
  983. DiagnosticErrorTrap Trap;
  984. BindingDecl *BD;
  985. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  986. : S(S), Trap(S.Diags), BD(BD) {}
  987. ~BindingDiagnosticTrap() {
  988. if (Trap.hasErrorOccurred())
  989. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  990. }
  991. };
  992. }
  993. static bool checkTupleLikeDecomposition(Sema &S,
  994. ArrayRef<BindingDecl *> Bindings,
  995. VarDecl *Src, QualType DecompType,
  996. const llvm::APSInt &TupleSize) {
  997. if ((int64_t)Bindings.size() != TupleSize) {
  998. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  999. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  1000. << (TupleSize < Bindings.size());
  1001. return true;
  1002. }
  1003. if (Bindings.empty())
  1004. return false;
  1005. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  1006. // [dcl.decomp]p3:
  1007. // The unqualified-id get is looked up in the scope of E by class member
  1008. // access lookup ...
  1009. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  1010. bool UseMemberGet = false;
  1011. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  1012. if (auto *RD = DecompType->getAsCXXRecordDecl())
  1013. S.LookupQualifiedName(MemberGet, RD);
  1014. if (MemberGet.isAmbiguous())
  1015. return true;
  1016. // ... and if that finds at least one declaration that is a function
  1017. // template whose first template parameter is a non-type parameter ...
  1018. for (NamedDecl *D : MemberGet) {
  1019. if (FunctionTemplateDecl *FTD =
  1020. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1021. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1022. if (TPL->size() != 0 &&
  1023. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1024. // ... the initializer is e.get<i>().
  1025. UseMemberGet = true;
  1026. break;
  1027. }
  1028. }
  1029. }
  1030. }
  1031. unsigned I = 0;
  1032. for (auto *B : Bindings) {
  1033. BindingDiagnosticTrap Trap(S, B);
  1034. SourceLocation Loc = B->getLocation();
  1035. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1036. if (E.isInvalid())
  1037. return true;
  1038. // e is an lvalue if the type of the entity is an lvalue reference and
  1039. // an xvalue otherwise
  1040. if (!Src->getType()->isLValueReferenceType())
  1041. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1042. E.get(), nullptr, VK_XValue);
  1043. TemplateArgumentListInfo Args(Loc, Loc);
  1044. Args.addArgument(
  1045. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1046. if (UseMemberGet) {
  1047. // if [lookup of member get] finds at least one declaration, the
  1048. // initializer is e.get<i-1>().
  1049. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1050. CXXScopeSpec(), SourceLocation(), nullptr,
  1051. MemberGet, &Args, nullptr);
  1052. if (E.isInvalid())
  1053. return true;
  1054. E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
  1055. } else {
  1056. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1057. // in the associated namespaces.
  1058. Expr *Get = UnresolvedLookupExpr::Create(
  1059. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1060. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1061. UnresolvedSetIterator(), UnresolvedSetIterator());
  1062. Expr *Arg = E.get();
  1063. E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
  1064. }
  1065. if (E.isInvalid())
  1066. return true;
  1067. Expr *Init = E.get();
  1068. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1069. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1070. if (T.isNull())
  1071. return true;
  1072. // each vi is a variable of type "reference to T" initialized with the
  1073. // initializer, where the reference is an lvalue reference if the
  1074. // initializer is an lvalue and an rvalue reference otherwise
  1075. QualType RefType =
  1076. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1077. if (RefType.isNull())
  1078. return true;
  1079. auto *RefVD = VarDecl::Create(
  1080. S.Context, Src->getDeclContext(), Loc, Loc,
  1081. B->getDeclName().getAsIdentifierInfo(), RefType,
  1082. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1083. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1084. RefVD->setTSCSpec(Src->getTSCSpec());
  1085. RefVD->setImplicit();
  1086. if (Src->isInlineSpecified())
  1087. RefVD->setInlineSpecified();
  1088. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1089. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1090. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1091. InitializationSequence Seq(S, Entity, Kind, Init);
  1092. E = Seq.Perform(S, Entity, Kind, Init);
  1093. if (E.isInvalid())
  1094. return true;
  1095. E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
  1096. if (E.isInvalid())
  1097. return true;
  1098. RefVD->setInit(E.get());
  1099. if (!E.get()->isValueDependent())
  1100. RefVD->checkInitIsICE();
  1101. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1102. DeclarationNameInfo(B->getDeclName(), Loc),
  1103. RefVD);
  1104. if (E.isInvalid())
  1105. return true;
  1106. B->setBinding(T, E.get());
  1107. I++;
  1108. }
  1109. return false;
  1110. }
  1111. /// Find the base class to decompose in a built-in decomposition of a class type.
  1112. /// This base class search is, unfortunately, not quite like any other that we
  1113. /// perform anywhere else in C++.
  1114. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1115. const CXXRecordDecl *RD,
  1116. CXXCastPath &BasePath) {
  1117. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1118. CXXBasePath &Path) {
  1119. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1120. };
  1121. const CXXRecordDecl *ClassWithFields = nullptr;
  1122. AccessSpecifier AS = AS_public;
  1123. if (RD->hasDirectFields())
  1124. // [dcl.decomp]p4:
  1125. // Otherwise, all of E's non-static data members shall be public direct
  1126. // members of E ...
  1127. ClassWithFields = RD;
  1128. else {
  1129. // ... or of ...
  1130. CXXBasePaths Paths;
  1131. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1132. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1133. // If no classes have fields, just decompose RD itself. (This will work
  1134. // if and only if zero bindings were provided.)
  1135. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1136. }
  1137. CXXBasePath *BestPath = nullptr;
  1138. for (auto &P : Paths) {
  1139. if (!BestPath)
  1140. BestPath = &P;
  1141. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1142. BestPath->back().Base->getType())) {
  1143. // ... the same ...
  1144. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1145. << false << RD << BestPath->back().Base->getType()
  1146. << P.back().Base->getType();
  1147. return DeclAccessPair();
  1148. } else if (P.Access < BestPath->Access) {
  1149. BestPath = &P;
  1150. }
  1151. }
  1152. // ... unambiguous ...
  1153. QualType BaseType = BestPath->back().Base->getType();
  1154. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1155. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1156. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1157. return DeclAccessPair();
  1158. }
  1159. // ... [accessible, implied by other rules] base class of E.
  1160. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1161. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1162. AS = BestPath->Access;
  1163. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1164. S.BuildBasePathArray(Paths, BasePath);
  1165. }
  1166. // The above search did not check whether the selected class itself has base
  1167. // classes with fields, so check that now.
  1168. CXXBasePaths Paths;
  1169. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1170. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1171. << (ClassWithFields == RD) << RD << ClassWithFields
  1172. << Paths.front().back().Base->getType();
  1173. return DeclAccessPair();
  1174. }
  1175. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1176. }
  1177. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1178. ValueDecl *Src, QualType DecompType,
  1179. const CXXRecordDecl *OrigRD) {
  1180. if (S.RequireCompleteType(Src->getLocation(), DecompType,
  1181. diag::err_incomplete_type))
  1182. return true;
  1183. CXXCastPath BasePath;
  1184. DeclAccessPair BasePair =
  1185. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1186. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1187. if (!RD)
  1188. return true;
  1189. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1190. DecompType.getQualifiers());
  1191. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1192. unsigned NumFields =
  1193. std::count_if(RD->field_begin(), RD->field_end(),
  1194. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1195. assert(Bindings.size() != NumFields);
  1196. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1197. << DecompType << (unsigned)Bindings.size() << NumFields
  1198. << (NumFields < Bindings.size());
  1199. return true;
  1200. };
  1201. // all of E's non-static data members shall be [...] well-formed
  1202. // when named as e.name in the context of the structured binding,
  1203. // E shall not have an anonymous union member, ...
  1204. unsigned I = 0;
  1205. for (auto *FD : RD->fields()) {
  1206. if (FD->isUnnamedBitfield())
  1207. continue;
  1208. if (FD->isAnonymousStructOrUnion()) {
  1209. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1210. << DecompType << FD->getType()->isUnionType();
  1211. S.Diag(FD->getLocation(), diag::note_declared_at);
  1212. return true;
  1213. }
  1214. // We have a real field to bind.
  1215. if (I >= Bindings.size())
  1216. return DiagnoseBadNumberOfBindings();
  1217. auto *B = Bindings[I++];
  1218. SourceLocation Loc = B->getLocation();
  1219. // The field must be accessible in the context of the structured binding.
  1220. // We already checked that the base class is accessible.
  1221. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1222. // const_cast here.
  1223. S.CheckStructuredBindingMemberAccess(
  1224. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1225. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1226. BasePair.getAccess(), FD->getAccess())));
  1227. // Initialize the binding to Src.FD.
  1228. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1229. if (E.isInvalid())
  1230. return true;
  1231. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1232. VK_LValue, &BasePath);
  1233. if (E.isInvalid())
  1234. return true;
  1235. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1236. CXXScopeSpec(), FD,
  1237. DeclAccessPair::make(FD, FD->getAccess()),
  1238. DeclarationNameInfo(FD->getDeclName(), Loc));
  1239. if (E.isInvalid())
  1240. return true;
  1241. // If the type of the member is T, the referenced type is cv T, where cv is
  1242. // the cv-qualification of the decomposition expression.
  1243. //
  1244. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1245. // 'const' to the type of the field.
  1246. Qualifiers Q = DecompType.getQualifiers();
  1247. if (FD->isMutable())
  1248. Q.removeConst();
  1249. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1250. }
  1251. if (I != Bindings.size())
  1252. return DiagnoseBadNumberOfBindings();
  1253. return false;
  1254. }
  1255. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1256. QualType DecompType = DD->getType();
  1257. // If the type of the decomposition is dependent, then so is the type of
  1258. // each binding.
  1259. if (DecompType->isDependentType()) {
  1260. for (auto *B : DD->bindings())
  1261. B->setType(Context.DependentTy);
  1262. return;
  1263. }
  1264. DecompType = DecompType.getNonReferenceType();
  1265. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1266. // C++1z [dcl.decomp]/2:
  1267. // If E is an array type [...]
  1268. // As an extension, we also support decomposition of built-in complex and
  1269. // vector types.
  1270. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1271. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1272. DD->setInvalidDecl();
  1273. return;
  1274. }
  1275. if (auto *VT = DecompType->getAs<VectorType>()) {
  1276. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1277. DD->setInvalidDecl();
  1278. return;
  1279. }
  1280. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1281. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1282. DD->setInvalidDecl();
  1283. return;
  1284. }
  1285. // C++1z [dcl.decomp]/3:
  1286. // if the expression std::tuple_size<E>::value is a well-formed integral
  1287. // constant expression, [...]
  1288. llvm::APSInt TupleSize(32);
  1289. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1290. case IsTupleLike::Error:
  1291. DD->setInvalidDecl();
  1292. return;
  1293. case IsTupleLike::TupleLike:
  1294. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1295. DD->setInvalidDecl();
  1296. return;
  1297. case IsTupleLike::NotTupleLike:
  1298. break;
  1299. }
  1300. // C++1z [dcl.dcl]/8:
  1301. // [E shall be of array or non-union class type]
  1302. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1303. if (!RD || RD->isUnion()) {
  1304. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1305. << DD << !RD << DecompType;
  1306. DD->setInvalidDecl();
  1307. return;
  1308. }
  1309. // C++1z [dcl.decomp]/4:
  1310. // all of E's non-static data members shall be [...] direct members of
  1311. // E or of the same unambiguous public base class of E, ...
  1312. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1313. DD->setInvalidDecl();
  1314. }
  1315. /// Merge the exception specifications of two variable declarations.
  1316. ///
  1317. /// This is called when there's a redeclaration of a VarDecl. The function
  1318. /// checks if the redeclaration might have an exception specification and
  1319. /// validates compatibility and merges the specs if necessary.
  1320. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1321. // Shortcut if exceptions are disabled.
  1322. if (!getLangOpts().CXXExceptions)
  1323. return;
  1324. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1325. "Should only be called if types are otherwise the same.");
  1326. QualType NewType = New->getType();
  1327. QualType OldType = Old->getType();
  1328. // We're only interested in pointers and references to functions, as well
  1329. // as pointers to member functions.
  1330. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1331. NewType = R->getPointeeType();
  1332. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1333. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1334. NewType = P->getPointeeType();
  1335. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1336. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1337. NewType = M->getPointeeType();
  1338. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1339. }
  1340. if (!NewType->isFunctionProtoType())
  1341. return;
  1342. // There's lots of special cases for functions. For function pointers, system
  1343. // libraries are hopefully not as broken so that we don't need these
  1344. // workarounds.
  1345. if (CheckEquivalentExceptionSpec(
  1346. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1347. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1348. New->setInvalidDecl();
  1349. }
  1350. }
  1351. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1352. /// function declaration are well-formed according to C++
  1353. /// [dcl.fct.default].
  1354. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1355. unsigned NumParams = FD->getNumParams();
  1356. unsigned p;
  1357. // Find first parameter with a default argument
  1358. for (p = 0; p < NumParams; ++p) {
  1359. ParmVarDecl *Param = FD->getParamDecl(p);
  1360. if (Param->hasDefaultArg())
  1361. break;
  1362. }
  1363. // C++11 [dcl.fct.default]p4:
  1364. // In a given function declaration, each parameter subsequent to a parameter
  1365. // with a default argument shall have a default argument supplied in this or
  1366. // a previous declaration or shall be a function parameter pack. A default
  1367. // argument shall not be redefined by a later declaration (not even to the
  1368. // same value).
  1369. unsigned LastMissingDefaultArg = 0;
  1370. for (; p < NumParams; ++p) {
  1371. ParmVarDecl *Param = FD->getParamDecl(p);
  1372. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1373. if (Param->isInvalidDecl())
  1374. /* We already complained about this parameter. */;
  1375. else if (Param->getIdentifier())
  1376. Diag(Param->getLocation(),
  1377. diag::err_param_default_argument_missing_name)
  1378. << Param->getIdentifier();
  1379. else
  1380. Diag(Param->getLocation(),
  1381. diag::err_param_default_argument_missing);
  1382. LastMissingDefaultArg = p;
  1383. }
  1384. }
  1385. if (LastMissingDefaultArg > 0) {
  1386. // Some default arguments were missing. Clear out all of the
  1387. // default arguments up to (and including) the last missing
  1388. // default argument, so that we leave the function parameters
  1389. // in a semantically valid state.
  1390. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1391. ParmVarDecl *Param = FD->getParamDecl(p);
  1392. if (Param->hasDefaultArg()) {
  1393. Param->setDefaultArg(nullptr);
  1394. }
  1395. }
  1396. }
  1397. }
  1398. /// Check that the given type is a literal type. Issue a diagnostic if not,
  1399. /// if Kind is Diagnose.
  1400. /// \return \c true if a problem has been found (and optionally diagnosed).
  1401. template <typename... Ts>
  1402. static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
  1403. SourceLocation Loc, QualType T, unsigned DiagID,
  1404. Ts &&...DiagArgs) {
  1405. if (T->isDependentType())
  1406. return false;
  1407. switch (Kind) {
  1408. case Sema::CheckConstexprKind::Diagnose:
  1409. return SemaRef.RequireLiteralType(Loc, T, DiagID,
  1410. std::forward<Ts>(DiagArgs)...);
  1411. case Sema::CheckConstexprKind::CheckValid:
  1412. return !T->isLiteralType(SemaRef.Context);
  1413. }
  1414. llvm_unreachable("unknown CheckConstexprKind");
  1415. }
  1416. /// Determine whether a destructor cannot be constexpr due to
  1417. static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
  1418. const CXXDestructorDecl *DD,
  1419. Sema::CheckConstexprKind Kind) {
  1420. auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
  1421. const CXXRecordDecl *RD =
  1422. T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1423. if (!RD || RD->hasConstexprDestructor())
  1424. return true;
  1425. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1426. SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
  1427. << DD->getConstexprKind() << !FD
  1428. << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1429. SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
  1430. << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1431. }
  1432. return false;
  1433. };
  1434. const CXXRecordDecl *RD = DD->getParent();
  1435. for (const CXXBaseSpecifier &B : RD->bases())
  1436. if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
  1437. return false;
  1438. for (const FieldDecl *FD : RD->fields())
  1439. if (!Check(FD->getLocation(), FD->getType(), FD))
  1440. return false;
  1441. return true;
  1442. }
  1443. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1444. // are all literal types. If so, return true. If not, produce a suitable
  1445. // diagnostic and return false.
  1446. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1447. const FunctionDecl *FD,
  1448. Sema::CheckConstexprKind Kind) {
  1449. unsigned ArgIndex = 0;
  1450. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1451. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1452. e = FT->param_type_end();
  1453. i != e; ++i, ++ArgIndex) {
  1454. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1455. SourceLocation ParamLoc = PD->getLocation();
  1456. if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
  1457. diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1458. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1459. FD->isConsteval()))
  1460. return false;
  1461. }
  1462. return true;
  1463. }
  1464. /// Get diagnostic %select index for tag kind for
  1465. /// record diagnostic message.
  1466. /// WARNING: Indexes apply to particular diagnostics only!
  1467. ///
  1468. /// \returns diagnostic %select index.
  1469. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1470. switch (Tag) {
  1471. case TTK_Struct: return 0;
  1472. case TTK_Interface: return 1;
  1473. case TTK_Class: return 2;
  1474. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1475. }
  1476. }
  1477. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1478. Stmt *Body,
  1479. Sema::CheckConstexprKind Kind);
  1480. // Check whether a function declaration satisfies the requirements of a
  1481. // constexpr function definition or a constexpr constructor definition. If so,
  1482. // return true. If not, produce appropriate diagnostics (unless asked not to by
  1483. // Kind) and return false.
  1484. //
  1485. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1486. bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
  1487. CheckConstexprKind Kind) {
  1488. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1489. if (MD && MD->isInstance()) {
  1490. // C++11 [dcl.constexpr]p4:
  1491. // The definition of a constexpr constructor shall satisfy the following
  1492. // constraints:
  1493. // - the class shall not have any virtual base classes;
  1494. //
  1495. // FIXME: This only applies to constructors and destructors, not arbitrary
  1496. // member functions.
  1497. const CXXRecordDecl *RD = MD->getParent();
  1498. if (RD->getNumVBases()) {
  1499. if (Kind == CheckConstexprKind::CheckValid)
  1500. return false;
  1501. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1502. << isa<CXXConstructorDecl>(NewFD)
  1503. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1504. for (const auto &I : RD->vbases())
  1505. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1506. << I.getSourceRange();
  1507. return false;
  1508. }
  1509. }
  1510. if (!isa<CXXConstructorDecl>(NewFD)) {
  1511. // C++11 [dcl.constexpr]p3:
  1512. // The definition of a constexpr function shall satisfy the following
  1513. // constraints:
  1514. // - it shall not be virtual; (removed in C++20)
  1515. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1516. if (Method && Method->isVirtual()) {
  1517. if (getLangOpts().CPlusPlus2a) {
  1518. if (Kind == CheckConstexprKind::Diagnose)
  1519. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1520. } else {
  1521. if (Kind == CheckConstexprKind::CheckValid)
  1522. return false;
  1523. Method = Method->getCanonicalDecl();
  1524. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1525. // If it's not obvious why this function is virtual, find an overridden
  1526. // function which uses the 'virtual' keyword.
  1527. const CXXMethodDecl *WrittenVirtual = Method;
  1528. while (!WrittenVirtual->isVirtualAsWritten())
  1529. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1530. if (WrittenVirtual != Method)
  1531. Diag(WrittenVirtual->getLocation(),
  1532. diag::note_overridden_virtual_function);
  1533. return false;
  1534. }
  1535. }
  1536. // - its return type shall be a literal type;
  1537. QualType RT = NewFD->getReturnType();
  1538. if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
  1539. diag::err_constexpr_non_literal_return,
  1540. NewFD->isConsteval()))
  1541. return false;
  1542. }
  1543. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
  1544. // A destructor can be constexpr only if the defaulted destructor could be;
  1545. // we don't need to check the members and bases if we already know they all
  1546. // have constexpr destructors.
  1547. if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
  1548. if (Kind == CheckConstexprKind::CheckValid)
  1549. return false;
  1550. if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
  1551. return false;
  1552. }
  1553. }
  1554. // - each of its parameter types shall be a literal type;
  1555. if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
  1556. return false;
  1557. Stmt *Body = NewFD->getBody();
  1558. assert(Body &&
  1559. "CheckConstexprFunctionDefinition called on function with no body");
  1560. return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
  1561. }
  1562. /// Check the given declaration statement is legal within a constexpr function
  1563. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1564. ///
  1565. /// \return true if the body is OK (maybe only as an extension), false if we
  1566. /// have diagnosed a problem.
  1567. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1568. DeclStmt *DS, SourceLocation &Cxx1yLoc,
  1569. Sema::CheckConstexprKind Kind) {
  1570. // C++11 [dcl.constexpr]p3 and p4:
  1571. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1572. // contain only
  1573. for (const auto *DclIt : DS->decls()) {
  1574. switch (DclIt->getKind()) {
  1575. case Decl::StaticAssert:
  1576. case Decl::Using:
  1577. case Decl::UsingShadow:
  1578. case Decl::UsingDirective:
  1579. case Decl::UnresolvedUsingTypename:
  1580. case Decl::UnresolvedUsingValue:
  1581. // - static_assert-declarations
  1582. // - using-declarations,
  1583. // - using-directives,
  1584. continue;
  1585. case Decl::Typedef:
  1586. case Decl::TypeAlias: {
  1587. // - typedef declarations and alias-declarations that do not define
  1588. // classes or enumerations,
  1589. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1590. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1591. // Don't allow variably-modified types in constexpr functions.
  1592. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1593. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1594. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1595. << TL.getSourceRange() << TL.getType()
  1596. << isa<CXXConstructorDecl>(Dcl);
  1597. }
  1598. return false;
  1599. }
  1600. continue;
  1601. }
  1602. case Decl::Enum:
  1603. case Decl::CXXRecord:
  1604. // C++1y allows types to be defined, not just declared.
  1605. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
  1606. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1607. SemaRef.Diag(DS->getBeginLoc(),
  1608. SemaRef.getLangOpts().CPlusPlus14
  1609. ? diag::warn_cxx11_compat_constexpr_type_definition
  1610. : diag::ext_constexpr_type_definition)
  1611. << isa<CXXConstructorDecl>(Dcl);
  1612. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1613. return false;
  1614. }
  1615. }
  1616. continue;
  1617. case Decl::EnumConstant:
  1618. case Decl::IndirectField:
  1619. case Decl::ParmVar:
  1620. // These can only appear with other declarations which are banned in
  1621. // C++11 and permitted in C++1y, so ignore them.
  1622. continue;
  1623. case Decl::Var:
  1624. case Decl::Decomposition: {
  1625. // C++1y [dcl.constexpr]p3 allows anything except:
  1626. // a definition of a variable of non-literal type or of static or
  1627. // thread storage duration or [before C++2a] for which no
  1628. // initialization is performed.
  1629. const auto *VD = cast<VarDecl>(DclIt);
  1630. if (VD->isThisDeclarationADefinition()) {
  1631. if (VD->isStaticLocal()) {
  1632. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1633. SemaRef.Diag(VD->getLocation(),
  1634. diag::err_constexpr_local_var_static)
  1635. << isa<CXXConstructorDecl>(Dcl)
  1636. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1637. }
  1638. return false;
  1639. }
  1640. if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
  1641. diag::err_constexpr_local_var_non_literal_type,
  1642. isa<CXXConstructorDecl>(Dcl)))
  1643. return false;
  1644. if (!VD->getType()->isDependentType() &&
  1645. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1646. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1647. SemaRef.Diag(
  1648. VD->getLocation(),
  1649. SemaRef.getLangOpts().CPlusPlus2a
  1650. ? diag::warn_cxx17_compat_constexpr_local_var_no_init
  1651. : diag::ext_constexpr_local_var_no_init)
  1652. << isa<CXXConstructorDecl>(Dcl);
  1653. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1654. return false;
  1655. }
  1656. continue;
  1657. }
  1658. }
  1659. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1660. SemaRef.Diag(VD->getLocation(),
  1661. SemaRef.getLangOpts().CPlusPlus14
  1662. ? diag::warn_cxx11_compat_constexpr_local_var
  1663. : diag::ext_constexpr_local_var)
  1664. << isa<CXXConstructorDecl>(Dcl);
  1665. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1666. return false;
  1667. }
  1668. continue;
  1669. }
  1670. case Decl::NamespaceAlias:
  1671. case Decl::Function:
  1672. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1673. // everywhere as an extension.
  1674. if (!Cxx1yLoc.isValid())
  1675. Cxx1yLoc = DS->getBeginLoc();
  1676. continue;
  1677. default:
  1678. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1679. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1680. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1681. }
  1682. return false;
  1683. }
  1684. }
  1685. return true;
  1686. }
  1687. /// Check that the given field is initialized within a constexpr constructor.
  1688. ///
  1689. /// \param Dcl The constexpr constructor being checked.
  1690. /// \param Field The field being checked. This may be a member of an anonymous
  1691. /// struct or union nested within the class being checked.
  1692. /// \param Inits All declarations, including anonymous struct/union members and
  1693. /// indirect members, for which any initialization was provided.
  1694. /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
  1695. /// multiple notes for different members to the same error.
  1696. /// \param Kind Whether we're diagnosing a constructor as written or determining
  1697. /// whether the formal requirements are satisfied.
  1698. /// \return \c false if we're checking for validity and the constructor does
  1699. /// not satisfy the requirements on a constexpr constructor.
  1700. static bool CheckConstexprCtorInitializer(Sema &SemaRef,
  1701. const FunctionDecl *Dcl,
  1702. FieldDecl *Field,
  1703. llvm::SmallSet<Decl*, 16> &Inits,
  1704. bool &Diagnosed,
  1705. Sema::CheckConstexprKind Kind) {
  1706. // In C++20 onwards, there's nothing to check for validity.
  1707. if (Kind == Sema::CheckConstexprKind::CheckValid &&
  1708. SemaRef.getLangOpts().CPlusPlus2a)
  1709. return true;
  1710. if (Field->isInvalidDecl())
  1711. return true;
  1712. if (Field->isUnnamedBitfield())
  1713. return true;
  1714. // Anonymous unions with no variant members and empty anonymous structs do not
  1715. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1716. // indirect fields don't need initializing.
  1717. if (Field->isAnonymousStructOrUnion() &&
  1718. (Field->getType()->isUnionType()
  1719. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1720. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1721. return true;
  1722. if (!Inits.count(Field)) {
  1723. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1724. if (!Diagnosed) {
  1725. SemaRef.Diag(Dcl->getLocation(),
  1726. SemaRef.getLangOpts().CPlusPlus2a
  1727. ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
  1728. : diag::ext_constexpr_ctor_missing_init);
  1729. Diagnosed = true;
  1730. }
  1731. SemaRef.Diag(Field->getLocation(),
  1732. diag::note_constexpr_ctor_missing_init);
  1733. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1734. return false;
  1735. }
  1736. } else if (Field->isAnonymousStructOrUnion()) {
  1737. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1738. for (auto *I : RD->fields())
  1739. // If an anonymous union contains an anonymous struct of which any member
  1740. // is initialized, all members must be initialized.
  1741. if (!RD->isUnion() || Inits.count(I))
  1742. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1743. Kind))
  1744. return false;
  1745. }
  1746. return true;
  1747. }
  1748. /// Check the provided statement is allowed in a constexpr function
  1749. /// definition.
  1750. static bool
  1751. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1752. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1753. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
  1754. Sema::CheckConstexprKind Kind) {
  1755. // - its function-body shall be [...] a compound-statement that contains only
  1756. switch (S->getStmtClass()) {
  1757. case Stmt::NullStmtClass:
  1758. // - null statements,
  1759. return true;
  1760. case Stmt::DeclStmtClass:
  1761. // - static_assert-declarations
  1762. // - using-declarations,
  1763. // - using-directives,
  1764. // - typedef declarations and alias-declarations that do not define
  1765. // classes or enumerations,
  1766. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
  1767. return false;
  1768. return true;
  1769. case Stmt::ReturnStmtClass:
  1770. // - and exactly one return statement;
  1771. if (isa<CXXConstructorDecl>(Dcl)) {
  1772. // C++1y allows return statements in constexpr constructors.
  1773. if (!Cxx1yLoc.isValid())
  1774. Cxx1yLoc = S->getBeginLoc();
  1775. return true;
  1776. }
  1777. ReturnStmts.push_back(S->getBeginLoc());
  1778. return true;
  1779. case Stmt::CompoundStmtClass: {
  1780. // C++1y allows compound-statements.
  1781. if (!Cxx1yLoc.isValid())
  1782. Cxx1yLoc = S->getBeginLoc();
  1783. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1784. for (auto *BodyIt : CompStmt->body()) {
  1785. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1786. Cxx1yLoc, Cxx2aLoc, Kind))
  1787. return false;
  1788. }
  1789. return true;
  1790. }
  1791. case Stmt::AttributedStmtClass:
  1792. if (!Cxx1yLoc.isValid())
  1793. Cxx1yLoc = S->getBeginLoc();
  1794. return true;
  1795. case Stmt::IfStmtClass: {
  1796. // C++1y allows if-statements.
  1797. if (!Cxx1yLoc.isValid())
  1798. Cxx1yLoc = S->getBeginLoc();
  1799. IfStmt *If = cast<IfStmt>(S);
  1800. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1801. Cxx1yLoc, Cxx2aLoc, Kind))
  1802. return false;
  1803. if (If->getElse() &&
  1804. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1805. Cxx1yLoc, Cxx2aLoc, Kind))
  1806. return false;
  1807. return true;
  1808. }
  1809. case Stmt::WhileStmtClass:
  1810. case Stmt::DoStmtClass:
  1811. case Stmt::ForStmtClass:
  1812. case Stmt::CXXForRangeStmtClass:
  1813. case Stmt::ContinueStmtClass:
  1814. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1815. // because they don't make sense without variable mutation.
  1816. if (!SemaRef.getLangOpts().CPlusPlus14)
  1817. break;
  1818. if (!Cxx1yLoc.isValid())
  1819. Cxx1yLoc = S->getBeginLoc();
  1820. for (Stmt *SubStmt : S->children())
  1821. if (SubStmt &&
  1822. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1823. Cxx1yLoc, Cxx2aLoc, Kind))
  1824. return false;
  1825. return true;
  1826. case Stmt::SwitchStmtClass:
  1827. case Stmt::CaseStmtClass:
  1828. case Stmt::DefaultStmtClass:
  1829. case Stmt::BreakStmtClass:
  1830. // C++1y allows switch-statements, and since they don't need variable
  1831. // mutation, we can reasonably allow them in C++11 as an extension.
  1832. if (!Cxx1yLoc.isValid())
  1833. Cxx1yLoc = S->getBeginLoc();
  1834. for (Stmt *SubStmt : S->children())
  1835. if (SubStmt &&
  1836. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1837. Cxx1yLoc, Cxx2aLoc, Kind))
  1838. return false;
  1839. return true;
  1840. case Stmt::GCCAsmStmtClass:
  1841. case Stmt::MSAsmStmtClass:
  1842. // C++2a allows inline assembly statements.
  1843. case Stmt::CXXTryStmtClass:
  1844. if (Cxx2aLoc.isInvalid())
  1845. Cxx2aLoc = S->getBeginLoc();
  1846. for (Stmt *SubStmt : S->children()) {
  1847. if (SubStmt &&
  1848. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1849. Cxx1yLoc, Cxx2aLoc, Kind))
  1850. return false;
  1851. }
  1852. return true;
  1853. case Stmt::CXXCatchStmtClass:
  1854. // Do not bother checking the language mode (already covered by the
  1855. // try block check).
  1856. if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
  1857. cast<CXXCatchStmt>(S)->getHandlerBlock(),
  1858. ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
  1859. return false;
  1860. return true;
  1861. default:
  1862. if (!isa<Expr>(S))
  1863. break;
  1864. // C++1y allows expression-statements.
  1865. if (!Cxx1yLoc.isValid())
  1866. Cxx1yLoc = S->getBeginLoc();
  1867. return true;
  1868. }
  1869. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1870. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1871. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1872. }
  1873. return false;
  1874. }
  1875. /// Check the body for the given constexpr function declaration only contains
  1876. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1877. ///
  1878. /// \return true if the body is OK, false if we have found or diagnosed a
  1879. /// problem.
  1880. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1881. Stmt *Body,
  1882. Sema::CheckConstexprKind Kind) {
  1883. SmallVector<SourceLocation, 4> ReturnStmts;
  1884. if (isa<CXXTryStmt>(Body)) {
  1885. // C++11 [dcl.constexpr]p3:
  1886. // The definition of a constexpr function shall satisfy the following
  1887. // constraints: [...]
  1888. // - its function-body shall be = delete, = default, or a
  1889. // compound-statement
  1890. //
  1891. // C++11 [dcl.constexpr]p4:
  1892. // In the definition of a constexpr constructor, [...]
  1893. // - its function-body shall not be a function-try-block;
  1894. //
  1895. // This restriction is lifted in C++2a, as long as inner statements also
  1896. // apply the general constexpr rules.
  1897. switch (Kind) {
  1898. case Sema::CheckConstexprKind::CheckValid:
  1899. if (!SemaRef.getLangOpts().CPlusPlus2a)
  1900. return false;
  1901. break;
  1902. case Sema::CheckConstexprKind::Diagnose:
  1903. SemaRef.Diag(Body->getBeginLoc(),
  1904. !SemaRef.getLangOpts().CPlusPlus2a
  1905. ? diag::ext_constexpr_function_try_block_cxx2a
  1906. : diag::warn_cxx17_compat_constexpr_function_try_block)
  1907. << isa<CXXConstructorDecl>(Dcl);
  1908. break;
  1909. }
  1910. }
  1911. // - its function-body shall be [...] a compound-statement that contains only
  1912. // [... list of cases ...]
  1913. //
  1914. // Note that walking the children here is enough to properly check for
  1915. // CompoundStmt and CXXTryStmt body.
  1916. SourceLocation Cxx1yLoc, Cxx2aLoc;
  1917. for (Stmt *SubStmt : Body->children()) {
  1918. if (SubStmt &&
  1919. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1920. Cxx1yLoc, Cxx2aLoc, Kind))
  1921. return false;
  1922. }
  1923. if (Kind == Sema::CheckConstexprKind::CheckValid) {
  1924. // If this is only valid as an extension, report that we don't satisfy the
  1925. // constraints of the current language.
  1926. if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
  1927. (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
  1928. return false;
  1929. } else if (Cxx2aLoc.isValid()) {
  1930. SemaRef.Diag(Cxx2aLoc,
  1931. SemaRef.getLangOpts().CPlusPlus2a
  1932. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  1933. : diag::ext_constexpr_body_invalid_stmt_cxx2a)
  1934. << isa<CXXConstructorDecl>(Dcl);
  1935. } else if (Cxx1yLoc.isValid()) {
  1936. SemaRef.Diag(Cxx1yLoc,
  1937. SemaRef.getLangOpts().CPlusPlus14
  1938. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1939. : diag::ext_constexpr_body_invalid_stmt)
  1940. << isa<CXXConstructorDecl>(Dcl);
  1941. }
  1942. if (const CXXConstructorDecl *Constructor
  1943. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1944. const CXXRecordDecl *RD = Constructor->getParent();
  1945. // DR1359:
  1946. // - every non-variant non-static data member and base class sub-object
  1947. // shall be initialized;
  1948. // DR1460:
  1949. // - if the class is a union having variant members, exactly one of them
  1950. // shall be initialized;
  1951. if (RD->isUnion()) {
  1952. if (Constructor->getNumCtorInitializers() == 0 &&
  1953. RD->hasVariantMembers()) {
  1954. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1955. SemaRef.Diag(
  1956. Dcl->getLocation(),
  1957. SemaRef.getLangOpts().CPlusPlus2a
  1958. ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
  1959. : diag::ext_constexpr_union_ctor_no_init);
  1960. } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
  1961. return false;
  1962. }
  1963. }
  1964. } else if (!Constructor->isDependentContext() &&
  1965. !Constructor->isDelegatingConstructor()) {
  1966. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1967. // Skip detailed checking if we have enough initializers, and we would
  1968. // allow at most one initializer per member.
  1969. bool AnyAnonStructUnionMembers = false;
  1970. unsigned Fields = 0;
  1971. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1972. E = RD->field_end(); I != E; ++I, ++Fields) {
  1973. if (I->isAnonymousStructOrUnion()) {
  1974. AnyAnonStructUnionMembers = true;
  1975. break;
  1976. }
  1977. }
  1978. // DR1460:
  1979. // - if the class is a union-like class, but is not a union, for each of
  1980. // its anonymous union members having variant members, exactly one of
  1981. // them shall be initialized;
  1982. if (AnyAnonStructUnionMembers ||
  1983. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1984. // Check initialization of non-static data members. Base classes are
  1985. // always initialized so do not need to be checked. Dependent bases
  1986. // might not have initializers in the member initializer list.
  1987. llvm::SmallSet<Decl*, 16> Inits;
  1988. for (const auto *I: Constructor->inits()) {
  1989. if (FieldDecl *FD = I->getMember())
  1990. Inits.insert(FD);
  1991. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1992. Inits.insert(ID->chain_begin(), ID->chain_end());
  1993. }
  1994. bool Diagnosed = false;
  1995. for (auto *I : RD->fields())
  1996. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1997. Kind))
  1998. return false;
  1999. }
  2000. }
  2001. } else {
  2002. if (ReturnStmts.empty()) {
  2003. // C++1y doesn't require constexpr functions to contain a 'return'
  2004. // statement. We still do, unless the return type might be void, because
  2005. // otherwise if there's no return statement, the function cannot
  2006. // be used in a core constant expression.
  2007. bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
  2008. (Dcl->getReturnType()->isVoidType() ||
  2009. Dcl->getReturnType()->isDependentType());
  2010. switch (Kind) {
  2011. case Sema::CheckConstexprKind::Diagnose:
  2012. SemaRef.Diag(Dcl->getLocation(),
  2013. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  2014. : diag::err_constexpr_body_no_return)
  2015. << Dcl->isConsteval();
  2016. if (!OK)
  2017. return false;
  2018. break;
  2019. case Sema::CheckConstexprKind::CheckValid:
  2020. // The formal requirements don't include this rule in C++14, even
  2021. // though the "must be able to produce a constant expression" rules
  2022. // still imply it in some cases.
  2023. if (!SemaRef.getLangOpts().CPlusPlus14)
  2024. return false;
  2025. break;
  2026. }
  2027. } else if (ReturnStmts.size() > 1) {
  2028. switch (Kind) {
  2029. case Sema::CheckConstexprKind::Diagnose:
  2030. SemaRef.Diag(
  2031. ReturnStmts.back(),
  2032. SemaRef.getLangOpts().CPlusPlus14
  2033. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  2034. : diag::ext_constexpr_body_multiple_return);
  2035. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  2036. SemaRef.Diag(ReturnStmts[I],
  2037. diag::note_constexpr_body_previous_return);
  2038. break;
  2039. case Sema::CheckConstexprKind::CheckValid:
  2040. if (!SemaRef.getLangOpts().CPlusPlus14)
  2041. return false;
  2042. break;
  2043. }
  2044. }
  2045. }
  2046. // C++11 [dcl.constexpr]p5:
  2047. // if no function argument values exist such that the function invocation
  2048. // substitution would produce a constant expression, the program is
  2049. // ill-formed; no diagnostic required.
  2050. // C++11 [dcl.constexpr]p3:
  2051. // - every constructor call and implicit conversion used in initializing the
  2052. // return value shall be one of those allowed in a constant expression.
  2053. // C++11 [dcl.constexpr]p4:
  2054. // - every constructor involved in initializing non-static data members and
  2055. // base class sub-objects shall be a constexpr constructor.
  2056. //
  2057. // Note that this rule is distinct from the "requirements for a constexpr
  2058. // function", so is not checked in CheckValid mode.
  2059. SmallVector<PartialDiagnosticAt, 8> Diags;
  2060. if (Kind == Sema::CheckConstexprKind::Diagnose &&
  2061. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  2062. SemaRef.Diag(Dcl->getLocation(),
  2063. diag::ext_constexpr_function_never_constant_expr)
  2064. << isa<CXXConstructorDecl>(Dcl);
  2065. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  2066. SemaRef.Diag(Diags[I].first, Diags[I].second);
  2067. // Don't return false here: we allow this for compatibility in
  2068. // system headers.
  2069. }
  2070. return true;
  2071. }
  2072. /// Get the class that is directly named by the current context. This is the
  2073. /// class for which an unqualified-id in this scope could name a constructor
  2074. /// or destructor.
  2075. ///
  2076. /// If the scope specifier denotes a class, this will be that class.
  2077. /// If the scope specifier is empty, this will be the class whose
  2078. /// member-specification we are currently within. Otherwise, there
  2079. /// is no such class.
  2080. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  2081. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2082. if (SS && SS->isInvalid())
  2083. return nullptr;
  2084. if (SS && SS->isNotEmpty()) {
  2085. DeclContext *DC = computeDeclContext(*SS, true);
  2086. return dyn_cast_or_null<CXXRecordDecl>(DC);
  2087. }
  2088. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2089. }
  2090. /// isCurrentClassName - Determine whether the identifier II is the
  2091. /// name of the class type currently being defined. In the case of
  2092. /// nested classes, this will only return true if II is the name of
  2093. /// the innermost class.
  2094. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  2095. const CXXScopeSpec *SS) {
  2096. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  2097. return CurDecl && &II == CurDecl->getIdentifier();
  2098. }
  2099. /// Determine whether the identifier II is a typo for the name of
  2100. /// the class type currently being defined. If so, update it to the identifier
  2101. /// that should have been used.
  2102. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  2103. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2104. if (!getLangOpts().SpellChecking)
  2105. return false;
  2106. CXXRecordDecl *CurDecl;
  2107. if (SS && SS->isSet() && !SS->isInvalid()) {
  2108. DeclContext *DC = computeDeclContext(*SS, true);
  2109. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  2110. } else
  2111. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2112. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  2113. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  2114. < II->getLength()) {
  2115. II = CurDecl->getIdentifier();
  2116. return true;
  2117. }
  2118. return false;
  2119. }
  2120. /// Determine whether the given class is a base class of the given
  2121. /// class, including looking at dependent bases.
  2122. static bool findCircularInheritance(const CXXRecordDecl *Class,
  2123. const CXXRecordDecl *Current) {
  2124. SmallVector<const CXXRecordDecl*, 8> Queue;
  2125. Class = Class->getCanonicalDecl();
  2126. while (true) {
  2127. for (const auto &I : Current->bases()) {
  2128. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  2129. if (!Base)
  2130. continue;
  2131. Base = Base->getDefinition();
  2132. if (!Base)
  2133. continue;
  2134. if (Base->getCanonicalDecl() == Class)
  2135. return true;
  2136. Queue.push_back(Base);
  2137. }
  2138. if (Queue.empty())
  2139. return false;
  2140. Current = Queue.pop_back_val();
  2141. }
  2142. return false;
  2143. }
  2144. /// Check the validity of a C++ base class specifier.
  2145. ///
  2146. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  2147. /// and returns NULL otherwise.
  2148. CXXBaseSpecifier *
  2149. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  2150. SourceRange SpecifierRange,
  2151. bool Virtual, AccessSpecifier Access,
  2152. TypeSourceInfo *TInfo,
  2153. SourceLocation EllipsisLoc) {
  2154. QualType BaseType = TInfo->getType();
  2155. // C++ [class.union]p1:
  2156. // A union shall not have base classes.
  2157. if (Class->isUnion()) {
  2158. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  2159. << SpecifierRange;
  2160. return nullptr;
  2161. }
  2162. if (EllipsisLoc.isValid() &&
  2163. !TInfo->getType()->containsUnexpandedParameterPack()) {
  2164. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2165. << TInfo->getTypeLoc().getSourceRange();
  2166. EllipsisLoc = SourceLocation();
  2167. }
  2168. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2169. if (BaseType->isDependentType()) {
  2170. // Make sure that we don't have circular inheritance among our dependent
  2171. // bases. For non-dependent bases, the check for completeness below handles
  2172. // this.
  2173. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2174. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2175. ((BaseDecl = BaseDecl->getDefinition()) &&
  2176. findCircularInheritance(Class, BaseDecl))) {
  2177. Diag(BaseLoc, diag::err_circular_inheritance)
  2178. << BaseType << Context.getTypeDeclType(Class);
  2179. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2180. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2181. << BaseType;
  2182. return nullptr;
  2183. }
  2184. }
  2185. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2186. Class->getTagKind() == TTK_Class,
  2187. Access, TInfo, EllipsisLoc);
  2188. }
  2189. // Base specifiers must be record types.
  2190. if (!BaseType->isRecordType()) {
  2191. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2192. return nullptr;
  2193. }
  2194. // C++ [class.union]p1:
  2195. // A union shall not be used as a base class.
  2196. if (BaseType->isUnionType()) {
  2197. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2198. return nullptr;
  2199. }
  2200. // For the MS ABI, propagate DLL attributes to base class templates.
  2201. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2202. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2203. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2204. BaseType->getAsCXXRecordDecl())) {
  2205. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2206. BaseLoc);
  2207. }
  2208. }
  2209. }
  2210. // C++ [class.derived]p2:
  2211. // The class-name in a base-specifier shall not be an incompletely
  2212. // defined class.
  2213. if (RequireCompleteType(BaseLoc, BaseType,
  2214. diag::err_incomplete_base_class, SpecifierRange)) {
  2215. Class->setInvalidDecl();
  2216. return nullptr;
  2217. }
  2218. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2219. RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
  2220. assert(BaseDecl && "Record type has no declaration");
  2221. BaseDecl = BaseDecl->getDefinition();
  2222. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2223. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2224. assert(CXXBaseDecl && "Base type is not a C++ type");
  2225. // Microsoft docs say:
  2226. // "If a base-class has a code_seg attribute, derived classes must have the
  2227. // same attribute."
  2228. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2229. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2230. if ((DerivedCSA || BaseCSA) &&
  2231. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2232. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2233. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2234. << CXXBaseDecl;
  2235. return nullptr;
  2236. }
  2237. // A class which contains a flexible array member is not suitable for use as a
  2238. // base class:
  2239. // - If the layout determines that a base comes before another base,
  2240. // the flexible array member would index into the subsequent base.
  2241. // - If the layout determines that base comes before the derived class,
  2242. // the flexible array member would index into the derived class.
  2243. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2244. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2245. << CXXBaseDecl->getDeclName();
  2246. return nullptr;
  2247. }
  2248. // C++ [class]p3:
  2249. // If a class is marked final and it appears as a base-type-specifier in
  2250. // base-clause, the program is ill-formed.
  2251. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2252. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2253. << CXXBaseDecl->getDeclName()
  2254. << FA->isSpelledAsSealed();
  2255. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2256. << CXXBaseDecl->getDeclName() << FA->getRange();
  2257. return nullptr;
  2258. }
  2259. if (BaseDecl->isInvalidDecl())
  2260. Class->setInvalidDecl();
  2261. // Create the base specifier.
  2262. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2263. Class->getTagKind() == TTK_Class,
  2264. Access, TInfo, EllipsisLoc);
  2265. }
  2266. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2267. /// one entry in the base class list of a class specifier, for
  2268. /// example:
  2269. /// class foo : public bar, virtual private baz {
  2270. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2271. BaseResult
  2272. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2273. ParsedAttributes &Attributes,
  2274. bool Virtual, AccessSpecifier Access,
  2275. ParsedType basetype, SourceLocation BaseLoc,
  2276. SourceLocation EllipsisLoc) {
  2277. if (!classdecl)
  2278. return true;
  2279. AdjustDeclIfTemplate(classdecl);
  2280. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2281. if (!Class)
  2282. return true;
  2283. // We haven't yet attached the base specifiers.
  2284. Class->setIsParsingBaseSpecifiers();
  2285. // We do not support any C++11 attributes on base-specifiers yet.
  2286. // Diagnose any attributes we see.
  2287. for (const ParsedAttr &AL : Attributes) {
  2288. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2289. continue;
  2290. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2291. ? (unsigned)diag::warn_unknown_attribute_ignored
  2292. : (unsigned)diag::err_base_specifier_attribute)
  2293. << AL;
  2294. }
  2295. TypeSourceInfo *TInfo = nullptr;
  2296. GetTypeFromParser(basetype, &TInfo);
  2297. if (EllipsisLoc.isInvalid() &&
  2298. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2299. UPPC_BaseType))
  2300. return true;
  2301. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2302. Virtual, Access, TInfo,
  2303. EllipsisLoc))
  2304. return BaseSpec;
  2305. else
  2306. Class->setInvalidDecl();
  2307. return true;
  2308. }
  2309. /// Use small set to collect indirect bases. As this is only used
  2310. /// locally, there's no need to abstract the small size parameter.
  2311. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2312. /// Recursively add the bases of Type. Don't add Type itself.
  2313. static void
  2314. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2315. const QualType &Type)
  2316. {
  2317. // Even though the incoming type is a base, it might not be
  2318. // a class -- it could be a template parm, for instance.
  2319. if (auto Rec = Type->getAs<RecordType>()) {
  2320. auto Decl = Rec->getAsCXXRecordDecl();
  2321. // Iterate over its bases.
  2322. for (const auto &BaseSpec : Decl->bases()) {
  2323. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2324. .getUnqualifiedType();
  2325. if (Set.insert(Base).second)
  2326. // If we've not already seen it, recurse.
  2327. NoteIndirectBases(Context, Set, Base);
  2328. }
  2329. }
  2330. }
  2331. /// Performs the actual work of attaching the given base class
  2332. /// specifiers to a C++ class.
  2333. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2334. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2335. if (Bases.empty())
  2336. return false;
  2337. // Used to keep track of which base types we have already seen, so
  2338. // that we can properly diagnose redundant direct base types. Note
  2339. // that the key is always the unqualified canonical type of the base
  2340. // class.
  2341. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2342. // Used to track indirect bases so we can see if a direct base is
  2343. // ambiguous.
  2344. IndirectBaseSet IndirectBaseTypes;
  2345. // Copy non-redundant base specifiers into permanent storage.
  2346. unsigned NumGoodBases = 0;
  2347. bool Invalid = false;
  2348. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2349. QualType NewBaseType
  2350. = Context.getCanonicalType(Bases[idx]->getType());
  2351. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2352. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2353. if (KnownBase) {
  2354. // C++ [class.mi]p3:
  2355. // A class shall not be specified as a direct base class of a
  2356. // derived class more than once.
  2357. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2358. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2359. // Delete the duplicate base class specifier; we're going to
  2360. // overwrite its pointer later.
  2361. Context.Deallocate(Bases[idx]);
  2362. Invalid = true;
  2363. } else {
  2364. // Okay, add this new base class.
  2365. KnownBase = Bases[idx];
  2366. Bases[NumGoodBases++] = Bases[idx];
  2367. // Note this base's direct & indirect bases, if there could be ambiguity.
  2368. if (Bases.size() > 1)
  2369. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2370. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2371. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2372. if (Class->isInterface() &&
  2373. (!RD->isInterfaceLike() ||
  2374. KnownBase->getAccessSpecifier() != AS_public)) {
  2375. // The Microsoft extension __interface does not permit bases that
  2376. // are not themselves public interfaces.
  2377. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2378. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2379. << RD->getSourceRange();
  2380. Invalid = true;
  2381. }
  2382. if (RD->hasAttr<WeakAttr>())
  2383. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2384. }
  2385. }
  2386. }
  2387. // Attach the remaining base class specifiers to the derived class.
  2388. Class->setBases(Bases.data(), NumGoodBases);
  2389. // Check that the only base classes that are duplicate are virtual.
  2390. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2391. // Check whether this direct base is inaccessible due to ambiguity.
  2392. QualType BaseType = Bases[idx]->getType();
  2393. // Skip all dependent types in templates being used as base specifiers.
  2394. // Checks below assume that the base specifier is a CXXRecord.
  2395. if (BaseType->isDependentType())
  2396. continue;
  2397. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2398. .getUnqualifiedType();
  2399. if (IndirectBaseTypes.count(CanonicalBase)) {
  2400. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2401. /*DetectVirtual=*/true);
  2402. bool found
  2403. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2404. assert(found);
  2405. (void)found;
  2406. if (Paths.isAmbiguous(CanonicalBase))
  2407. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2408. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2409. << Bases[idx]->getSourceRange();
  2410. else
  2411. assert(Bases[idx]->isVirtual());
  2412. }
  2413. // Delete the base class specifier, since its data has been copied
  2414. // into the CXXRecordDecl.
  2415. Context.Deallocate(Bases[idx]);
  2416. }
  2417. return Invalid;
  2418. }
  2419. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2420. /// class, after checking whether there are any duplicate base
  2421. /// classes.
  2422. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2423. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2424. if (!ClassDecl || Bases.empty())
  2425. return;
  2426. AdjustDeclIfTemplate(ClassDecl);
  2427. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2428. }
  2429. /// Determine whether the type \p Derived is a C++ class that is
  2430. /// derived from the type \p Base.
  2431. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2432. if (!getLangOpts().CPlusPlus)
  2433. return false;
  2434. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2435. if (!DerivedRD)
  2436. return false;
  2437. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2438. if (!BaseRD)
  2439. return false;
  2440. // If either the base or the derived type is invalid, don't try to
  2441. // check whether one is derived from the other.
  2442. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2443. return false;
  2444. // FIXME: In a modules build, do we need the entire path to be visible for us
  2445. // to be able to use the inheritance relationship?
  2446. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2447. return false;
  2448. return DerivedRD->isDerivedFrom(BaseRD);
  2449. }
  2450. /// Determine whether the type \p Derived is a C++ class that is
  2451. /// derived from the type \p Base.
  2452. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2453. CXXBasePaths &Paths) {
  2454. if (!getLangOpts().CPlusPlus)
  2455. return false;
  2456. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2457. if (!DerivedRD)
  2458. return false;
  2459. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2460. if (!BaseRD)
  2461. return false;
  2462. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2463. return false;
  2464. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2465. }
  2466. static void BuildBasePathArray(const CXXBasePath &Path,
  2467. CXXCastPath &BasePathArray) {
  2468. // We first go backward and check if we have a virtual base.
  2469. // FIXME: It would be better if CXXBasePath had the base specifier for
  2470. // the nearest virtual base.
  2471. unsigned Start = 0;
  2472. for (unsigned I = Path.size(); I != 0; --I) {
  2473. if (Path[I - 1].Base->isVirtual()) {
  2474. Start = I - 1;
  2475. break;
  2476. }
  2477. }
  2478. // Now add all bases.
  2479. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2480. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2481. }
  2482. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2483. CXXCastPath &BasePathArray) {
  2484. assert(BasePathArray.empty() && "Base path array must be empty!");
  2485. assert(Paths.isRecordingPaths() && "Must record paths!");
  2486. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2487. }
  2488. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2489. /// conversion (where Derived and Base are class types) is
  2490. /// well-formed, meaning that the conversion is unambiguous (and
  2491. /// that all of the base classes are accessible). Returns true
  2492. /// and emits a diagnostic if the code is ill-formed, returns false
  2493. /// otherwise. Loc is the location where this routine should point to
  2494. /// if there is an error, and Range is the source range to highlight
  2495. /// if there is an error.
  2496. ///
  2497. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2498. /// diagnostic for the respective type of error will be suppressed, but the
  2499. /// check for ill-formed code will still be performed.
  2500. bool
  2501. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2502. unsigned InaccessibleBaseID,
  2503. unsigned AmbigiousBaseConvID,
  2504. SourceLocation Loc, SourceRange Range,
  2505. DeclarationName Name,
  2506. CXXCastPath *BasePath,
  2507. bool IgnoreAccess) {
  2508. // First, determine whether the path from Derived to Base is
  2509. // ambiguous. This is slightly more expensive than checking whether
  2510. // the Derived to Base conversion exists, because here we need to
  2511. // explore multiple paths to determine if there is an ambiguity.
  2512. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2513. /*DetectVirtual=*/false);
  2514. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2515. if (!DerivationOkay)
  2516. return true;
  2517. const CXXBasePath *Path = nullptr;
  2518. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2519. Path = &Paths.front();
  2520. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2521. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2522. // user to access such bases.
  2523. if (!Path && getLangOpts().MSVCCompat) {
  2524. for (const CXXBasePath &PossiblePath : Paths) {
  2525. if (PossiblePath.size() == 1) {
  2526. Path = &PossiblePath;
  2527. if (AmbigiousBaseConvID)
  2528. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2529. << Base << Derived << Range;
  2530. break;
  2531. }
  2532. }
  2533. }
  2534. if (Path) {
  2535. if (!IgnoreAccess) {
  2536. // Check that the base class can be accessed.
  2537. switch (
  2538. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2539. case AR_inaccessible:
  2540. return true;
  2541. case AR_accessible:
  2542. case AR_dependent:
  2543. case AR_delayed:
  2544. break;
  2545. }
  2546. }
  2547. // Build a base path if necessary.
  2548. if (BasePath)
  2549. ::BuildBasePathArray(*Path, *BasePath);
  2550. return false;
  2551. }
  2552. if (AmbigiousBaseConvID) {
  2553. // We know that the derived-to-base conversion is ambiguous, and
  2554. // we're going to produce a diagnostic. Perform the derived-to-base
  2555. // search just one more time to compute all of the possible paths so
  2556. // that we can print them out. This is more expensive than any of
  2557. // the previous derived-to-base checks we've done, but at this point
  2558. // performance isn't as much of an issue.
  2559. Paths.clear();
  2560. Paths.setRecordingPaths(true);
  2561. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2562. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2563. (void)StillOkay;
  2564. // Build up a textual representation of the ambiguous paths, e.g.,
  2565. // D -> B -> A, that will be used to illustrate the ambiguous
  2566. // conversions in the diagnostic. We only print one of the paths
  2567. // to each base class subobject.
  2568. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2569. Diag(Loc, AmbigiousBaseConvID)
  2570. << Derived << Base << PathDisplayStr << Range << Name;
  2571. }
  2572. return true;
  2573. }
  2574. bool
  2575. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2576. SourceLocation Loc, SourceRange Range,
  2577. CXXCastPath *BasePath,
  2578. bool IgnoreAccess) {
  2579. return CheckDerivedToBaseConversion(
  2580. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2581. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2582. BasePath, IgnoreAccess);
  2583. }
  2584. /// Builds a string representing ambiguous paths from a
  2585. /// specific derived class to different subobjects of the same base
  2586. /// class.
  2587. ///
  2588. /// This function builds a string that can be used in error messages
  2589. /// to show the different paths that one can take through the
  2590. /// inheritance hierarchy to go from the derived class to different
  2591. /// subobjects of a base class. The result looks something like this:
  2592. /// @code
  2593. /// struct D -> struct B -> struct A
  2594. /// struct D -> struct C -> struct A
  2595. /// @endcode
  2596. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2597. std::string PathDisplayStr;
  2598. std::set<unsigned> DisplayedPaths;
  2599. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2600. Path != Paths.end(); ++Path) {
  2601. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2602. // We haven't displayed a path to this particular base
  2603. // class subobject yet.
  2604. PathDisplayStr += "\n ";
  2605. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2606. for (CXXBasePath::const_iterator Element = Path->begin();
  2607. Element != Path->end(); ++Element)
  2608. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2609. }
  2610. }
  2611. return PathDisplayStr;
  2612. }
  2613. //===----------------------------------------------------------------------===//
  2614. // C++ class member Handling
  2615. //===----------------------------------------------------------------------===//
  2616. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2617. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2618. SourceLocation ColonLoc,
  2619. const ParsedAttributesView &Attrs) {
  2620. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2621. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2622. ASLoc, ColonLoc);
  2623. CurContext->addHiddenDecl(ASDecl);
  2624. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2625. }
  2626. /// CheckOverrideControl - Check C++11 override control semantics.
  2627. void Sema::CheckOverrideControl(NamedDecl *D) {
  2628. if (D->isInvalidDecl())
  2629. return;
  2630. // We only care about "override" and "final" declarations.
  2631. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2632. return;
  2633. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2634. // We can't check dependent instance methods.
  2635. if (MD && MD->isInstance() &&
  2636. (MD->getParent()->hasAnyDependentBases() ||
  2637. MD->getType()->isDependentType()))
  2638. return;
  2639. if (MD && !MD->isVirtual()) {
  2640. // If we have a non-virtual method, check if if hides a virtual method.
  2641. // (In that case, it's most likely the method has the wrong type.)
  2642. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2643. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2644. if (!OverloadedMethods.empty()) {
  2645. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2646. Diag(OA->getLocation(),
  2647. diag::override_keyword_hides_virtual_member_function)
  2648. << "override" << (OverloadedMethods.size() > 1);
  2649. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2650. Diag(FA->getLocation(),
  2651. diag::override_keyword_hides_virtual_member_function)
  2652. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2653. << (OverloadedMethods.size() > 1);
  2654. }
  2655. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2656. MD->setInvalidDecl();
  2657. return;
  2658. }
  2659. // Fall through into the general case diagnostic.
  2660. // FIXME: We might want to attempt typo correction here.
  2661. }
  2662. if (!MD || !MD->isVirtual()) {
  2663. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2664. Diag(OA->getLocation(),
  2665. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2666. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2667. D->dropAttr<OverrideAttr>();
  2668. }
  2669. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2670. Diag(FA->getLocation(),
  2671. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2672. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2673. << FixItHint::CreateRemoval(FA->getLocation());
  2674. D->dropAttr<FinalAttr>();
  2675. }
  2676. return;
  2677. }
  2678. // C++11 [class.virtual]p5:
  2679. // If a function is marked with the virt-specifier override and
  2680. // does not override a member function of a base class, the program is
  2681. // ill-formed.
  2682. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2683. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2684. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2685. << MD->getDeclName();
  2686. }
  2687. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2688. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2689. return;
  2690. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2691. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2692. return;
  2693. SourceLocation Loc = MD->getLocation();
  2694. SourceLocation SpellingLoc = Loc;
  2695. if (getSourceManager().isMacroArgExpansion(Loc))
  2696. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2697. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2698. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2699. return;
  2700. if (MD->size_overridden_methods() > 0) {
  2701. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2702. ? diag::warn_destructor_marked_not_override_overriding
  2703. : diag::warn_function_marked_not_override_overriding;
  2704. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2705. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2706. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2707. }
  2708. }
  2709. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2710. /// function overrides a virtual member function marked 'final', according to
  2711. /// C++11 [class.virtual]p4.
  2712. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2713. const CXXMethodDecl *Old) {
  2714. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2715. if (!FA)
  2716. return false;
  2717. Diag(New->getLocation(), diag::err_final_function_overridden)
  2718. << New->getDeclName()
  2719. << FA->isSpelledAsSealed();
  2720. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2721. return true;
  2722. }
  2723. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2724. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2725. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2726. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2727. return !RD->isCompleteDefinition() ||
  2728. !RD->hasTrivialDefaultConstructor() ||
  2729. !RD->hasTrivialDestructor();
  2730. return false;
  2731. }
  2732. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2733. ParsedAttributesView::const_iterator Itr =
  2734. llvm::find_if(list, [](const ParsedAttr &AL) {
  2735. return AL.isDeclspecPropertyAttribute();
  2736. });
  2737. if (Itr != list.end())
  2738. return &*Itr;
  2739. return nullptr;
  2740. }
  2741. // Check if there is a field shadowing.
  2742. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2743. DeclarationName FieldName,
  2744. const CXXRecordDecl *RD,
  2745. bool DeclIsField) {
  2746. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2747. return;
  2748. // To record a shadowed field in a base
  2749. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2750. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2751. CXXBasePath &Path) {
  2752. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2753. // Record an ambiguous path directly
  2754. if (Bases.find(Base) != Bases.end())
  2755. return true;
  2756. for (const auto Field : Base->lookup(FieldName)) {
  2757. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2758. Field->getAccess() != AS_private) {
  2759. assert(Field->getAccess() != AS_none);
  2760. assert(Bases.find(Base) == Bases.end());
  2761. Bases[Base] = Field;
  2762. return true;
  2763. }
  2764. }
  2765. return false;
  2766. };
  2767. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2768. /*DetectVirtual=*/true);
  2769. if (!RD->lookupInBases(FieldShadowed, Paths))
  2770. return;
  2771. for (const auto &P : Paths) {
  2772. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2773. auto It = Bases.find(Base);
  2774. // Skip duplicated bases
  2775. if (It == Bases.end())
  2776. continue;
  2777. auto BaseField = It->second;
  2778. assert(BaseField->getAccess() != AS_private);
  2779. if (AS_none !=
  2780. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2781. Diag(Loc, diag::warn_shadow_field)
  2782. << FieldName << RD << Base << DeclIsField;
  2783. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2784. Bases.erase(It);
  2785. }
  2786. }
  2787. }
  2788. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2789. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2790. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2791. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2792. /// present (but parsing it has been deferred).
  2793. NamedDecl *
  2794. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2795. MultiTemplateParamsArg TemplateParameterLists,
  2796. Expr *BW, const VirtSpecifiers &VS,
  2797. InClassInitStyle InitStyle) {
  2798. const DeclSpec &DS = D.getDeclSpec();
  2799. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2800. DeclarationName Name = NameInfo.getName();
  2801. SourceLocation Loc = NameInfo.getLoc();
  2802. // For anonymous bitfields, the location should point to the type.
  2803. if (Loc.isInvalid())
  2804. Loc = D.getBeginLoc();
  2805. Expr *BitWidth = static_cast<Expr*>(BW);
  2806. assert(isa<CXXRecordDecl>(CurContext));
  2807. assert(!DS.isFriendSpecified());
  2808. bool isFunc = D.isDeclarationOfFunction();
  2809. const ParsedAttr *MSPropertyAttr =
  2810. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2811. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2812. // The Microsoft extension __interface only permits public member functions
  2813. // and prohibits constructors, destructors, operators, non-public member
  2814. // functions, static methods and data members.
  2815. unsigned InvalidDecl;
  2816. bool ShowDeclName = true;
  2817. if (!isFunc &&
  2818. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2819. InvalidDecl = 0;
  2820. else if (!isFunc)
  2821. InvalidDecl = 1;
  2822. else if (AS != AS_public)
  2823. InvalidDecl = 2;
  2824. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2825. InvalidDecl = 3;
  2826. else switch (Name.getNameKind()) {
  2827. case DeclarationName::CXXConstructorName:
  2828. InvalidDecl = 4;
  2829. ShowDeclName = false;
  2830. break;
  2831. case DeclarationName::CXXDestructorName:
  2832. InvalidDecl = 5;
  2833. ShowDeclName = false;
  2834. break;
  2835. case DeclarationName::CXXOperatorName:
  2836. case DeclarationName::CXXConversionFunctionName:
  2837. InvalidDecl = 6;
  2838. break;
  2839. default:
  2840. InvalidDecl = 0;
  2841. break;
  2842. }
  2843. if (InvalidDecl) {
  2844. if (ShowDeclName)
  2845. Diag(Loc, diag::err_invalid_member_in_interface)
  2846. << (InvalidDecl-1) << Name;
  2847. else
  2848. Diag(Loc, diag::err_invalid_member_in_interface)
  2849. << (InvalidDecl-1) << "";
  2850. return nullptr;
  2851. }
  2852. }
  2853. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2854. // duration (auto, register) or with the extern storage-class-specifier.
  2855. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2856. // data members and cannot be applied to names declared const or static,
  2857. // and cannot be applied to reference members.
  2858. switch (DS.getStorageClassSpec()) {
  2859. case DeclSpec::SCS_unspecified:
  2860. case DeclSpec::SCS_typedef:
  2861. case DeclSpec::SCS_static:
  2862. break;
  2863. case DeclSpec::SCS_mutable:
  2864. if (isFunc) {
  2865. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2866. // FIXME: It would be nicer if the keyword was ignored only for this
  2867. // declarator. Otherwise we could get follow-up errors.
  2868. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2869. }
  2870. break;
  2871. default:
  2872. Diag(DS.getStorageClassSpecLoc(),
  2873. diag::err_storageclass_invalid_for_member);
  2874. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2875. break;
  2876. }
  2877. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2878. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2879. !isFunc);
  2880. if (DS.hasConstexprSpecifier() && isInstField) {
  2881. SemaDiagnosticBuilder B =
  2882. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2883. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2884. if (InitStyle == ICIS_NoInit) {
  2885. B << 0 << 0;
  2886. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2887. B << FixItHint::CreateRemoval(ConstexprLoc);
  2888. else {
  2889. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2890. D.getMutableDeclSpec().ClearConstexprSpec();
  2891. const char *PrevSpec;
  2892. unsigned DiagID;
  2893. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2894. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2895. (void)Failed;
  2896. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2897. }
  2898. } else {
  2899. B << 1;
  2900. const char *PrevSpec;
  2901. unsigned DiagID;
  2902. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2903. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2904. Context.getPrintingPolicy())) {
  2905. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2906. "This is the only DeclSpec that should fail to be applied");
  2907. B << 1;
  2908. } else {
  2909. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2910. isInstField = false;
  2911. }
  2912. }
  2913. }
  2914. NamedDecl *Member;
  2915. if (isInstField) {
  2916. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2917. // Data members must have identifiers for names.
  2918. if (!Name.isIdentifier()) {
  2919. Diag(Loc, diag::err_bad_variable_name)
  2920. << Name;
  2921. return nullptr;
  2922. }
  2923. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2924. // Member field could not be with "template" keyword.
  2925. // So TemplateParameterLists should be empty in this case.
  2926. if (TemplateParameterLists.size()) {
  2927. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2928. if (TemplateParams->size()) {
  2929. // There is no such thing as a member field template.
  2930. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2931. << II
  2932. << SourceRange(TemplateParams->getTemplateLoc(),
  2933. TemplateParams->getRAngleLoc());
  2934. } else {
  2935. // There is an extraneous 'template<>' for this member.
  2936. Diag(TemplateParams->getTemplateLoc(),
  2937. diag::err_template_member_noparams)
  2938. << II
  2939. << SourceRange(TemplateParams->getTemplateLoc(),
  2940. TemplateParams->getRAngleLoc());
  2941. }
  2942. return nullptr;
  2943. }
  2944. if (SS.isSet() && !SS.isInvalid()) {
  2945. // The user provided a superfluous scope specifier inside a class
  2946. // definition:
  2947. //
  2948. // class X {
  2949. // int X::member;
  2950. // };
  2951. if (DeclContext *DC = computeDeclContext(SS, false))
  2952. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2953. D.getName().getKind() ==
  2954. UnqualifiedIdKind::IK_TemplateId);
  2955. else
  2956. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2957. << Name << SS.getRange();
  2958. SS.clear();
  2959. }
  2960. if (MSPropertyAttr) {
  2961. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2962. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2963. if (!Member)
  2964. return nullptr;
  2965. isInstField = false;
  2966. } else {
  2967. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2968. BitWidth, InitStyle, AS);
  2969. if (!Member)
  2970. return nullptr;
  2971. }
  2972. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2973. } else {
  2974. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2975. if (!Member)
  2976. return nullptr;
  2977. // Non-instance-fields can't have a bitfield.
  2978. if (BitWidth) {
  2979. if (Member->isInvalidDecl()) {
  2980. // don't emit another diagnostic.
  2981. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2982. // C++ 9.6p3: A bit-field shall not be a static member.
  2983. // "static member 'A' cannot be a bit-field"
  2984. Diag(Loc, diag::err_static_not_bitfield)
  2985. << Name << BitWidth->getSourceRange();
  2986. } else if (isa<TypedefDecl>(Member)) {
  2987. // "typedef member 'x' cannot be a bit-field"
  2988. Diag(Loc, diag::err_typedef_not_bitfield)
  2989. << Name << BitWidth->getSourceRange();
  2990. } else {
  2991. // A function typedef ("typedef int f(); f a;").
  2992. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2993. Diag(Loc, diag::err_not_integral_type_bitfield)
  2994. << Name << cast<ValueDecl>(Member)->getType()
  2995. << BitWidth->getSourceRange();
  2996. }
  2997. BitWidth = nullptr;
  2998. Member->setInvalidDecl();
  2999. }
  3000. NamedDecl *NonTemplateMember = Member;
  3001. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  3002. NonTemplateMember = FunTmpl->getTemplatedDecl();
  3003. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  3004. NonTemplateMember = VarTmpl->getTemplatedDecl();
  3005. Member->setAccess(AS);
  3006. // If we have declared a member function template or static data member
  3007. // template, set the access of the templated declaration as well.
  3008. if (NonTemplateMember != Member)
  3009. NonTemplateMember->setAccess(AS);
  3010. // C++ [temp.deduct.guide]p3:
  3011. // A deduction guide [...] for a member class template [shall be
  3012. // declared] with the same access [as the template].
  3013. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  3014. auto *TD = DG->getDeducedTemplate();
  3015. // Access specifiers are only meaningful if both the template and the
  3016. // deduction guide are from the same scope.
  3017. if (AS != TD->getAccess() &&
  3018. TD->getDeclContext()->getRedeclContext()->Equals(
  3019. DG->getDeclContext()->getRedeclContext())) {
  3020. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  3021. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  3022. << TD->getAccess();
  3023. const AccessSpecDecl *LastAccessSpec = nullptr;
  3024. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  3025. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  3026. LastAccessSpec = AccessSpec;
  3027. }
  3028. assert(LastAccessSpec && "differing access with no access specifier");
  3029. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  3030. << AS;
  3031. }
  3032. }
  3033. }
  3034. if (VS.isOverrideSpecified())
  3035. Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
  3036. AttributeCommonInfo::AS_Keyword));
  3037. if (VS.isFinalSpecified())
  3038. Member->addAttr(FinalAttr::Create(
  3039. Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
  3040. static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
  3041. if (VS.getLastLocation().isValid()) {
  3042. // Update the end location of a method that has a virt-specifiers.
  3043. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  3044. MD->setRangeEnd(VS.getLastLocation());
  3045. }
  3046. CheckOverrideControl(Member);
  3047. assert((Name || isInstField) && "No identifier for non-field ?");
  3048. if (isInstField) {
  3049. FieldDecl *FD = cast<FieldDecl>(Member);
  3050. FieldCollector->Add(FD);
  3051. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  3052. // Remember all explicit private FieldDecls that have a name, no side
  3053. // effects and are not part of a dependent type declaration.
  3054. if (!FD->isImplicit() && FD->getDeclName() &&
  3055. FD->getAccess() == AS_private &&
  3056. !FD->hasAttr<UnusedAttr>() &&
  3057. !FD->getParent()->isDependentContext() &&
  3058. !InitializationHasSideEffects(*FD))
  3059. UnusedPrivateFields.insert(FD);
  3060. }
  3061. }
  3062. return Member;
  3063. }
  3064. namespace {
  3065. class UninitializedFieldVisitor
  3066. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  3067. Sema &S;
  3068. // List of Decls to generate a warning on. Also remove Decls that become
  3069. // initialized.
  3070. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  3071. // List of base classes of the record. Classes are removed after their
  3072. // initializers.
  3073. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  3074. // Vector of decls to be removed from the Decl set prior to visiting the
  3075. // nodes. These Decls may have been initialized in the prior initializer.
  3076. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  3077. // If non-null, add a note to the warning pointing back to the constructor.
  3078. const CXXConstructorDecl *Constructor;
  3079. // Variables to hold state when processing an initializer list. When
  3080. // InitList is true, special case initialization of FieldDecls matching
  3081. // InitListFieldDecl.
  3082. bool InitList;
  3083. FieldDecl *InitListFieldDecl;
  3084. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  3085. public:
  3086. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  3087. UninitializedFieldVisitor(Sema &S,
  3088. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  3089. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  3090. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  3091. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  3092. // Returns true if the use of ME is not an uninitialized use.
  3093. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  3094. bool CheckReferenceOnly) {
  3095. llvm::SmallVector<FieldDecl*, 4> Fields;
  3096. bool ReferenceField = false;
  3097. while (ME) {
  3098. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  3099. if (!FD)
  3100. return false;
  3101. Fields.push_back(FD);
  3102. if (FD->getType()->isReferenceType())
  3103. ReferenceField = true;
  3104. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  3105. }
  3106. // Binding a reference to an uninitialized field is not an
  3107. // uninitialized use.
  3108. if (CheckReferenceOnly && !ReferenceField)
  3109. return true;
  3110. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  3111. // Discard the first field since it is the field decl that is being
  3112. // initialized.
  3113. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  3114. UsedFieldIndex.push_back((*I)->getFieldIndex());
  3115. }
  3116. for (auto UsedIter = UsedFieldIndex.begin(),
  3117. UsedEnd = UsedFieldIndex.end(),
  3118. OrigIter = InitFieldIndex.begin(),
  3119. OrigEnd = InitFieldIndex.end();
  3120. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  3121. if (*UsedIter < *OrigIter)
  3122. return true;
  3123. if (*UsedIter > *OrigIter)
  3124. break;
  3125. }
  3126. return false;
  3127. }
  3128. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  3129. bool AddressOf) {
  3130. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  3131. return;
  3132. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  3133. // or union.
  3134. MemberExpr *FieldME = ME;
  3135. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  3136. Expr *Base = ME;
  3137. while (MemberExpr *SubME =
  3138. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  3139. if (isa<VarDecl>(SubME->getMemberDecl()))
  3140. return;
  3141. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  3142. if (!FD->isAnonymousStructOrUnion())
  3143. FieldME = SubME;
  3144. if (!FieldME->getType().isPODType(S.Context))
  3145. AllPODFields = false;
  3146. Base = SubME->getBase();
  3147. }
  3148. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  3149. return;
  3150. if (AddressOf && AllPODFields)
  3151. return;
  3152. ValueDecl* FoundVD = FieldME->getMemberDecl();
  3153. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  3154. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  3155. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  3156. }
  3157. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  3158. QualType T = BaseCast->getType();
  3159. if (T->isPointerType() &&
  3160. BaseClasses.count(T->getPointeeType())) {
  3161. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  3162. << T->getPointeeType() << FoundVD;
  3163. }
  3164. }
  3165. }
  3166. if (!Decls.count(FoundVD))
  3167. return;
  3168. const bool IsReference = FoundVD->getType()->isReferenceType();
  3169. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3170. // Special checking for initializer lists.
  3171. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3172. return;
  3173. }
  3174. } else {
  3175. // Prevent double warnings on use of unbounded references.
  3176. if (CheckReferenceOnly && !IsReference)
  3177. return;
  3178. }
  3179. unsigned diag = IsReference
  3180. ? diag::warn_reference_field_is_uninit
  3181. : diag::warn_field_is_uninit;
  3182. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3183. if (Constructor)
  3184. S.Diag(Constructor->getLocation(),
  3185. diag::note_uninit_in_this_constructor)
  3186. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3187. }
  3188. void HandleValue(Expr *E, bool AddressOf) {
  3189. E = E->IgnoreParens();
  3190. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3191. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3192. AddressOf /*AddressOf*/);
  3193. return;
  3194. }
  3195. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3196. Visit(CO->getCond());
  3197. HandleValue(CO->getTrueExpr(), AddressOf);
  3198. HandleValue(CO->getFalseExpr(), AddressOf);
  3199. return;
  3200. }
  3201. if (BinaryConditionalOperator *BCO =
  3202. dyn_cast<BinaryConditionalOperator>(E)) {
  3203. Visit(BCO->getCond());
  3204. HandleValue(BCO->getFalseExpr(), AddressOf);
  3205. return;
  3206. }
  3207. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3208. HandleValue(OVE->getSourceExpr(), AddressOf);
  3209. return;
  3210. }
  3211. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3212. switch (BO->getOpcode()) {
  3213. default:
  3214. break;
  3215. case(BO_PtrMemD):
  3216. case(BO_PtrMemI):
  3217. HandleValue(BO->getLHS(), AddressOf);
  3218. Visit(BO->getRHS());
  3219. return;
  3220. case(BO_Comma):
  3221. Visit(BO->getLHS());
  3222. HandleValue(BO->getRHS(), AddressOf);
  3223. return;
  3224. }
  3225. }
  3226. Visit(E);
  3227. }
  3228. void CheckInitListExpr(InitListExpr *ILE) {
  3229. InitFieldIndex.push_back(0);
  3230. for (auto Child : ILE->children()) {
  3231. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3232. CheckInitListExpr(SubList);
  3233. } else {
  3234. Visit(Child);
  3235. }
  3236. ++InitFieldIndex.back();
  3237. }
  3238. InitFieldIndex.pop_back();
  3239. }
  3240. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3241. FieldDecl *Field, const Type *BaseClass) {
  3242. // Remove Decls that may have been initialized in the previous
  3243. // initializer.
  3244. for (ValueDecl* VD : DeclsToRemove)
  3245. Decls.erase(VD);
  3246. DeclsToRemove.clear();
  3247. Constructor = FieldConstructor;
  3248. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3249. if (ILE && Field) {
  3250. InitList = true;
  3251. InitListFieldDecl = Field;
  3252. InitFieldIndex.clear();
  3253. CheckInitListExpr(ILE);
  3254. } else {
  3255. InitList = false;
  3256. Visit(E);
  3257. }
  3258. if (Field)
  3259. Decls.erase(Field);
  3260. if (BaseClass)
  3261. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3262. }
  3263. void VisitMemberExpr(MemberExpr *ME) {
  3264. // All uses of unbounded reference fields will warn.
  3265. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3266. }
  3267. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3268. if (E->getCastKind() == CK_LValueToRValue) {
  3269. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3270. return;
  3271. }
  3272. Inherited::VisitImplicitCastExpr(E);
  3273. }
  3274. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3275. if (E->getConstructor()->isCopyConstructor()) {
  3276. Expr *ArgExpr = E->getArg(0);
  3277. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3278. if (ILE->getNumInits() == 1)
  3279. ArgExpr = ILE->getInit(0);
  3280. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3281. if (ICE->getCastKind() == CK_NoOp)
  3282. ArgExpr = ICE->getSubExpr();
  3283. HandleValue(ArgExpr, false /*AddressOf*/);
  3284. return;
  3285. }
  3286. Inherited::VisitCXXConstructExpr(E);
  3287. }
  3288. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3289. Expr *Callee = E->getCallee();
  3290. if (isa<MemberExpr>(Callee)) {
  3291. HandleValue(Callee, false /*AddressOf*/);
  3292. for (auto Arg : E->arguments())
  3293. Visit(Arg);
  3294. return;
  3295. }
  3296. Inherited::VisitCXXMemberCallExpr(E);
  3297. }
  3298. void VisitCallExpr(CallExpr *E) {
  3299. // Treat std::move as a use.
  3300. if (E->isCallToStdMove()) {
  3301. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3302. return;
  3303. }
  3304. Inherited::VisitCallExpr(E);
  3305. }
  3306. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3307. Expr *Callee = E->getCallee();
  3308. if (isa<UnresolvedLookupExpr>(Callee))
  3309. return Inherited::VisitCXXOperatorCallExpr(E);
  3310. Visit(Callee);
  3311. for (auto Arg : E->arguments())
  3312. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3313. }
  3314. void VisitBinaryOperator(BinaryOperator *E) {
  3315. // If a field assignment is detected, remove the field from the
  3316. // uninitiailized field set.
  3317. if (E->getOpcode() == BO_Assign)
  3318. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3319. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3320. if (!FD->getType()->isReferenceType())
  3321. DeclsToRemove.push_back(FD);
  3322. if (E->isCompoundAssignmentOp()) {
  3323. HandleValue(E->getLHS(), false /*AddressOf*/);
  3324. Visit(E->getRHS());
  3325. return;
  3326. }
  3327. Inherited::VisitBinaryOperator(E);
  3328. }
  3329. void VisitUnaryOperator(UnaryOperator *E) {
  3330. if (E->isIncrementDecrementOp()) {
  3331. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3332. return;
  3333. }
  3334. if (E->getOpcode() == UO_AddrOf) {
  3335. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3336. HandleValue(ME->getBase(), true /*AddressOf*/);
  3337. return;
  3338. }
  3339. }
  3340. Inherited::VisitUnaryOperator(E);
  3341. }
  3342. };
  3343. // Diagnose value-uses of fields to initialize themselves, e.g.
  3344. // foo(foo)
  3345. // where foo is not also a parameter to the constructor.
  3346. // Also diagnose across field uninitialized use such as
  3347. // x(y), y(x)
  3348. // TODO: implement -Wuninitialized and fold this into that framework.
  3349. static void DiagnoseUninitializedFields(
  3350. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3351. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3352. Constructor->getLocation())) {
  3353. return;
  3354. }
  3355. if (Constructor->isInvalidDecl())
  3356. return;
  3357. const CXXRecordDecl *RD = Constructor->getParent();
  3358. if (RD->getDescribedClassTemplate())
  3359. return;
  3360. // Holds fields that are uninitialized.
  3361. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3362. // At the beginning, all fields are uninitialized.
  3363. for (auto *I : RD->decls()) {
  3364. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3365. UninitializedFields.insert(FD);
  3366. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3367. UninitializedFields.insert(IFD->getAnonField());
  3368. }
  3369. }
  3370. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3371. for (auto I : RD->bases())
  3372. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3373. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3374. return;
  3375. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3376. UninitializedFields,
  3377. UninitializedBaseClasses);
  3378. for (const auto *FieldInit : Constructor->inits()) {
  3379. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3380. break;
  3381. Expr *InitExpr = FieldInit->getInit();
  3382. if (!InitExpr)
  3383. continue;
  3384. if (CXXDefaultInitExpr *Default =
  3385. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3386. InitExpr = Default->getExpr();
  3387. if (!InitExpr)
  3388. continue;
  3389. // In class initializers will point to the constructor.
  3390. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3391. FieldInit->getAnyMember(),
  3392. FieldInit->getBaseClass());
  3393. } else {
  3394. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3395. FieldInit->getAnyMember(),
  3396. FieldInit->getBaseClass());
  3397. }
  3398. }
  3399. }
  3400. } // namespace
  3401. /// Enter a new C++ default initializer scope. After calling this, the
  3402. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3403. /// parsing or instantiating the initializer failed.
  3404. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3405. // Create a synthetic function scope to represent the call to the constructor
  3406. // that notionally surrounds a use of this initializer.
  3407. PushFunctionScope();
  3408. }
  3409. /// This is invoked after parsing an in-class initializer for a
  3410. /// non-static C++ class member, and after instantiating an in-class initializer
  3411. /// in a class template. Such actions are deferred until the class is complete.
  3412. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3413. SourceLocation InitLoc,
  3414. Expr *InitExpr) {
  3415. // Pop the notional constructor scope we created earlier.
  3416. PopFunctionScopeInfo(nullptr, D);
  3417. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3418. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3419. "must set init style when field is created");
  3420. if (!InitExpr) {
  3421. D->setInvalidDecl();
  3422. if (FD)
  3423. FD->removeInClassInitializer();
  3424. return;
  3425. }
  3426. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3427. FD->setInvalidDecl();
  3428. FD->removeInClassInitializer();
  3429. return;
  3430. }
  3431. ExprResult Init = InitExpr;
  3432. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3433. InitializedEntity Entity =
  3434. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3435. InitializationKind Kind =
  3436. FD->getInClassInitStyle() == ICIS_ListInit
  3437. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3438. InitExpr->getBeginLoc(),
  3439. InitExpr->getEndLoc())
  3440. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3441. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3442. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3443. if (Init.isInvalid()) {
  3444. FD->setInvalidDecl();
  3445. return;
  3446. }
  3447. }
  3448. // C++11 [class.base.init]p7:
  3449. // The initialization of each base and member constitutes a
  3450. // full-expression.
  3451. Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
  3452. if (Init.isInvalid()) {
  3453. FD->setInvalidDecl();
  3454. return;
  3455. }
  3456. InitExpr = Init.get();
  3457. FD->setInClassInitializer(InitExpr);
  3458. }
  3459. /// Find the direct and/or virtual base specifiers that
  3460. /// correspond to the given base type, for use in base initialization
  3461. /// within a constructor.
  3462. static bool FindBaseInitializer(Sema &SemaRef,
  3463. CXXRecordDecl *ClassDecl,
  3464. QualType BaseType,
  3465. const CXXBaseSpecifier *&DirectBaseSpec,
  3466. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3467. // First, check for a direct base class.
  3468. DirectBaseSpec = nullptr;
  3469. for (const auto &Base : ClassDecl->bases()) {
  3470. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3471. // We found a direct base of this type. That's what we're
  3472. // initializing.
  3473. DirectBaseSpec = &Base;
  3474. break;
  3475. }
  3476. }
  3477. // Check for a virtual base class.
  3478. // FIXME: We might be able to short-circuit this if we know in advance that
  3479. // there are no virtual bases.
  3480. VirtualBaseSpec = nullptr;
  3481. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3482. // We haven't found a base yet; search the class hierarchy for a
  3483. // virtual base class.
  3484. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3485. /*DetectVirtual=*/false);
  3486. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3487. SemaRef.Context.getTypeDeclType(ClassDecl),
  3488. BaseType, Paths)) {
  3489. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3490. Path != Paths.end(); ++Path) {
  3491. if (Path->back().Base->isVirtual()) {
  3492. VirtualBaseSpec = Path->back().Base;
  3493. break;
  3494. }
  3495. }
  3496. }
  3497. }
  3498. return DirectBaseSpec || VirtualBaseSpec;
  3499. }
  3500. /// Handle a C++ member initializer using braced-init-list syntax.
  3501. MemInitResult
  3502. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3503. Scope *S,
  3504. CXXScopeSpec &SS,
  3505. IdentifierInfo *MemberOrBase,
  3506. ParsedType TemplateTypeTy,
  3507. const DeclSpec &DS,
  3508. SourceLocation IdLoc,
  3509. Expr *InitList,
  3510. SourceLocation EllipsisLoc) {
  3511. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3512. DS, IdLoc, InitList,
  3513. EllipsisLoc);
  3514. }
  3515. /// Handle a C++ member initializer using parentheses syntax.
  3516. MemInitResult
  3517. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3518. Scope *S,
  3519. CXXScopeSpec &SS,
  3520. IdentifierInfo *MemberOrBase,
  3521. ParsedType TemplateTypeTy,
  3522. const DeclSpec &DS,
  3523. SourceLocation IdLoc,
  3524. SourceLocation LParenLoc,
  3525. ArrayRef<Expr *> Args,
  3526. SourceLocation RParenLoc,
  3527. SourceLocation EllipsisLoc) {
  3528. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3529. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3530. DS, IdLoc, List, EllipsisLoc);
  3531. }
  3532. namespace {
  3533. // Callback to only accept typo corrections that can be a valid C++ member
  3534. // intializer: either a non-static field member or a base class.
  3535. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3536. public:
  3537. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3538. : ClassDecl(ClassDecl) {}
  3539. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3540. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3541. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3542. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3543. return isa<TypeDecl>(ND);
  3544. }
  3545. return false;
  3546. }
  3547. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3548. return std::make_unique<MemInitializerValidatorCCC>(*this);
  3549. }
  3550. private:
  3551. CXXRecordDecl *ClassDecl;
  3552. };
  3553. }
  3554. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3555. CXXScopeSpec &SS,
  3556. ParsedType TemplateTypeTy,
  3557. IdentifierInfo *MemberOrBase) {
  3558. if (SS.getScopeRep() || TemplateTypeTy)
  3559. return nullptr;
  3560. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3561. if (Result.empty())
  3562. return nullptr;
  3563. ValueDecl *Member;
  3564. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3565. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3566. return Member;
  3567. return nullptr;
  3568. }
  3569. /// Handle a C++ member initializer.
  3570. MemInitResult
  3571. Sema::BuildMemInitializer(Decl *ConstructorD,
  3572. Scope *S,
  3573. CXXScopeSpec &SS,
  3574. IdentifierInfo *MemberOrBase,
  3575. ParsedType TemplateTypeTy,
  3576. const DeclSpec &DS,
  3577. SourceLocation IdLoc,
  3578. Expr *Init,
  3579. SourceLocation EllipsisLoc) {
  3580. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3581. if (!Res.isUsable())
  3582. return true;
  3583. Init = Res.get();
  3584. if (!ConstructorD)
  3585. return true;
  3586. AdjustDeclIfTemplate(ConstructorD);
  3587. CXXConstructorDecl *Constructor
  3588. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3589. if (!Constructor) {
  3590. // The user wrote a constructor initializer on a function that is
  3591. // not a C++ constructor. Ignore the error for now, because we may
  3592. // have more member initializers coming; we'll diagnose it just
  3593. // once in ActOnMemInitializers.
  3594. return true;
  3595. }
  3596. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3597. // C++ [class.base.init]p2:
  3598. // Names in a mem-initializer-id are looked up in the scope of the
  3599. // constructor's class and, if not found in that scope, are looked
  3600. // up in the scope containing the constructor's definition.
  3601. // [Note: if the constructor's class contains a member with the
  3602. // same name as a direct or virtual base class of the class, a
  3603. // mem-initializer-id naming the member or base class and composed
  3604. // of a single identifier refers to the class member. A
  3605. // mem-initializer-id for the hidden base class may be specified
  3606. // using a qualified name. ]
  3607. // Look for a member, first.
  3608. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3609. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3610. if (EllipsisLoc.isValid())
  3611. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3612. << MemberOrBase
  3613. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3614. return BuildMemberInitializer(Member, Init, IdLoc);
  3615. }
  3616. // It didn't name a member, so see if it names a class.
  3617. QualType BaseType;
  3618. TypeSourceInfo *TInfo = nullptr;
  3619. if (TemplateTypeTy) {
  3620. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3621. if (BaseType.isNull())
  3622. return true;
  3623. } else if (DS.getTypeSpecType() == TST_decltype) {
  3624. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3625. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3626. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3627. return true;
  3628. } else {
  3629. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3630. LookupParsedName(R, S, &SS);
  3631. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3632. if (!TyD) {
  3633. if (R.isAmbiguous()) return true;
  3634. // We don't want access-control diagnostics here.
  3635. R.suppressDiagnostics();
  3636. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3637. bool NotUnknownSpecialization = false;
  3638. DeclContext *DC = computeDeclContext(SS, false);
  3639. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3640. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3641. if (!NotUnknownSpecialization) {
  3642. // When the scope specifier can refer to a member of an unknown
  3643. // specialization, we take it as a type name.
  3644. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3645. SS.getWithLocInContext(Context),
  3646. *MemberOrBase, IdLoc);
  3647. if (BaseType.isNull())
  3648. return true;
  3649. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3650. DependentNameTypeLoc TL =
  3651. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3652. if (!TL.isNull()) {
  3653. TL.setNameLoc(IdLoc);
  3654. TL.setElaboratedKeywordLoc(SourceLocation());
  3655. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3656. }
  3657. R.clear();
  3658. R.setLookupName(MemberOrBase);
  3659. }
  3660. }
  3661. // If no results were found, try to correct typos.
  3662. TypoCorrection Corr;
  3663. MemInitializerValidatorCCC CCC(ClassDecl);
  3664. if (R.empty() && BaseType.isNull() &&
  3665. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3666. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3667. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3668. // We have found a non-static data member with a similar
  3669. // name to what was typed; complain and initialize that
  3670. // member.
  3671. diagnoseTypo(Corr,
  3672. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3673. << MemberOrBase << true);
  3674. return BuildMemberInitializer(Member, Init, IdLoc);
  3675. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3676. const CXXBaseSpecifier *DirectBaseSpec;
  3677. const CXXBaseSpecifier *VirtualBaseSpec;
  3678. if (FindBaseInitializer(*this, ClassDecl,
  3679. Context.getTypeDeclType(Type),
  3680. DirectBaseSpec, VirtualBaseSpec)) {
  3681. // We have found a direct or virtual base class with a
  3682. // similar name to what was typed; complain and initialize
  3683. // that base class.
  3684. diagnoseTypo(Corr,
  3685. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3686. << MemberOrBase << false,
  3687. PDiag() /*Suppress note, we provide our own.*/);
  3688. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3689. : VirtualBaseSpec;
  3690. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3691. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3692. TyD = Type;
  3693. }
  3694. }
  3695. }
  3696. if (!TyD && BaseType.isNull()) {
  3697. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3698. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3699. return true;
  3700. }
  3701. }
  3702. if (BaseType.isNull()) {
  3703. BaseType = Context.getTypeDeclType(TyD);
  3704. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3705. if (SS.isSet()) {
  3706. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3707. BaseType);
  3708. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3709. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3710. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3711. TL.setElaboratedKeywordLoc(SourceLocation());
  3712. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3713. }
  3714. }
  3715. }
  3716. if (!TInfo)
  3717. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3718. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3719. }
  3720. MemInitResult
  3721. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3722. SourceLocation IdLoc) {
  3723. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3724. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3725. assert((DirectMember || IndirectMember) &&
  3726. "Member must be a FieldDecl or IndirectFieldDecl");
  3727. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3728. return true;
  3729. if (Member->isInvalidDecl())
  3730. return true;
  3731. MultiExprArg Args;
  3732. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3733. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3734. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3735. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3736. } else {
  3737. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3738. Args = Init;
  3739. }
  3740. SourceRange InitRange = Init->getSourceRange();
  3741. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3742. // Can't check initialization for a member of dependent type or when
  3743. // any of the arguments are type-dependent expressions.
  3744. DiscardCleanupsInEvaluationContext();
  3745. } else {
  3746. bool InitList = false;
  3747. if (isa<InitListExpr>(Init)) {
  3748. InitList = true;
  3749. Args = Init;
  3750. }
  3751. // Initialize the member.
  3752. InitializedEntity MemberEntity =
  3753. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3754. : InitializedEntity::InitializeMember(IndirectMember,
  3755. nullptr);
  3756. InitializationKind Kind =
  3757. InitList ? InitializationKind::CreateDirectList(
  3758. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3759. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3760. InitRange.getEnd());
  3761. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3762. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3763. nullptr);
  3764. if (MemberInit.isInvalid())
  3765. return true;
  3766. // C++11 [class.base.init]p7:
  3767. // The initialization of each base and member constitutes a
  3768. // full-expression.
  3769. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3770. /*DiscardedValue*/ false);
  3771. if (MemberInit.isInvalid())
  3772. return true;
  3773. Init = MemberInit.get();
  3774. }
  3775. if (DirectMember) {
  3776. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3777. InitRange.getBegin(), Init,
  3778. InitRange.getEnd());
  3779. } else {
  3780. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3781. InitRange.getBegin(), Init,
  3782. InitRange.getEnd());
  3783. }
  3784. }
  3785. MemInitResult
  3786. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3787. CXXRecordDecl *ClassDecl) {
  3788. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3789. if (!LangOpts.CPlusPlus11)
  3790. return Diag(NameLoc, diag::err_delegating_ctor)
  3791. << TInfo->getTypeLoc().getLocalSourceRange();
  3792. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3793. bool InitList = true;
  3794. MultiExprArg Args = Init;
  3795. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3796. InitList = false;
  3797. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3798. }
  3799. SourceRange InitRange = Init->getSourceRange();
  3800. // Initialize the object.
  3801. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3802. QualType(ClassDecl->getTypeForDecl(), 0));
  3803. InitializationKind Kind =
  3804. InitList ? InitializationKind::CreateDirectList(
  3805. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3806. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3807. InitRange.getEnd());
  3808. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3809. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3810. Args, nullptr);
  3811. if (DelegationInit.isInvalid())
  3812. return true;
  3813. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3814. "Delegating constructor with no target?");
  3815. // C++11 [class.base.init]p7:
  3816. // The initialization of each base and member constitutes a
  3817. // full-expression.
  3818. DelegationInit = ActOnFinishFullExpr(
  3819. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  3820. if (DelegationInit.isInvalid())
  3821. return true;
  3822. // If we are in a dependent context, template instantiation will
  3823. // perform this type-checking again. Just save the arguments that we
  3824. // received in a ParenListExpr.
  3825. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3826. // of the information that we have about the base
  3827. // initializer. However, deconstructing the ASTs is a dicey process,
  3828. // and this approach is far more likely to get the corner cases right.
  3829. if (CurContext->isDependentContext())
  3830. DelegationInit = Init;
  3831. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3832. DelegationInit.getAs<Expr>(),
  3833. InitRange.getEnd());
  3834. }
  3835. MemInitResult
  3836. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3837. Expr *Init, CXXRecordDecl *ClassDecl,
  3838. SourceLocation EllipsisLoc) {
  3839. SourceLocation BaseLoc
  3840. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3841. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3842. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3843. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3844. // C++ [class.base.init]p2:
  3845. // [...] Unless the mem-initializer-id names a nonstatic data
  3846. // member of the constructor's class or a direct or virtual base
  3847. // of that class, the mem-initializer is ill-formed. A
  3848. // mem-initializer-list can initialize a base class using any
  3849. // name that denotes that base class type.
  3850. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3851. SourceRange InitRange = Init->getSourceRange();
  3852. if (EllipsisLoc.isValid()) {
  3853. // This is a pack expansion.
  3854. if (!BaseType->containsUnexpandedParameterPack()) {
  3855. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3856. << SourceRange(BaseLoc, InitRange.getEnd());
  3857. EllipsisLoc = SourceLocation();
  3858. }
  3859. } else {
  3860. // Check for any unexpanded parameter packs.
  3861. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3862. return true;
  3863. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3864. return true;
  3865. }
  3866. // Check for direct and virtual base classes.
  3867. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3868. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3869. if (!Dependent) {
  3870. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3871. BaseType))
  3872. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3873. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3874. VirtualBaseSpec);
  3875. // C++ [base.class.init]p2:
  3876. // Unless the mem-initializer-id names a nonstatic data member of the
  3877. // constructor's class or a direct or virtual base of that class, the
  3878. // mem-initializer is ill-formed.
  3879. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3880. // If the class has any dependent bases, then it's possible that
  3881. // one of those types will resolve to the same type as
  3882. // BaseType. Therefore, just treat this as a dependent base
  3883. // class initialization. FIXME: Should we try to check the
  3884. // initialization anyway? It seems odd.
  3885. if (ClassDecl->hasAnyDependentBases())
  3886. Dependent = true;
  3887. else
  3888. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3889. << BaseType << Context.getTypeDeclType(ClassDecl)
  3890. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3891. }
  3892. }
  3893. if (Dependent) {
  3894. DiscardCleanupsInEvaluationContext();
  3895. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3896. /*IsVirtual=*/false,
  3897. InitRange.getBegin(), Init,
  3898. InitRange.getEnd(), EllipsisLoc);
  3899. }
  3900. // C++ [base.class.init]p2:
  3901. // If a mem-initializer-id is ambiguous because it designates both
  3902. // a direct non-virtual base class and an inherited virtual base
  3903. // class, the mem-initializer is ill-formed.
  3904. if (DirectBaseSpec && VirtualBaseSpec)
  3905. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3906. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3907. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3908. if (!BaseSpec)
  3909. BaseSpec = VirtualBaseSpec;
  3910. // Initialize the base.
  3911. bool InitList = true;
  3912. MultiExprArg Args = Init;
  3913. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3914. InitList = false;
  3915. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3916. }
  3917. InitializedEntity BaseEntity =
  3918. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3919. InitializationKind Kind =
  3920. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3921. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3922. InitRange.getEnd());
  3923. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3924. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3925. if (BaseInit.isInvalid())
  3926. return true;
  3927. // C++11 [class.base.init]p7:
  3928. // The initialization of each base and member constitutes a
  3929. // full-expression.
  3930. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  3931. /*DiscardedValue*/ false);
  3932. if (BaseInit.isInvalid())
  3933. return true;
  3934. // If we are in a dependent context, template instantiation will
  3935. // perform this type-checking again. Just save the arguments that we
  3936. // received in a ParenListExpr.
  3937. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3938. // of the information that we have about the base
  3939. // initializer. However, deconstructing the ASTs is a dicey process,
  3940. // and this approach is far more likely to get the corner cases right.
  3941. if (CurContext->isDependentContext())
  3942. BaseInit = Init;
  3943. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3944. BaseSpec->isVirtual(),
  3945. InitRange.getBegin(),
  3946. BaseInit.getAs<Expr>(),
  3947. InitRange.getEnd(), EllipsisLoc);
  3948. }
  3949. // Create a static_cast\<T&&>(expr).
  3950. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3951. if (T.isNull()) T = E->getType();
  3952. QualType TargetType = SemaRef.BuildReferenceType(
  3953. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3954. SourceLocation ExprLoc = E->getBeginLoc();
  3955. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3956. TargetType, ExprLoc);
  3957. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3958. SourceRange(ExprLoc, ExprLoc),
  3959. E->getSourceRange()).get();
  3960. }
  3961. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3962. /// initialize its base or member.
  3963. enum ImplicitInitializerKind {
  3964. IIK_Default,
  3965. IIK_Copy,
  3966. IIK_Move,
  3967. IIK_Inherit
  3968. };
  3969. static bool
  3970. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3971. ImplicitInitializerKind ImplicitInitKind,
  3972. CXXBaseSpecifier *BaseSpec,
  3973. bool IsInheritedVirtualBase,
  3974. CXXCtorInitializer *&CXXBaseInit) {
  3975. InitializedEntity InitEntity
  3976. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3977. IsInheritedVirtualBase);
  3978. ExprResult BaseInit;
  3979. switch (ImplicitInitKind) {
  3980. case IIK_Inherit:
  3981. case IIK_Default: {
  3982. InitializationKind InitKind
  3983. = InitializationKind::CreateDefault(Constructor->getLocation());
  3984. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3985. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3986. break;
  3987. }
  3988. case IIK_Move:
  3989. case IIK_Copy: {
  3990. bool Moving = ImplicitInitKind == IIK_Move;
  3991. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3992. QualType ParamType = Param->getType().getNonReferenceType();
  3993. Expr *CopyCtorArg =
  3994. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3995. SourceLocation(), Param, false,
  3996. Constructor->getLocation(), ParamType,
  3997. VK_LValue, nullptr);
  3998. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3999. // Cast to the base class to avoid ambiguities.
  4000. QualType ArgTy =
  4001. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  4002. ParamType.getQualifiers());
  4003. if (Moving) {
  4004. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  4005. }
  4006. CXXCastPath BasePath;
  4007. BasePath.push_back(BaseSpec);
  4008. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  4009. CK_UncheckedDerivedToBase,
  4010. Moving ? VK_XValue : VK_LValue,
  4011. &BasePath).get();
  4012. InitializationKind InitKind
  4013. = InitializationKind::CreateDirect(Constructor->getLocation(),
  4014. SourceLocation(), SourceLocation());
  4015. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4016. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4017. break;
  4018. }
  4019. }
  4020. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  4021. if (BaseInit.isInvalid())
  4022. return true;
  4023. CXXBaseInit =
  4024. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4025. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  4026. SourceLocation()),
  4027. BaseSpec->isVirtual(),
  4028. SourceLocation(),
  4029. BaseInit.getAs<Expr>(),
  4030. SourceLocation(),
  4031. SourceLocation());
  4032. return false;
  4033. }
  4034. static bool RefersToRValueRef(Expr *MemRef) {
  4035. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  4036. return Referenced->getType()->isRValueReferenceType();
  4037. }
  4038. static bool
  4039. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4040. ImplicitInitializerKind ImplicitInitKind,
  4041. FieldDecl *Field, IndirectFieldDecl *Indirect,
  4042. CXXCtorInitializer *&CXXMemberInit) {
  4043. if (Field->isInvalidDecl())
  4044. return true;
  4045. SourceLocation Loc = Constructor->getLocation();
  4046. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  4047. bool Moving = ImplicitInitKind == IIK_Move;
  4048. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4049. QualType ParamType = Param->getType().getNonReferenceType();
  4050. // Suppress copying zero-width bitfields.
  4051. if (Field->isZeroLengthBitField(SemaRef.Context))
  4052. return false;
  4053. Expr *MemberExprBase =
  4054. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4055. SourceLocation(), Param, false,
  4056. Loc, ParamType, VK_LValue, nullptr);
  4057. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  4058. if (Moving) {
  4059. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  4060. }
  4061. // Build a reference to this field within the parameter.
  4062. CXXScopeSpec SS;
  4063. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  4064. Sema::LookupMemberName);
  4065. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  4066. : cast<ValueDecl>(Field), AS_public);
  4067. MemberLookup.resolveKind();
  4068. ExprResult CtorArg
  4069. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  4070. ParamType, Loc,
  4071. /*IsArrow=*/false,
  4072. SS,
  4073. /*TemplateKWLoc=*/SourceLocation(),
  4074. /*FirstQualifierInScope=*/nullptr,
  4075. MemberLookup,
  4076. /*TemplateArgs=*/nullptr,
  4077. /*S*/nullptr);
  4078. if (CtorArg.isInvalid())
  4079. return true;
  4080. // C++11 [class.copy]p15:
  4081. // - if a member m has rvalue reference type T&&, it is direct-initialized
  4082. // with static_cast<T&&>(x.m);
  4083. if (RefersToRValueRef(CtorArg.get())) {
  4084. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  4085. }
  4086. InitializedEntity Entity =
  4087. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4088. /*Implicit*/ true)
  4089. : InitializedEntity::InitializeMember(Field, nullptr,
  4090. /*Implicit*/ true);
  4091. // Direct-initialize to use the copy constructor.
  4092. InitializationKind InitKind =
  4093. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  4094. Expr *CtorArgE = CtorArg.getAs<Expr>();
  4095. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  4096. ExprResult MemberInit =
  4097. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  4098. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4099. if (MemberInit.isInvalid())
  4100. return true;
  4101. if (Indirect)
  4102. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4103. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4104. else
  4105. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4106. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4107. return false;
  4108. }
  4109. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  4110. "Unhandled implicit init kind!");
  4111. QualType FieldBaseElementType =
  4112. SemaRef.Context.getBaseElementType(Field->getType());
  4113. if (FieldBaseElementType->isRecordType()) {
  4114. InitializedEntity InitEntity =
  4115. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4116. /*Implicit*/ true)
  4117. : InitializedEntity::InitializeMember(Field, nullptr,
  4118. /*Implicit*/ true);
  4119. InitializationKind InitKind =
  4120. InitializationKind::CreateDefault(Loc);
  4121. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  4122. ExprResult MemberInit =
  4123. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  4124. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4125. if (MemberInit.isInvalid())
  4126. return true;
  4127. if (Indirect)
  4128. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4129. Indirect, Loc,
  4130. Loc,
  4131. MemberInit.get(),
  4132. Loc);
  4133. else
  4134. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4135. Field, Loc, Loc,
  4136. MemberInit.get(),
  4137. Loc);
  4138. return false;
  4139. }
  4140. if (!Field->getParent()->isUnion()) {
  4141. if (FieldBaseElementType->isReferenceType()) {
  4142. SemaRef.Diag(Constructor->getLocation(),
  4143. diag::err_uninitialized_member_in_ctor)
  4144. << (int)Constructor->isImplicit()
  4145. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4146. << 0 << Field->getDeclName();
  4147. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4148. return true;
  4149. }
  4150. if (FieldBaseElementType.isConstQualified()) {
  4151. SemaRef.Diag(Constructor->getLocation(),
  4152. diag::err_uninitialized_member_in_ctor)
  4153. << (int)Constructor->isImplicit()
  4154. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4155. << 1 << Field->getDeclName();
  4156. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4157. return true;
  4158. }
  4159. }
  4160. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  4161. // ARC and Weak:
  4162. // Default-initialize Objective-C pointers to NULL.
  4163. CXXMemberInit
  4164. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  4165. Loc, Loc,
  4166. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  4167. Loc);
  4168. return false;
  4169. }
  4170. // Nothing to initialize.
  4171. CXXMemberInit = nullptr;
  4172. return false;
  4173. }
  4174. namespace {
  4175. struct BaseAndFieldInfo {
  4176. Sema &S;
  4177. CXXConstructorDecl *Ctor;
  4178. bool AnyErrorsInInits;
  4179. ImplicitInitializerKind IIK;
  4180. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4181. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4182. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4183. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4184. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4185. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4186. if (Ctor->getInheritedConstructor())
  4187. IIK = IIK_Inherit;
  4188. else if (Generated && Ctor->isCopyConstructor())
  4189. IIK = IIK_Copy;
  4190. else if (Generated && Ctor->isMoveConstructor())
  4191. IIK = IIK_Move;
  4192. else
  4193. IIK = IIK_Default;
  4194. }
  4195. bool isImplicitCopyOrMove() const {
  4196. switch (IIK) {
  4197. case IIK_Copy:
  4198. case IIK_Move:
  4199. return true;
  4200. case IIK_Default:
  4201. case IIK_Inherit:
  4202. return false;
  4203. }
  4204. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4205. }
  4206. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4207. AllToInit.push_back(Init);
  4208. // Check whether this initializer makes the field "used".
  4209. if (Init->getInit()->HasSideEffects(S.Context))
  4210. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4211. return false;
  4212. }
  4213. bool isInactiveUnionMember(FieldDecl *Field) {
  4214. RecordDecl *Record = Field->getParent();
  4215. if (!Record->isUnion())
  4216. return false;
  4217. if (FieldDecl *Active =
  4218. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4219. return Active != Field->getCanonicalDecl();
  4220. // In an implicit copy or move constructor, ignore any in-class initializer.
  4221. if (isImplicitCopyOrMove())
  4222. return true;
  4223. // If there's no explicit initialization, the field is active only if it
  4224. // has an in-class initializer...
  4225. if (Field->hasInClassInitializer())
  4226. return false;
  4227. // ... or it's an anonymous struct or union whose class has an in-class
  4228. // initializer.
  4229. if (!Field->isAnonymousStructOrUnion())
  4230. return true;
  4231. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4232. return !FieldRD->hasInClassInitializer();
  4233. }
  4234. /// Determine whether the given field is, or is within, a union member
  4235. /// that is inactive (because there was an initializer given for a different
  4236. /// member of the union, or because the union was not initialized at all).
  4237. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4238. IndirectFieldDecl *Indirect) {
  4239. if (!Indirect)
  4240. return isInactiveUnionMember(Field);
  4241. for (auto *C : Indirect->chain()) {
  4242. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4243. if (Field && isInactiveUnionMember(Field))
  4244. return true;
  4245. }
  4246. return false;
  4247. }
  4248. };
  4249. }
  4250. /// Determine whether the given type is an incomplete or zero-lenfgth
  4251. /// array type.
  4252. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4253. if (T->isIncompleteArrayType())
  4254. return true;
  4255. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4256. if (!ArrayT->getSize())
  4257. return true;
  4258. T = ArrayT->getElementType();
  4259. }
  4260. return false;
  4261. }
  4262. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4263. FieldDecl *Field,
  4264. IndirectFieldDecl *Indirect = nullptr) {
  4265. if (Field->isInvalidDecl())
  4266. return false;
  4267. // Overwhelmingly common case: we have a direct initializer for this field.
  4268. if (CXXCtorInitializer *Init =
  4269. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4270. return Info.addFieldInitializer(Init);
  4271. // C++11 [class.base.init]p8:
  4272. // if the entity is a non-static data member that has a
  4273. // brace-or-equal-initializer and either
  4274. // -- the constructor's class is a union and no other variant member of that
  4275. // union is designated by a mem-initializer-id or
  4276. // -- the constructor's class is not a union, and, if the entity is a member
  4277. // of an anonymous union, no other member of that union is designated by
  4278. // a mem-initializer-id,
  4279. // the entity is initialized as specified in [dcl.init].
  4280. //
  4281. // We also apply the same rules to handle anonymous structs within anonymous
  4282. // unions.
  4283. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4284. return false;
  4285. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4286. ExprResult DIE =
  4287. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4288. if (DIE.isInvalid())
  4289. return true;
  4290. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4291. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4292. CXXCtorInitializer *Init;
  4293. if (Indirect)
  4294. Init = new (SemaRef.Context)
  4295. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4296. SourceLocation(), DIE.get(), SourceLocation());
  4297. else
  4298. Init = new (SemaRef.Context)
  4299. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4300. SourceLocation(), DIE.get(), SourceLocation());
  4301. return Info.addFieldInitializer(Init);
  4302. }
  4303. // Don't initialize incomplete or zero-length arrays.
  4304. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4305. return false;
  4306. // Don't try to build an implicit initializer if there were semantic
  4307. // errors in any of the initializers (and therefore we might be
  4308. // missing some that the user actually wrote).
  4309. if (Info.AnyErrorsInInits)
  4310. return false;
  4311. CXXCtorInitializer *Init = nullptr;
  4312. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4313. Indirect, Init))
  4314. return true;
  4315. if (!Init)
  4316. return false;
  4317. return Info.addFieldInitializer(Init);
  4318. }
  4319. bool
  4320. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4321. CXXCtorInitializer *Initializer) {
  4322. assert(Initializer->isDelegatingInitializer());
  4323. Constructor->setNumCtorInitializers(1);
  4324. CXXCtorInitializer **initializer =
  4325. new (Context) CXXCtorInitializer*[1];
  4326. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4327. Constructor->setCtorInitializers(initializer);
  4328. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4329. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4330. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4331. }
  4332. DelegatingCtorDecls.push_back(Constructor);
  4333. DiagnoseUninitializedFields(*this, Constructor);
  4334. return false;
  4335. }
  4336. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4337. ArrayRef<CXXCtorInitializer *> Initializers) {
  4338. if (Constructor->isDependentContext()) {
  4339. // Just store the initializers as written, they will be checked during
  4340. // instantiation.
  4341. if (!Initializers.empty()) {
  4342. Constructor->setNumCtorInitializers(Initializers.size());
  4343. CXXCtorInitializer **baseOrMemberInitializers =
  4344. new (Context) CXXCtorInitializer*[Initializers.size()];
  4345. memcpy(baseOrMemberInitializers, Initializers.data(),
  4346. Initializers.size() * sizeof(CXXCtorInitializer*));
  4347. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4348. }
  4349. // Let template instantiation know whether we had errors.
  4350. if (AnyErrors)
  4351. Constructor->setInvalidDecl();
  4352. return false;
  4353. }
  4354. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4355. // We need to build the initializer AST according to order of construction
  4356. // and not what user specified in the Initializers list.
  4357. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4358. if (!ClassDecl)
  4359. return true;
  4360. bool HadError = false;
  4361. for (unsigned i = 0; i < Initializers.size(); i++) {
  4362. CXXCtorInitializer *Member = Initializers[i];
  4363. if (Member->isBaseInitializer())
  4364. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4365. else {
  4366. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4367. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4368. for (auto *C : F->chain()) {
  4369. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4370. if (FD && FD->getParent()->isUnion())
  4371. Info.ActiveUnionMember.insert(std::make_pair(
  4372. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4373. }
  4374. } else if (FieldDecl *FD = Member->getMember()) {
  4375. if (FD->getParent()->isUnion())
  4376. Info.ActiveUnionMember.insert(std::make_pair(
  4377. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4378. }
  4379. }
  4380. }
  4381. // Keep track of the direct virtual bases.
  4382. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4383. for (auto &I : ClassDecl->bases()) {
  4384. if (I.isVirtual())
  4385. DirectVBases.insert(&I);
  4386. }
  4387. // Push virtual bases before others.
  4388. for (auto &VBase : ClassDecl->vbases()) {
  4389. if (CXXCtorInitializer *Value
  4390. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4391. // [class.base.init]p7, per DR257:
  4392. // A mem-initializer where the mem-initializer-id names a virtual base
  4393. // class is ignored during execution of a constructor of any class that
  4394. // is not the most derived class.
  4395. if (ClassDecl->isAbstract()) {
  4396. // FIXME: Provide a fixit to remove the base specifier. This requires
  4397. // tracking the location of the associated comma for a base specifier.
  4398. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4399. << VBase.getType() << ClassDecl;
  4400. DiagnoseAbstractType(ClassDecl);
  4401. }
  4402. Info.AllToInit.push_back(Value);
  4403. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4404. // [class.base.init]p8, per DR257:
  4405. // If a given [...] base class is not named by a mem-initializer-id
  4406. // [...] and the entity is not a virtual base class of an abstract
  4407. // class, then [...] the entity is default-initialized.
  4408. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4409. CXXCtorInitializer *CXXBaseInit;
  4410. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4411. &VBase, IsInheritedVirtualBase,
  4412. CXXBaseInit)) {
  4413. HadError = true;
  4414. continue;
  4415. }
  4416. Info.AllToInit.push_back(CXXBaseInit);
  4417. }
  4418. }
  4419. // Non-virtual bases.
  4420. for (auto &Base : ClassDecl->bases()) {
  4421. // Virtuals are in the virtual base list and already constructed.
  4422. if (Base.isVirtual())
  4423. continue;
  4424. if (CXXCtorInitializer *Value
  4425. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4426. Info.AllToInit.push_back(Value);
  4427. } else if (!AnyErrors) {
  4428. CXXCtorInitializer *CXXBaseInit;
  4429. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4430. &Base, /*IsInheritedVirtualBase=*/false,
  4431. CXXBaseInit)) {
  4432. HadError = true;
  4433. continue;
  4434. }
  4435. Info.AllToInit.push_back(CXXBaseInit);
  4436. }
  4437. }
  4438. // Fields.
  4439. for (auto *Mem : ClassDecl->decls()) {
  4440. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4441. // C++ [class.bit]p2:
  4442. // A declaration for a bit-field that omits the identifier declares an
  4443. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4444. // initialized.
  4445. if (F->isUnnamedBitfield())
  4446. continue;
  4447. // If we're not generating the implicit copy/move constructor, then we'll
  4448. // handle anonymous struct/union fields based on their individual
  4449. // indirect fields.
  4450. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4451. continue;
  4452. if (CollectFieldInitializer(*this, Info, F))
  4453. HadError = true;
  4454. continue;
  4455. }
  4456. // Beyond this point, we only consider default initialization.
  4457. if (Info.isImplicitCopyOrMove())
  4458. continue;
  4459. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4460. if (F->getType()->isIncompleteArrayType()) {
  4461. assert(ClassDecl->hasFlexibleArrayMember() &&
  4462. "Incomplete array type is not valid");
  4463. continue;
  4464. }
  4465. // Initialize each field of an anonymous struct individually.
  4466. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4467. HadError = true;
  4468. continue;
  4469. }
  4470. }
  4471. unsigned NumInitializers = Info.AllToInit.size();
  4472. if (NumInitializers > 0) {
  4473. Constructor->setNumCtorInitializers(NumInitializers);
  4474. CXXCtorInitializer **baseOrMemberInitializers =
  4475. new (Context) CXXCtorInitializer*[NumInitializers];
  4476. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4477. NumInitializers * sizeof(CXXCtorInitializer*));
  4478. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4479. // Constructors implicitly reference the base and member
  4480. // destructors.
  4481. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4482. Constructor->getParent());
  4483. }
  4484. return HadError;
  4485. }
  4486. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4487. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4488. const RecordDecl *RD = RT->getDecl();
  4489. if (RD->isAnonymousStructOrUnion()) {
  4490. for (auto *Field : RD->fields())
  4491. PopulateKeysForFields(Field, IdealInits);
  4492. return;
  4493. }
  4494. }
  4495. IdealInits.push_back(Field->getCanonicalDecl());
  4496. }
  4497. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4498. return Context.getCanonicalType(BaseType).getTypePtr();
  4499. }
  4500. static const void *GetKeyForMember(ASTContext &Context,
  4501. CXXCtorInitializer *Member) {
  4502. if (!Member->isAnyMemberInitializer())
  4503. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4504. return Member->getAnyMember()->getCanonicalDecl();
  4505. }
  4506. static void DiagnoseBaseOrMemInitializerOrder(
  4507. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4508. ArrayRef<CXXCtorInitializer *> Inits) {
  4509. if (Constructor->getDeclContext()->isDependentContext())
  4510. return;
  4511. // Don't check initializers order unless the warning is enabled at the
  4512. // location of at least one initializer.
  4513. bool ShouldCheckOrder = false;
  4514. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4515. CXXCtorInitializer *Init = Inits[InitIndex];
  4516. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4517. Init->getSourceLocation())) {
  4518. ShouldCheckOrder = true;
  4519. break;
  4520. }
  4521. }
  4522. if (!ShouldCheckOrder)
  4523. return;
  4524. // Build the list of bases and members in the order that they'll
  4525. // actually be initialized. The explicit initializers should be in
  4526. // this same order but may be missing things.
  4527. SmallVector<const void*, 32> IdealInitKeys;
  4528. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4529. // 1. Virtual bases.
  4530. for (const auto &VBase : ClassDecl->vbases())
  4531. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4532. // 2. Non-virtual bases.
  4533. for (const auto &Base : ClassDecl->bases()) {
  4534. if (Base.isVirtual())
  4535. continue;
  4536. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4537. }
  4538. // 3. Direct fields.
  4539. for (auto *Field : ClassDecl->fields()) {
  4540. if (Field->isUnnamedBitfield())
  4541. continue;
  4542. PopulateKeysForFields(Field, IdealInitKeys);
  4543. }
  4544. unsigned NumIdealInits = IdealInitKeys.size();
  4545. unsigned IdealIndex = 0;
  4546. CXXCtorInitializer *PrevInit = nullptr;
  4547. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4548. CXXCtorInitializer *Init = Inits[InitIndex];
  4549. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4550. // Scan forward to try to find this initializer in the idealized
  4551. // initializers list.
  4552. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4553. if (InitKey == IdealInitKeys[IdealIndex])
  4554. break;
  4555. // If we didn't find this initializer, it must be because we
  4556. // scanned past it on a previous iteration. That can only
  4557. // happen if we're out of order; emit a warning.
  4558. if (IdealIndex == NumIdealInits && PrevInit) {
  4559. Sema::SemaDiagnosticBuilder D =
  4560. SemaRef.Diag(PrevInit->getSourceLocation(),
  4561. diag::warn_initializer_out_of_order);
  4562. if (PrevInit->isAnyMemberInitializer())
  4563. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4564. else
  4565. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4566. if (Init->isAnyMemberInitializer())
  4567. D << 0 << Init->getAnyMember()->getDeclName();
  4568. else
  4569. D << 1 << Init->getTypeSourceInfo()->getType();
  4570. // Move back to the initializer's location in the ideal list.
  4571. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4572. if (InitKey == IdealInitKeys[IdealIndex])
  4573. break;
  4574. assert(IdealIndex < NumIdealInits &&
  4575. "initializer not found in initializer list");
  4576. }
  4577. PrevInit = Init;
  4578. }
  4579. }
  4580. namespace {
  4581. bool CheckRedundantInit(Sema &S,
  4582. CXXCtorInitializer *Init,
  4583. CXXCtorInitializer *&PrevInit) {
  4584. if (!PrevInit) {
  4585. PrevInit = Init;
  4586. return false;
  4587. }
  4588. if (FieldDecl *Field = Init->getAnyMember())
  4589. S.Diag(Init->getSourceLocation(),
  4590. diag::err_multiple_mem_initialization)
  4591. << Field->getDeclName()
  4592. << Init->getSourceRange();
  4593. else {
  4594. const Type *BaseClass = Init->getBaseClass();
  4595. assert(BaseClass && "neither field nor base");
  4596. S.Diag(Init->getSourceLocation(),
  4597. diag::err_multiple_base_initialization)
  4598. << QualType(BaseClass, 0)
  4599. << Init->getSourceRange();
  4600. }
  4601. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4602. << 0 << PrevInit->getSourceRange();
  4603. return true;
  4604. }
  4605. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4606. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4607. bool CheckRedundantUnionInit(Sema &S,
  4608. CXXCtorInitializer *Init,
  4609. RedundantUnionMap &Unions) {
  4610. FieldDecl *Field = Init->getAnyMember();
  4611. RecordDecl *Parent = Field->getParent();
  4612. NamedDecl *Child = Field;
  4613. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4614. if (Parent->isUnion()) {
  4615. UnionEntry &En = Unions[Parent];
  4616. if (En.first && En.first != Child) {
  4617. S.Diag(Init->getSourceLocation(),
  4618. diag::err_multiple_mem_union_initialization)
  4619. << Field->getDeclName()
  4620. << Init->getSourceRange();
  4621. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4622. << 0 << En.second->getSourceRange();
  4623. return true;
  4624. }
  4625. if (!En.first) {
  4626. En.first = Child;
  4627. En.second = Init;
  4628. }
  4629. if (!Parent->isAnonymousStructOrUnion())
  4630. return false;
  4631. }
  4632. Child = Parent;
  4633. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4634. }
  4635. return false;
  4636. }
  4637. }
  4638. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4639. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4640. SourceLocation ColonLoc,
  4641. ArrayRef<CXXCtorInitializer*> MemInits,
  4642. bool AnyErrors) {
  4643. if (!ConstructorDecl)
  4644. return;
  4645. AdjustDeclIfTemplate(ConstructorDecl);
  4646. CXXConstructorDecl *Constructor
  4647. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4648. if (!Constructor) {
  4649. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4650. return;
  4651. }
  4652. // Mapping for the duplicate initializers check.
  4653. // For member initializers, this is keyed with a FieldDecl*.
  4654. // For base initializers, this is keyed with a Type*.
  4655. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4656. // Mapping for the inconsistent anonymous-union initializers check.
  4657. RedundantUnionMap MemberUnions;
  4658. bool HadError = false;
  4659. for (unsigned i = 0; i < MemInits.size(); i++) {
  4660. CXXCtorInitializer *Init = MemInits[i];
  4661. // Set the source order index.
  4662. Init->setSourceOrder(i);
  4663. if (Init->isAnyMemberInitializer()) {
  4664. const void *Key = GetKeyForMember(Context, Init);
  4665. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4666. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4667. HadError = true;
  4668. } else if (Init->isBaseInitializer()) {
  4669. const void *Key = GetKeyForMember(Context, Init);
  4670. if (CheckRedundantInit(*this, Init, Members[Key]))
  4671. HadError = true;
  4672. } else {
  4673. assert(Init->isDelegatingInitializer());
  4674. // This must be the only initializer
  4675. if (MemInits.size() != 1) {
  4676. Diag(Init->getSourceLocation(),
  4677. diag::err_delegating_initializer_alone)
  4678. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4679. // We will treat this as being the only initializer.
  4680. }
  4681. SetDelegatingInitializer(Constructor, MemInits[i]);
  4682. // Return immediately as the initializer is set.
  4683. return;
  4684. }
  4685. }
  4686. if (HadError)
  4687. return;
  4688. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4689. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4690. DiagnoseUninitializedFields(*this, Constructor);
  4691. }
  4692. void
  4693. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4694. CXXRecordDecl *ClassDecl) {
  4695. // Ignore dependent contexts. Also ignore unions, since their members never
  4696. // have destructors implicitly called.
  4697. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4698. return;
  4699. // FIXME: all the access-control diagnostics are positioned on the
  4700. // field/base declaration. That's probably good; that said, the
  4701. // user might reasonably want to know why the destructor is being
  4702. // emitted, and we currently don't say.
  4703. // Non-static data members.
  4704. for (auto *Field : ClassDecl->fields()) {
  4705. if (Field->isInvalidDecl())
  4706. continue;
  4707. // Don't destroy incomplete or zero-length arrays.
  4708. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4709. continue;
  4710. QualType FieldType = Context.getBaseElementType(Field->getType());
  4711. const RecordType* RT = FieldType->getAs<RecordType>();
  4712. if (!RT)
  4713. continue;
  4714. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4715. if (FieldClassDecl->isInvalidDecl())
  4716. continue;
  4717. if (FieldClassDecl->hasIrrelevantDestructor())
  4718. continue;
  4719. // The destructor for an implicit anonymous union member is never invoked.
  4720. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4721. continue;
  4722. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4723. assert(Dtor && "No dtor found for FieldClassDecl!");
  4724. CheckDestructorAccess(Field->getLocation(), Dtor,
  4725. PDiag(diag::err_access_dtor_field)
  4726. << Field->getDeclName()
  4727. << FieldType);
  4728. MarkFunctionReferenced(Location, Dtor);
  4729. DiagnoseUseOfDecl(Dtor, Location);
  4730. }
  4731. // We only potentially invoke the destructors of potentially constructed
  4732. // subobjects.
  4733. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4734. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4735. // Bases.
  4736. for (const auto &Base : ClassDecl->bases()) {
  4737. // Bases are always records in a well-formed non-dependent class.
  4738. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4739. // Remember direct virtual bases.
  4740. if (Base.isVirtual()) {
  4741. if (!VisitVirtualBases)
  4742. continue;
  4743. DirectVirtualBases.insert(RT);
  4744. }
  4745. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4746. // If our base class is invalid, we probably can't get its dtor anyway.
  4747. if (BaseClassDecl->isInvalidDecl())
  4748. continue;
  4749. if (BaseClassDecl->hasIrrelevantDestructor())
  4750. continue;
  4751. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4752. assert(Dtor && "No dtor found for BaseClassDecl!");
  4753. // FIXME: caret should be on the start of the class name
  4754. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4755. PDiag(diag::err_access_dtor_base)
  4756. << Base.getType() << Base.getSourceRange(),
  4757. Context.getTypeDeclType(ClassDecl));
  4758. MarkFunctionReferenced(Location, Dtor);
  4759. DiagnoseUseOfDecl(Dtor, Location);
  4760. }
  4761. if (!VisitVirtualBases)
  4762. return;
  4763. // Virtual bases.
  4764. for (const auto &VBase : ClassDecl->vbases()) {
  4765. // Bases are always records in a well-formed non-dependent class.
  4766. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4767. // Ignore direct virtual bases.
  4768. if (DirectVirtualBases.count(RT))
  4769. continue;
  4770. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4771. // If our base class is invalid, we probably can't get its dtor anyway.
  4772. if (BaseClassDecl->isInvalidDecl())
  4773. continue;
  4774. if (BaseClassDecl->hasIrrelevantDestructor())
  4775. continue;
  4776. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4777. assert(Dtor && "No dtor found for BaseClassDecl!");
  4778. if (CheckDestructorAccess(
  4779. ClassDecl->getLocation(), Dtor,
  4780. PDiag(diag::err_access_dtor_vbase)
  4781. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4782. Context.getTypeDeclType(ClassDecl)) ==
  4783. AR_accessible) {
  4784. CheckDerivedToBaseConversion(
  4785. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4786. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4787. SourceRange(), DeclarationName(), nullptr);
  4788. }
  4789. MarkFunctionReferenced(Location, Dtor);
  4790. DiagnoseUseOfDecl(Dtor, Location);
  4791. }
  4792. }
  4793. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4794. if (!CDtorDecl)
  4795. return;
  4796. if (CXXConstructorDecl *Constructor
  4797. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4798. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4799. DiagnoseUninitializedFields(*this, Constructor);
  4800. }
  4801. }
  4802. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4803. if (!getLangOpts().CPlusPlus)
  4804. return false;
  4805. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4806. if (!RD)
  4807. return false;
  4808. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4809. // class template specialization here, but doing so breaks a lot of code.
  4810. // We can't answer whether something is abstract until it has a
  4811. // definition. If it's currently being defined, we'll walk back
  4812. // over all the declarations when we have a full definition.
  4813. const CXXRecordDecl *Def = RD->getDefinition();
  4814. if (!Def || Def->isBeingDefined())
  4815. return false;
  4816. return RD->isAbstract();
  4817. }
  4818. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4819. TypeDiagnoser &Diagnoser) {
  4820. if (!isAbstractType(Loc, T))
  4821. return false;
  4822. T = Context.getBaseElementType(T);
  4823. Diagnoser.diagnose(*this, Loc, T);
  4824. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4825. return true;
  4826. }
  4827. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4828. // Check if we've already emitted the list of pure virtual functions
  4829. // for this class.
  4830. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4831. return;
  4832. // If the diagnostic is suppressed, don't emit the notes. We're only
  4833. // going to emit them once, so try to attach them to a diagnostic we're
  4834. // actually going to show.
  4835. if (Diags.isLastDiagnosticIgnored())
  4836. return;
  4837. CXXFinalOverriderMap FinalOverriders;
  4838. RD->getFinalOverriders(FinalOverriders);
  4839. // Keep a set of seen pure methods so we won't diagnose the same method
  4840. // more than once.
  4841. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4842. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4843. MEnd = FinalOverriders.end();
  4844. M != MEnd;
  4845. ++M) {
  4846. for (OverridingMethods::iterator SO = M->second.begin(),
  4847. SOEnd = M->second.end();
  4848. SO != SOEnd; ++SO) {
  4849. // C++ [class.abstract]p4:
  4850. // A class is abstract if it contains or inherits at least one
  4851. // pure virtual function for which the final overrider is pure
  4852. // virtual.
  4853. //
  4854. if (SO->second.size() != 1)
  4855. continue;
  4856. if (!SO->second.front().Method->isPure())
  4857. continue;
  4858. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4859. continue;
  4860. Diag(SO->second.front().Method->getLocation(),
  4861. diag::note_pure_virtual_function)
  4862. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4863. }
  4864. }
  4865. if (!PureVirtualClassDiagSet)
  4866. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4867. PureVirtualClassDiagSet->insert(RD);
  4868. }
  4869. namespace {
  4870. struct AbstractUsageInfo {
  4871. Sema &S;
  4872. CXXRecordDecl *Record;
  4873. CanQualType AbstractType;
  4874. bool Invalid;
  4875. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4876. : S(S), Record(Record),
  4877. AbstractType(S.Context.getCanonicalType(
  4878. S.Context.getTypeDeclType(Record))),
  4879. Invalid(false) {}
  4880. void DiagnoseAbstractType() {
  4881. if (Invalid) return;
  4882. S.DiagnoseAbstractType(Record);
  4883. Invalid = true;
  4884. }
  4885. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4886. };
  4887. struct CheckAbstractUsage {
  4888. AbstractUsageInfo &Info;
  4889. const NamedDecl *Ctx;
  4890. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4891. : Info(Info), Ctx(Ctx) {}
  4892. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4893. switch (TL.getTypeLocClass()) {
  4894. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4895. #define TYPELOC(CLASS, PARENT) \
  4896. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4897. #include "clang/AST/TypeLocNodes.def"
  4898. }
  4899. }
  4900. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4901. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4902. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4903. if (!TL.getParam(I))
  4904. continue;
  4905. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4906. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4907. }
  4908. }
  4909. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4910. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4911. }
  4912. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4913. // Visit the type parameters from a permissive context.
  4914. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4915. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4916. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4917. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4918. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4919. // TODO: other template argument types?
  4920. }
  4921. }
  4922. // Visit pointee types from a permissive context.
  4923. #define CheckPolymorphic(Type) \
  4924. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4925. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4926. }
  4927. CheckPolymorphic(PointerTypeLoc)
  4928. CheckPolymorphic(ReferenceTypeLoc)
  4929. CheckPolymorphic(MemberPointerTypeLoc)
  4930. CheckPolymorphic(BlockPointerTypeLoc)
  4931. CheckPolymorphic(AtomicTypeLoc)
  4932. /// Handle all the types we haven't given a more specific
  4933. /// implementation for above.
  4934. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4935. // Every other kind of type that we haven't called out already
  4936. // that has an inner type is either (1) sugar or (2) contains that
  4937. // inner type in some way as a subobject.
  4938. if (TypeLoc Next = TL.getNextTypeLoc())
  4939. return Visit(Next, Sel);
  4940. // If there's no inner type and we're in a permissive context,
  4941. // don't diagnose.
  4942. if (Sel == Sema::AbstractNone) return;
  4943. // Check whether the type matches the abstract type.
  4944. QualType T = TL.getType();
  4945. if (T->isArrayType()) {
  4946. Sel = Sema::AbstractArrayType;
  4947. T = Info.S.Context.getBaseElementType(T);
  4948. }
  4949. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4950. if (CT != Info.AbstractType) return;
  4951. // It matched; do some magic.
  4952. if (Sel == Sema::AbstractArrayType) {
  4953. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4954. << T << TL.getSourceRange();
  4955. } else {
  4956. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4957. << Sel << T << TL.getSourceRange();
  4958. }
  4959. Info.DiagnoseAbstractType();
  4960. }
  4961. };
  4962. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4963. Sema::AbstractDiagSelID Sel) {
  4964. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4965. }
  4966. }
  4967. /// Check for invalid uses of an abstract type in a method declaration.
  4968. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4969. CXXMethodDecl *MD) {
  4970. // No need to do the check on definitions, which require that
  4971. // the return/param types be complete.
  4972. if (MD->doesThisDeclarationHaveABody())
  4973. return;
  4974. // For safety's sake, just ignore it if we don't have type source
  4975. // information. This should never happen for non-implicit methods,
  4976. // but...
  4977. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4978. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4979. }
  4980. /// Check for invalid uses of an abstract type within a class definition.
  4981. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4982. CXXRecordDecl *RD) {
  4983. for (auto *D : RD->decls()) {
  4984. if (D->isImplicit()) continue;
  4985. // Methods and method templates.
  4986. if (isa<CXXMethodDecl>(D)) {
  4987. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4988. } else if (isa<FunctionTemplateDecl>(D)) {
  4989. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4990. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4991. // Fields and static variables.
  4992. } else if (isa<FieldDecl>(D)) {
  4993. FieldDecl *FD = cast<FieldDecl>(D);
  4994. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4995. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4996. } else if (isa<VarDecl>(D)) {
  4997. VarDecl *VD = cast<VarDecl>(D);
  4998. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4999. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  5000. // Nested classes and class templates.
  5001. } else if (isa<CXXRecordDecl>(D)) {
  5002. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  5003. } else if (isa<ClassTemplateDecl>(D)) {
  5004. CheckAbstractClassUsage(Info,
  5005. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  5006. }
  5007. }
  5008. }
  5009. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  5010. Attr *ClassAttr = getDLLAttr(Class);
  5011. if (!ClassAttr)
  5012. return;
  5013. assert(ClassAttr->getKind() == attr::DLLExport);
  5014. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5015. if (TSK == TSK_ExplicitInstantiationDeclaration)
  5016. // Don't go any further if this is just an explicit instantiation
  5017. // declaration.
  5018. return;
  5019. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  5020. S.MarkVTableUsed(Class->getLocation(), Class, true);
  5021. for (Decl *Member : Class->decls()) {
  5022. // Defined static variables that are members of an exported base
  5023. // class must be marked export too.
  5024. auto *VD = dyn_cast<VarDecl>(Member);
  5025. if (VD && Member->getAttr<DLLExportAttr>() &&
  5026. VD->getStorageClass() == SC_Static &&
  5027. TSK == TSK_ImplicitInstantiation)
  5028. S.MarkVariableReferenced(VD->getLocation(), VD);
  5029. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  5030. if (!MD)
  5031. continue;
  5032. if (Member->getAttr<DLLExportAttr>()) {
  5033. if (MD->isUserProvided()) {
  5034. // Instantiate non-default class member functions ...
  5035. // .. except for certain kinds of template specializations.
  5036. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  5037. continue;
  5038. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5039. // The function will be passed to the consumer when its definition is
  5040. // encountered.
  5041. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  5042. MD->isCopyAssignmentOperator() ||
  5043. MD->isMoveAssignmentOperator()) {
  5044. // Synthesize and instantiate non-trivial implicit methods, explicitly
  5045. // defaulted methods, and the copy and move assignment operators. The
  5046. // latter are exported even if they are trivial, because the address of
  5047. // an operator can be taken and should compare equal across libraries.
  5048. DiagnosticErrorTrap Trap(S.Diags);
  5049. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5050. if (Trap.hasErrorOccurred()) {
  5051. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  5052. << Class << !S.getLangOpts().CPlusPlus11;
  5053. break;
  5054. }
  5055. // There is no later point when we will see the definition of this
  5056. // function, so pass it to the consumer now.
  5057. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5058. }
  5059. }
  5060. }
  5061. }
  5062. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  5063. CXXRecordDecl *Class) {
  5064. // Only the MS ABI has default constructor closures, so we don't need to do
  5065. // this semantic checking anywhere else.
  5066. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  5067. return;
  5068. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  5069. for (Decl *Member : Class->decls()) {
  5070. // Look for exported default constructors.
  5071. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  5072. if (!CD || !CD->isDefaultConstructor())
  5073. continue;
  5074. auto *Attr = CD->getAttr<DLLExportAttr>();
  5075. if (!Attr)
  5076. continue;
  5077. // If the class is non-dependent, mark the default arguments as ODR-used so
  5078. // that we can properly codegen the constructor closure.
  5079. if (!Class->isDependentContext()) {
  5080. for (ParmVarDecl *PD : CD->parameters()) {
  5081. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  5082. S.DiscardCleanupsInEvaluationContext();
  5083. }
  5084. }
  5085. if (LastExportedDefaultCtor) {
  5086. S.Diag(LastExportedDefaultCtor->getLocation(),
  5087. diag::err_attribute_dll_ambiguous_default_ctor)
  5088. << Class;
  5089. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  5090. << CD->getDeclName();
  5091. return;
  5092. }
  5093. LastExportedDefaultCtor = CD;
  5094. }
  5095. }
  5096. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  5097. // Mark any compiler-generated routines with the implicit code_seg attribute.
  5098. for (auto *Method : Class->methods()) {
  5099. if (Method->isUserProvided())
  5100. continue;
  5101. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  5102. Method->addAttr(A);
  5103. }
  5104. }
  5105. /// Check class-level dllimport/dllexport attribute.
  5106. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  5107. Attr *ClassAttr = getDLLAttr(Class);
  5108. // MSVC inherits DLL attributes to partial class template specializations.
  5109. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  5110. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  5111. if (Attr *TemplateAttr =
  5112. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  5113. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  5114. A->setInherited(true);
  5115. ClassAttr = A;
  5116. }
  5117. }
  5118. }
  5119. if (!ClassAttr)
  5120. return;
  5121. if (!Class->isExternallyVisible()) {
  5122. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  5123. << Class << ClassAttr;
  5124. return;
  5125. }
  5126. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5127. !ClassAttr->isInherited()) {
  5128. // Diagnose dll attributes on members of class with dll attribute.
  5129. for (Decl *Member : Class->decls()) {
  5130. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  5131. continue;
  5132. InheritableAttr *MemberAttr = getDLLAttr(Member);
  5133. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  5134. continue;
  5135. Diag(MemberAttr->getLocation(),
  5136. diag::err_attribute_dll_member_of_dll_class)
  5137. << MemberAttr << ClassAttr;
  5138. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  5139. Member->setInvalidDecl();
  5140. }
  5141. }
  5142. if (Class->getDescribedClassTemplate())
  5143. // Don't inherit dll attribute until the template is instantiated.
  5144. return;
  5145. // The class is either imported or exported.
  5146. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  5147. // Check if this was a dllimport attribute propagated from a derived class to
  5148. // a base class template specialization. We don't apply these attributes to
  5149. // static data members.
  5150. const bool PropagatedImport =
  5151. !ClassExported &&
  5152. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  5153. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5154. // Ignore explicit dllexport on explicit class template instantiation
  5155. // declarations, except in MinGW mode.
  5156. if (ClassExported && !ClassAttr->isInherited() &&
  5157. TSK == TSK_ExplicitInstantiationDeclaration &&
  5158. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  5159. Class->dropAttr<DLLExportAttr>();
  5160. return;
  5161. }
  5162. // Force declaration of implicit members so they can inherit the attribute.
  5163. ForceDeclarationOfImplicitMembers(Class);
  5164. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  5165. // seem to be true in practice?
  5166. for (Decl *Member : Class->decls()) {
  5167. VarDecl *VD = dyn_cast<VarDecl>(Member);
  5168. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5169. // Only methods and static fields inherit the attributes.
  5170. if (!VD && !MD)
  5171. continue;
  5172. if (MD) {
  5173. // Don't process deleted methods.
  5174. if (MD->isDeleted())
  5175. continue;
  5176. if (MD->isInlined()) {
  5177. // MinGW does not import or export inline methods. But do it for
  5178. // template instantiations.
  5179. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5180. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
  5181. TSK != TSK_ExplicitInstantiationDeclaration &&
  5182. TSK != TSK_ExplicitInstantiationDefinition)
  5183. continue;
  5184. // MSVC versions before 2015 don't export the move assignment operators
  5185. // and move constructor, so don't attempt to import/export them if
  5186. // we have a definition.
  5187. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5188. if ((MD->isMoveAssignmentOperator() ||
  5189. (Ctor && Ctor->isMoveConstructor())) &&
  5190. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5191. continue;
  5192. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5193. // operator is exported anyway.
  5194. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5195. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5196. continue;
  5197. }
  5198. }
  5199. // Don't apply dllimport attributes to static data members of class template
  5200. // instantiations when the attribute is propagated from a derived class.
  5201. if (VD && PropagatedImport)
  5202. continue;
  5203. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5204. continue;
  5205. if (!getDLLAttr(Member)) {
  5206. InheritableAttr *NewAttr = nullptr;
  5207. // Do not export/import inline function when -fno-dllexport-inlines is
  5208. // passed. But add attribute for later local static var check.
  5209. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5210. TSK != TSK_ExplicitInstantiationDeclaration &&
  5211. TSK != TSK_ExplicitInstantiationDefinition) {
  5212. if (ClassExported) {
  5213. NewAttr = ::new (getASTContext())
  5214. DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
  5215. } else {
  5216. NewAttr = ::new (getASTContext())
  5217. DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
  5218. }
  5219. } else {
  5220. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5221. }
  5222. NewAttr->setInherited(true);
  5223. Member->addAttr(NewAttr);
  5224. if (MD) {
  5225. // Propagate DLLAttr to friend re-declarations of MD that have already
  5226. // been constructed.
  5227. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5228. FD = FD->getPreviousDecl()) {
  5229. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5230. continue;
  5231. assert(!getDLLAttr(FD) &&
  5232. "friend re-decl should not already have a DLLAttr");
  5233. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5234. NewAttr->setInherited(true);
  5235. FD->addAttr(NewAttr);
  5236. }
  5237. }
  5238. }
  5239. }
  5240. if (ClassExported)
  5241. DelayedDllExportClasses.push_back(Class);
  5242. }
  5243. /// Perform propagation of DLL attributes from a derived class to a
  5244. /// templated base class for MS compatibility.
  5245. void Sema::propagateDLLAttrToBaseClassTemplate(
  5246. CXXRecordDecl *Class, Attr *ClassAttr,
  5247. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5248. if (getDLLAttr(
  5249. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5250. // If the base class template has a DLL attribute, don't try to change it.
  5251. return;
  5252. }
  5253. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5254. if (!getDLLAttr(BaseTemplateSpec) &&
  5255. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5256. TSK == TSK_ImplicitInstantiation)) {
  5257. // The template hasn't been instantiated yet (or it has, but only as an
  5258. // explicit instantiation declaration or implicit instantiation, which means
  5259. // we haven't codegenned any members yet), so propagate the attribute.
  5260. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5261. NewAttr->setInherited(true);
  5262. BaseTemplateSpec->addAttr(NewAttr);
  5263. // If this was an import, mark that we propagated it from a derived class to
  5264. // a base class template specialization.
  5265. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5266. ImportAttr->setPropagatedToBaseTemplate();
  5267. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5268. // needs to be run again to work see the new attribute. Otherwise this will
  5269. // get run whenever the template is instantiated.
  5270. if (TSK != TSK_Undeclared)
  5271. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5272. return;
  5273. }
  5274. if (getDLLAttr(BaseTemplateSpec)) {
  5275. // The template has already been specialized or instantiated with an
  5276. // attribute, explicitly or through propagation. We should not try to change
  5277. // it.
  5278. return;
  5279. }
  5280. // The template was previously instantiated or explicitly specialized without
  5281. // a dll attribute, It's too late for us to add an attribute, so warn that
  5282. // this is unsupported.
  5283. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5284. << BaseTemplateSpec->isExplicitSpecialization();
  5285. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5286. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5287. Diag(BaseTemplateSpec->getLocation(),
  5288. diag::note_template_class_explicit_specialization_was_here)
  5289. << BaseTemplateSpec;
  5290. } else {
  5291. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5292. diag::note_template_class_instantiation_was_here)
  5293. << BaseTemplateSpec;
  5294. }
  5295. }
  5296. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5297. SourceLocation DefaultLoc) {
  5298. switch (S.getSpecialMember(MD)) {
  5299. case Sema::CXXDefaultConstructor:
  5300. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5301. cast<CXXConstructorDecl>(MD));
  5302. break;
  5303. case Sema::CXXCopyConstructor:
  5304. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5305. break;
  5306. case Sema::CXXCopyAssignment:
  5307. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5308. break;
  5309. case Sema::CXXDestructor:
  5310. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5311. break;
  5312. case Sema::CXXMoveConstructor:
  5313. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5314. break;
  5315. case Sema::CXXMoveAssignment:
  5316. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5317. break;
  5318. case Sema::CXXInvalid:
  5319. llvm_unreachable("Invalid special member.");
  5320. }
  5321. }
  5322. /// Determine whether a type is permitted to be passed or returned in
  5323. /// registers, per C++ [class.temporary]p3.
  5324. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5325. TargetInfo::CallingConvKind CCK) {
  5326. if (D->isDependentType() || D->isInvalidDecl())
  5327. return false;
  5328. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5329. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5330. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5331. return !D->hasNonTrivialDestructorForCall() &&
  5332. !D->hasNonTrivialCopyConstructorForCall();
  5333. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5334. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5335. bool DtorIsTrivialForCall = false;
  5336. // If a class has at least one non-deleted, trivial copy constructor, it
  5337. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5338. //
  5339. // Note: This permits classes with non-trivial copy or move ctors to be
  5340. // passed in registers, so long as they *also* have a trivial copy ctor,
  5341. // which is non-conforming.
  5342. if (D->needsImplicitCopyConstructor()) {
  5343. if (!D->defaultedCopyConstructorIsDeleted()) {
  5344. if (D->hasTrivialCopyConstructor())
  5345. CopyCtorIsTrivial = true;
  5346. if (D->hasTrivialCopyConstructorForCall())
  5347. CopyCtorIsTrivialForCall = true;
  5348. }
  5349. } else {
  5350. for (const CXXConstructorDecl *CD : D->ctors()) {
  5351. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5352. if (CD->isTrivial())
  5353. CopyCtorIsTrivial = true;
  5354. if (CD->isTrivialForCall())
  5355. CopyCtorIsTrivialForCall = true;
  5356. }
  5357. }
  5358. }
  5359. if (D->needsImplicitDestructor()) {
  5360. if (!D->defaultedDestructorIsDeleted() &&
  5361. D->hasTrivialDestructorForCall())
  5362. DtorIsTrivialForCall = true;
  5363. } else if (const auto *DD = D->getDestructor()) {
  5364. if (!DD->isDeleted() && DD->isTrivialForCall())
  5365. DtorIsTrivialForCall = true;
  5366. }
  5367. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5368. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5369. return true;
  5370. // If a class has a destructor, we'd really like to pass it indirectly
  5371. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5372. // impossible for small types, which it will pass in a single register or
  5373. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5374. // We can't call out all large objects as being indirect because there are
  5375. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5376. // how we pass large POD types.
  5377. // Note: This permits small classes with nontrivial destructors to be
  5378. // passed in registers, which is non-conforming.
  5379. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5380. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5381. if (CopyCtorIsTrivial &&
  5382. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5383. return true;
  5384. return false;
  5385. }
  5386. // Per C++ [class.temporary]p3, the relevant condition is:
  5387. // each copy constructor, move constructor, and destructor of X is
  5388. // either trivial or deleted, and X has at least one non-deleted copy
  5389. // or move constructor
  5390. bool HasNonDeletedCopyOrMove = false;
  5391. if (D->needsImplicitCopyConstructor() &&
  5392. !D->defaultedCopyConstructorIsDeleted()) {
  5393. if (!D->hasTrivialCopyConstructorForCall())
  5394. return false;
  5395. HasNonDeletedCopyOrMove = true;
  5396. }
  5397. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5398. !D->defaultedMoveConstructorIsDeleted()) {
  5399. if (!D->hasTrivialMoveConstructorForCall())
  5400. return false;
  5401. HasNonDeletedCopyOrMove = true;
  5402. }
  5403. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5404. !D->hasTrivialDestructorForCall())
  5405. return false;
  5406. for (const CXXMethodDecl *MD : D->methods()) {
  5407. if (MD->isDeleted())
  5408. continue;
  5409. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5410. if (CD && CD->isCopyOrMoveConstructor())
  5411. HasNonDeletedCopyOrMove = true;
  5412. else if (!isa<CXXDestructorDecl>(MD))
  5413. continue;
  5414. if (!MD->isTrivialForCall())
  5415. return false;
  5416. }
  5417. return HasNonDeletedCopyOrMove;
  5418. }
  5419. /// Perform semantic checks on a class definition that has been
  5420. /// completing, introducing implicitly-declared members, checking for
  5421. /// abstract types, etc.
  5422. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5423. if (!Record)
  5424. return;
  5425. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5426. AbstractUsageInfo Info(*this, Record);
  5427. CheckAbstractClassUsage(Info, Record);
  5428. }
  5429. // If this is not an aggregate type and has no user-declared constructor,
  5430. // complain about any non-static data members of reference or const scalar
  5431. // type, since they will never get initializers.
  5432. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5433. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5434. !Record->isLambda()) {
  5435. bool Complained = false;
  5436. for (const auto *F : Record->fields()) {
  5437. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5438. continue;
  5439. if (F->getType()->isReferenceType() ||
  5440. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5441. if (!Complained) {
  5442. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5443. << Record->getTagKind() << Record;
  5444. Complained = true;
  5445. }
  5446. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5447. << F->getType()->isReferenceType()
  5448. << F->getDeclName();
  5449. }
  5450. }
  5451. }
  5452. if (Record->getIdentifier()) {
  5453. // C++ [class.mem]p13:
  5454. // If T is the name of a class, then each of the following shall have a
  5455. // name different from T:
  5456. // - every member of every anonymous union that is a member of class T.
  5457. //
  5458. // C++ [class.mem]p14:
  5459. // In addition, if class T has a user-declared constructor (12.1), every
  5460. // non-static data member of class T shall have a name different from T.
  5461. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5462. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5463. ++I) {
  5464. NamedDecl *D = (*I)->getUnderlyingDecl();
  5465. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5466. Record->hasUserDeclaredConstructor()) ||
  5467. isa<IndirectFieldDecl>(D)) {
  5468. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5469. << D->getDeclName();
  5470. break;
  5471. }
  5472. }
  5473. }
  5474. // Warn if the class has virtual methods but non-virtual public destructor.
  5475. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5476. CXXDestructorDecl *dtor = Record->getDestructor();
  5477. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5478. !Record->hasAttr<FinalAttr>())
  5479. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5480. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5481. }
  5482. if (Record->isAbstract()) {
  5483. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5484. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5485. << FA->isSpelledAsSealed();
  5486. DiagnoseAbstractType(Record);
  5487. }
  5488. }
  5489. // Warn if the class has a final destructor but is not itself marked final.
  5490. if (!Record->hasAttr<FinalAttr>()) {
  5491. if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
  5492. if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
  5493. Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
  5494. << FA->isSpelledAsSealed()
  5495. << FixItHint::CreateInsertion(
  5496. getLocForEndOfToken(Record->getLocation()),
  5497. (FA->isSpelledAsSealed() ? " sealed" : " final"));
  5498. Diag(Record->getLocation(),
  5499. diag::note_final_dtor_non_final_class_silence)
  5500. << Context.getRecordType(Record) << FA->isSpelledAsSealed();
  5501. }
  5502. }
  5503. }
  5504. // See if trivial_abi has to be dropped.
  5505. if (Record->hasAttr<TrivialABIAttr>())
  5506. checkIllFormedTrivialABIStruct(*Record);
  5507. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5508. // "trivial_abi".
  5509. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5510. if (HasTrivialABI)
  5511. Record->setHasTrivialSpecialMemberForCall();
  5512. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  5513. // Check whether the explicitly-defaulted special members are valid.
  5514. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5515. CheckExplicitlyDefaultedSpecialMember(M);
  5516. // For an explicitly defaulted or deleted special member, we defer
  5517. // determining triviality until the class is complete. That time is now!
  5518. CXXSpecialMember CSM = getSpecialMember(M);
  5519. if (!M->isImplicit() && !M->isUserProvided()) {
  5520. if (CSM != CXXInvalid) {
  5521. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5522. // Inform the class that we've finished declaring this member.
  5523. Record->finishedDefaultedOrDeletedMember(M);
  5524. M->setTrivialForCall(
  5525. HasTrivialABI ||
  5526. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5527. Record->setTrivialForCallFlags(M);
  5528. }
  5529. }
  5530. // Set triviality for the purpose of calls if this is a user-provided
  5531. // copy/move constructor or destructor.
  5532. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5533. CSM == CXXDestructor) && M->isUserProvided()) {
  5534. M->setTrivialForCall(HasTrivialABI);
  5535. Record->setTrivialForCallFlags(M);
  5536. }
  5537. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5538. M->hasAttr<DLLExportAttr>()) {
  5539. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5540. M->isTrivial() &&
  5541. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5542. CSM == CXXDestructor))
  5543. M->dropAttr<DLLExportAttr>();
  5544. if (M->hasAttr<DLLExportAttr>()) {
  5545. // Define after any fields with in-class initializers have been parsed.
  5546. DelayedDllExportMemberFunctions.push_back(M);
  5547. }
  5548. }
  5549. // Define defaulted constexpr virtual functions that override a base class
  5550. // function right away.
  5551. // FIXME: We can defer doing this until the vtable is marked as used.
  5552. if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
  5553. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5554. };
  5555. bool HasMethodWithOverrideControl = false,
  5556. HasOverridingMethodWithoutOverrideControl = false;
  5557. if (!Record->isDependentType()) {
  5558. // Check the destructor before any other member function. We need to
  5559. // determine whether it's trivial in order to determine whether the claas
  5560. // type is a literal type, which is a prerequisite for determining whether
  5561. // other special member functions are valid and whether they're implicitly
  5562. // 'constexpr'.
  5563. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  5564. CompleteMemberFunction(Dtor);
  5565. for (auto *M : Record->methods()) {
  5566. // See if a method overloads virtual methods in a base
  5567. // class without overriding any.
  5568. if (!M->isStatic())
  5569. DiagnoseHiddenVirtualMethods(M);
  5570. if (M->hasAttr<OverrideAttr>())
  5571. HasMethodWithOverrideControl = true;
  5572. else if (M->size_overridden_methods() > 0)
  5573. HasOverridingMethodWithoutOverrideControl = true;
  5574. if (!isa<CXXDestructorDecl>(M))
  5575. CompleteMemberFunction(M);
  5576. }
  5577. }
  5578. if (HasMethodWithOverrideControl &&
  5579. HasOverridingMethodWithoutOverrideControl) {
  5580. // At least one method has the 'override' control declared.
  5581. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5582. for (auto *M : Record->methods())
  5583. DiagnoseAbsenceOfOverrideControl(M);
  5584. }
  5585. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5586. // whether this class uses any C++ features that are implemented
  5587. // completely differently in MSVC, and if so, emit a diagnostic.
  5588. // That diagnostic defaults to an error, but we allow projects to
  5589. // map it down to a warning (or ignore it). It's a fairly common
  5590. // practice among users of the ms_struct pragma to mass-annotate
  5591. // headers, sweeping up a bunch of types that the project doesn't
  5592. // really rely on MSVC-compatible layout for. We must therefore
  5593. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5594. if (Record->isMsStruct(Context) &&
  5595. (Record->isPolymorphic() || Record->getNumBases())) {
  5596. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5597. }
  5598. checkClassLevelDLLAttribute(Record);
  5599. checkClassLevelCodeSegAttribute(Record);
  5600. bool ClangABICompat4 =
  5601. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5602. TargetInfo::CallingConvKind CCK =
  5603. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5604. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5605. // Do not change ArgPassingRestrictions if it has already been set to
  5606. // APK_CanNeverPassInRegs.
  5607. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5608. Record->setArgPassingRestrictions(CanPass
  5609. ? RecordDecl::APK_CanPassInRegs
  5610. : RecordDecl::APK_CannotPassInRegs);
  5611. // If canPassInRegisters returns true despite the record having a non-trivial
  5612. // destructor, the record is destructed in the callee. This happens only when
  5613. // the record or one of its subobjects has a field annotated with trivial_abi
  5614. // or a field qualified with ObjC __strong/__weak.
  5615. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5616. Record->setParamDestroyedInCallee(true);
  5617. else if (Record->hasNonTrivialDestructor())
  5618. Record->setParamDestroyedInCallee(CanPass);
  5619. if (getLangOpts().ForceEmitVTables) {
  5620. // If we want to emit all the vtables, we need to mark it as used. This
  5621. // is especially required for cases like vtable assumption loads.
  5622. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5623. }
  5624. }
  5625. /// Look up the special member function that would be called by a special
  5626. /// member function for a subobject of class type.
  5627. ///
  5628. /// \param Class The class type of the subobject.
  5629. /// \param CSM The kind of special member function.
  5630. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5631. /// \param ConstRHS True if this is a copy operation with a const object
  5632. /// on its RHS, that is, if the argument to the outer special member
  5633. /// function is 'const' and this is not a field marked 'mutable'.
  5634. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5635. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5636. unsigned FieldQuals, bool ConstRHS) {
  5637. unsigned LHSQuals = 0;
  5638. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5639. LHSQuals = FieldQuals;
  5640. unsigned RHSQuals = FieldQuals;
  5641. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5642. RHSQuals = 0;
  5643. else if (ConstRHS)
  5644. RHSQuals |= Qualifiers::Const;
  5645. return S.LookupSpecialMember(Class, CSM,
  5646. RHSQuals & Qualifiers::Const,
  5647. RHSQuals & Qualifiers::Volatile,
  5648. false,
  5649. LHSQuals & Qualifiers::Const,
  5650. LHSQuals & Qualifiers::Volatile);
  5651. }
  5652. class Sema::InheritedConstructorInfo {
  5653. Sema &S;
  5654. SourceLocation UseLoc;
  5655. /// A mapping from the base classes through which the constructor was
  5656. /// inherited to the using shadow declaration in that base class (or a null
  5657. /// pointer if the constructor was declared in that base class).
  5658. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5659. InheritedFromBases;
  5660. public:
  5661. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5662. ConstructorUsingShadowDecl *Shadow)
  5663. : S(S), UseLoc(UseLoc) {
  5664. bool DiagnosedMultipleConstructedBases = false;
  5665. CXXRecordDecl *ConstructedBase = nullptr;
  5666. UsingDecl *ConstructedBaseUsing = nullptr;
  5667. // Find the set of such base class subobjects and check that there's a
  5668. // unique constructed subobject.
  5669. for (auto *D : Shadow->redecls()) {
  5670. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5671. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5672. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5673. InheritedFromBases.insert(
  5674. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5675. DShadow->getNominatedBaseClassShadowDecl()));
  5676. if (DShadow->constructsVirtualBase())
  5677. InheritedFromBases.insert(
  5678. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5679. DShadow->getConstructedBaseClassShadowDecl()));
  5680. else
  5681. assert(DNominatedBase == DConstructedBase);
  5682. // [class.inhctor.init]p2:
  5683. // If the constructor was inherited from multiple base class subobjects
  5684. // of type B, the program is ill-formed.
  5685. if (!ConstructedBase) {
  5686. ConstructedBase = DConstructedBase;
  5687. ConstructedBaseUsing = D->getUsingDecl();
  5688. } else if (ConstructedBase != DConstructedBase &&
  5689. !Shadow->isInvalidDecl()) {
  5690. if (!DiagnosedMultipleConstructedBases) {
  5691. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5692. << Shadow->getTargetDecl();
  5693. S.Diag(ConstructedBaseUsing->getLocation(),
  5694. diag::note_ambiguous_inherited_constructor_using)
  5695. << ConstructedBase;
  5696. DiagnosedMultipleConstructedBases = true;
  5697. }
  5698. S.Diag(D->getUsingDecl()->getLocation(),
  5699. diag::note_ambiguous_inherited_constructor_using)
  5700. << DConstructedBase;
  5701. }
  5702. }
  5703. if (DiagnosedMultipleConstructedBases)
  5704. Shadow->setInvalidDecl();
  5705. }
  5706. /// Find the constructor to use for inherited construction of a base class,
  5707. /// and whether that base class constructor inherits the constructor from a
  5708. /// virtual base class (in which case it won't actually invoke it).
  5709. std::pair<CXXConstructorDecl *, bool>
  5710. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5711. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5712. if (It == InheritedFromBases.end())
  5713. return std::make_pair(nullptr, false);
  5714. // This is an intermediary class.
  5715. if (It->second)
  5716. return std::make_pair(
  5717. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5718. It->second->constructsVirtualBase());
  5719. // This is the base class from which the constructor was inherited.
  5720. return std::make_pair(Ctor, false);
  5721. }
  5722. };
  5723. /// Is the special member function which would be selected to perform the
  5724. /// specified operation on the specified class type a constexpr constructor?
  5725. static bool
  5726. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5727. Sema::CXXSpecialMember CSM, unsigned Quals,
  5728. bool ConstRHS,
  5729. CXXConstructorDecl *InheritedCtor = nullptr,
  5730. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5731. // If we're inheriting a constructor, see if we need to call it for this base
  5732. // class.
  5733. if (InheritedCtor) {
  5734. assert(CSM == Sema::CXXDefaultConstructor);
  5735. auto BaseCtor =
  5736. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5737. if (BaseCtor)
  5738. return BaseCtor->isConstexpr();
  5739. }
  5740. if (CSM == Sema::CXXDefaultConstructor)
  5741. return ClassDecl->hasConstexprDefaultConstructor();
  5742. if (CSM == Sema::CXXDestructor)
  5743. return ClassDecl->hasConstexprDestructor();
  5744. Sema::SpecialMemberOverloadResult SMOR =
  5745. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5746. if (!SMOR.getMethod())
  5747. // A constructor we wouldn't select can't be "involved in initializing"
  5748. // anything.
  5749. return true;
  5750. return SMOR.getMethod()->isConstexpr();
  5751. }
  5752. /// Determine whether the specified special member function would be constexpr
  5753. /// if it were implicitly defined.
  5754. static bool defaultedSpecialMemberIsConstexpr(
  5755. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5756. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5757. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5758. if (!S.getLangOpts().CPlusPlus11)
  5759. return false;
  5760. // C++11 [dcl.constexpr]p4:
  5761. // In the definition of a constexpr constructor [...]
  5762. bool Ctor = true;
  5763. switch (CSM) {
  5764. case Sema::CXXDefaultConstructor:
  5765. if (Inherited)
  5766. break;
  5767. // Since default constructor lookup is essentially trivial (and cannot
  5768. // involve, for instance, template instantiation), we compute whether a
  5769. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5770. //
  5771. // This is important for performance; we need to know whether the default
  5772. // constructor is constexpr to determine whether the type is a literal type.
  5773. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5774. case Sema::CXXCopyConstructor:
  5775. case Sema::CXXMoveConstructor:
  5776. // For copy or move constructors, we need to perform overload resolution.
  5777. break;
  5778. case Sema::CXXCopyAssignment:
  5779. case Sema::CXXMoveAssignment:
  5780. if (!S.getLangOpts().CPlusPlus14)
  5781. return false;
  5782. // In C++1y, we need to perform overload resolution.
  5783. Ctor = false;
  5784. break;
  5785. case Sema::CXXDestructor:
  5786. return ClassDecl->defaultedDestructorIsConstexpr();
  5787. case Sema::CXXInvalid:
  5788. return false;
  5789. }
  5790. // -- if the class is a non-empty union, or for each non-empty anonymous
  5791. // union member of a non-union class, exactly one non-static data member
  5792. // shall be initialized; [DR1359]
  5793. //
  5794. // If we squint, this is guaranteed, since exactly one non-static data member
  5795. // will be initialized (if the constructor isn't deleted), we just don't know
  5796. // which one.
  5797. if (Ctor && ClassDecl->isUnion())
  5798. return CSM == Sema::CXXDefaultConstructor
  5799. ? ClassDecl->hasInClassInitializer() ||
  5800. !ClassDecl->hasVariantMembers()
  5801. : true;
  5802. // -- the class shall not have any virtual base classes;
  5803. if (Ctor && ClassDecl->getNumVBases())
  5804. return false;
  5805. // C++1y [class.copy]p26:
  5806. // -- [the class] is a literal type, and
  5807. if (!Ctor && !ClassDecl->isLiteral())
  5808. return false;
  5809. // -- every constructor involved in initializing [...] base class
  5810. // sub-objects shall be a constexpr constructor;
  5811. // -- the assignment operator selected to copy/move each direct base
  5812. // class is a constexpr function, and
  5813. for (const auto &B : ClassDecl->bases()) {
  5814. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5815. if (!BaseType) continue;
  5816. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5817. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5818. InheritedCtor, Inherited))
  5819. return false;
  5820. }
  5821. // -- every constructor involved in initializing non-static data members
  5822. // [...] shall be a constexpr constructor;
  5823. // -- every non-static data member and base class sub-object shall be
  5824. // initialized
  5825. // -- for each non-static data member of X that is of class type (or array
  5826. // thereof), the assignment operator selected to copy/move that member is
  5827. // a constexpr function
  5828. for (const auto *F : ClassDecl->fields()) {
  5829. if (F->isInvalidDecl())
  5830. continue;
  5831. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5832. continue;
  5833. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5834. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5835. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5836. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5837. BaseType.getCVRQualifiers(),
  5838. ConstArg && !F->isMutable()))
  5839. return false;
  5840. } else if (CSM == Sema::CXXDefaultConstructor) {
  5841. return false;
  5842. }
  5843. }
  5844. // All OK, it's constexpr!
  5845. return true;
  5846. }
  5847. static Sema::ImplicitExceptionSpecification
  5848. ComputeDefaultedSpecialMemberExceptionSpec(
  5849. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5850. Sema::InheritedConstructorInfo *ICI);
  5851. static Sema::ImplicitExceptionSpecification
  5852. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5853. auto CSM = S.getSpecialMember(MD);
  5854. if (CSM != Sema::CXXInvalid)
  5855. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5856. auto *CD = cast<CXXConstructorDecl>(MD);
  5857. assert(CD->getInheritedConstructor() &&
  5858. "only special members have implicit exception specs");
  5859. Sema::InheritedConstructorInfo ICI(
  5860. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5861. return ComputeDefaultedSpecialMemberExceptionSpec(
  5862. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5863. }
  5864. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5865. CXXMethodDecl *MD) {
  5866. FunctionProtoType::ExtProtoInfo EPI;
  5867. // Build an exception specification pointing back at this member.
  5868. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5869. EPI.ExceptionSpec.SourceDecl = MD;
  5870. // Set the calling convention to the default for C++ instance methods.
  5871. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5872. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5873. /*IsCXXMethod=*/true));
  5874. return EPI;
  5875. }
  5876. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5877. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5878. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5879. return;
  5880. // Evaluate the exception specification.
  5881. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5882. auto ESI = IES.getExceptionSpec();
  5883. // Update the type of the special member to use it.
  5884. UpdateExceptionSpec(MD, ESI);
  5885. // A user-provided destructor can be defined outside the class. When that
  5886. // happens, be sure to update the exception specification on both
  5887. // declarations.
  5888. const FunctionProtoType *CanonicalFPT =
  5889. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5890. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5891. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5892. }
  5893. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5894. CXXRecordDecl *RD = MD->getParent();
  5895. CXXSpecialMember CSM = getSpecialMember(MD);
  5896. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5897. "not an explicitly-defaulted special member");
  5898. // Whether this was the first-declared instance of the constructor.
  5899. // This affects whether we implicitly add an exception spec and constexpr.
  5900. bool First = MD == MD->getCanonicalDecl();
  5901. bool HadError = false;
  5902. // C++11 [dcl.fct.def.default]p1:
  5903. // A function that is explicitly defaulted shall
  5904. // -- be a special member function (checked elsewhere),
  5905. // -- have the same type (except for ref-qualifiers, and except that a
  5906. // copy operation can take a non-const reference) as an implicit
  5907. // declaration, and
  5908. // -- not have default arguments.
  5909. // C++2a changes the second bullet to instead delete the function if it's
  5910. // defaulted on its first declaration, unless it's "an assignment operator,
  5911. // and its return type differs or its parameter type is not a reference".
  5912. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
  5913. bool ShouldDeleteForTypeMismatch = false;
  5914. unsigned ExpectedParams = 1;
  5915. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5916. ExpectedParams = 0;
  5917. if (MD->getNumParams() != ExpectedParams) {
  5918. // This checks for default arguments: a copy or move constructor with a
  5919. // default argument is classified as a default constructor, and assignment
  5920. // operations and destructors can't have default arguments.
  5921. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5922. << CSM << MD->getSourceRange();
  5923. HadError = true;
  5924. } else if (MD->isVariadic()) {
  5925. if (DeleteOnTypeMismatch)
  5926. ShouldDeleteForTypeMismatch = true;
  5927. else {
  5928. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5929. << CSM << MD->getSourceRange();
  5930. HadError = true;
  5931. }
  5932. }
  5933. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5934. bool CanHaveConstParam = false;
  5935. if (CSM == CXXCopyConstructor)
  5936. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5937. else if (CSM == CXXCopyAssignment)
  5938. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5939. QualType ReturnType = Context.VoidTy;
  5940. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5941. // Check for return type matching.
  5942. ReturnType = Type->getReturnType();
  5943. QualType DeclType = Context.getTypeDeclType(RD);
  5944. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  5945. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  5946. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5947. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5948. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5949. HadError = true;
  5950. }
  5951. // A defaulted special member cannot have cv-qualifiers.
  5952. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  5953. if (DeleteOnTypeMismatch)
  5954. ShouldDeleteForTypeMismatch = true;
  5955. else {
  5956. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5957. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5958. HadError = true;
  5959. }
  5960. }
  5961. }
  5962. // Check for parameter type matching.
  5963. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5964. bool HasConstParam = false;
  5965. if (ExpectedParams && ArgType->isReferenceType()) {
  5966. // Argument must be reference to possibly-const T.
  5967. QualType ReferentType = ArgType->getPointeeType();
  5968. HasConstParam = ReferentType.isConstQualified();
  5969. if (ReferentType.isVolatileQualified()) {
  5970. if (DeleteOnTypeMismatch)
  5971. ShouldDeleteForTypeMismatch = true;
  5972. else {
  5973. Diag(MD->getLocation(),
  5974. diag::err_defaulted_special_member_volatile_param) << CSM;
  5975. HadError = true;
  5976. }
  5977. }
  5978. if (HasConstParam && !CanHaveConstParam) {
  5979. if (DeleteOnTypeMismatch)
  5980. ShouldDeleteForTypeMismatch = true;
  5981. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5982. Diag(MD->getLocation(),
  5983. diag::err_defaulted_special_member_copy_const_param)
  5984. << (CSM == CXXCopyAssignment);
  5985. // FIXME: Explain why this special member can't be const.
  5986. HadError = true;
  5987. } else {
  5988. Diag(MD->getLocation(),
  5989. diag::err_defaulted_special_member_move_const_param)
  5990. << (CSM == CXXMoveAssignment);
  5991. HadError = true;
  5992. }
  5993. }
  5994. } else if (ExpectedParams) {
  5995. // A copy assignment operator can take its argument by value, but a
  5996. // defaulted one cannot.
  5997. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5998. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5999. HadError = true;
  6000. }
  6001. // C++11 [dcl.fct.def.default]p2:
  6002. // An explicitly-defaulted function may be declared constexpr only if it
  6003. // would have been implicitly declared as constexpr,
  6004. // Do not apply this rule to members of class templates, since core issue 1358
  6005. // makes such functions always instantiate to constexpr functions. For
  6006. // functions which cannot be constexpr (for non-constructors in C++11 and for
  6007. // destructors in C++14 and C++17), this is checked elsewhere.
  6008. //
  6009. // FIXME: This should not apply if the member is deleted.
  6010. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  6011. HasConstParam);
  6012. if ((getLangOpts().CPlusPlus2a ||
  6013. (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  6014. : isa<CXXConstructorDecl>(MD))) &&
  6015. MD->isConstexpr() && !Constexpr &&
  6016. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  6017. Diag(MD->getBeginLoc(), MD->isConsteval()
  6018. ? diag::err_incorrect_defaulted_consteval
  6019. : diag::err_incorrect_defaulted_constexpr)
  6020. << CSM;
  6021. // FIXME: Explain why the special member can't be constexpr.
  6022. HadError = true;
  6023. }
  6024. if (First) {
  6025. // C++2a [dcl.fct.def.default]p3:
  6026. // If a function is explicitly defaulted on its first declaration, it is
  6027. // implicitly considered to be constexpr if the implicit declaration
  6028. // would be.
  6029. MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
  6030. if (!Type->hasExceptionSpec()) {
  6031. // C++2a [except.spec]p3:
  6032. // If a declaration of a function does not have a noexcept-specifier
  6033. // [and] is defaulted on its first declaration, [...] the exception
  6034. // specification is as specified below
  6035. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  6036. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6037. EPI.ExceptionSpec.SourceDecl = MD;
  6038. MD->setType(Context.getFunctionType(ReturnType,
  6039. llvm::makeArrayRef(&ArgType,
  6040. ExpectedParams),
  6041. EPI));
  6042. }
  6043. }
  6044. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  6045. if (First) {
  6046. SetDeclDeleted(MD, MD->getLocation());
  6047. if (!inTemplateInstantiation() && !HadError) {
  6048. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  6049. if (ShouldDeleteForTypeMismatch) {
  6050. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  6051. } else {
  6052. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6053. }
  6054. }
  6055. if (ShouldDeleteForTypeMismatch && !HadError) {
  6056. Diag(MD->getLocation(),
  6057. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  6058. }
  6059. } else {
  6060. // C++11 [dcl.fct.def.default]p4:
  6061. // [For a] user-provided explicitly-defaulted function [...] if such a
  6062. // function is implicitly defined as deleted, the program is ill-formed.
  6063. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  6064. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  6065. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6066. HadError = true;
  6067. }
  6068. }
  6069. if (HadError)
  6070. MD->setInvalidDecl();
  6071. }
  6072. void Sema::CheckDelayedMemberExceptionSpecs() {
  6073. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  6074. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  6075. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  6076. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  6077. // Perform any deferred checking of exception specifications for virtual
  6078. // destructors.
  6079. for (auto &Check : Overriding)
  6080. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  6081. // Perform any deferred checking of exception specifications for befriended
  6082. // special members.
  6083. for (auto &Check : Equivalent)
  6084. CheckEquivalentExceptionSpec(Check.second, Check.first);
  6085. }
  6086. namespace {
  6087. /// CRTP base class for visiting operations performed by a special member
  6088. /// function (or inherited constructor).
  6089. template<typename Derived>
  6090. struct SpecialMemberVisitor {
  6091. Sema &S;
  6092. CXXMethodDecl *MD;
  6093. Sema::CXXSpecialMember CSM;
  6094. Sema::InheritedConstructorInfo *ICI;
  6095. // Properties of the special member, computed for convenience.
  6096. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  6097. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  6098. Sema::InheritedConstructorInfo *ICI)
  6099. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  6100. switch (CSM) {
  6101. case Sema::CXXDefaultConstructor:
  6102. case Sema::CXXCopyConstructor:
  6103. case Sema::CXXMoveConstructor:
  6104. IsConstructor = true;
  6105. break;
  6106. case Sema::CXXCopyAssignment:
  6107. case Sema::CXXMoveAssignment:
  6108. IsAssignment = true;
  6109. break;
  6110. case Sema::CXXDestructor:
  6111. break;
  6112. case Sema::CXXInvalid:
  6113. llvm_unreachable("invalid special member kind");
  6114. }
  6115. if (MD->getNumParams()) {
  6116. if (const ReferenceType *RT =
  6117. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  6118. ConstArg = RT->getPointeeType().isConstQualified();
  6119. }
  6120. }
  6121. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6122. /// Is this a "move" special member?
  6123. bool isMove() const {
  6124. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  6125. }
  6126. /// Look up the corresponding special member in the given class.
  6127. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  6128. unsigned Quals, bool IsMutable) {
  6129. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  6130. ConstArg && !IsMutable);
  6131. }
  6132. /// Look up the constructor for the specified base class to see if it's
  6133. /// overridden due to this being an inherited constructor.
  6134. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  6135. if (!ICI)
  6136. return {};
  6137. assert(CSM == Sema::CXXDefaultConstructor);
  6138. auto *BaseCtor =
  6139. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  6140. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  6141. return MD;
  6142. return {};
  6143. }
  6144. /// A base or member subobject.
  6145. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  6146. /// Get the location to use for a subobject in diagnostics.
  6147. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  6148. // FIXME: For an indirect virtual base, the direct base leading to
  6149. // the indirect virtual base would be a more useful choice.
  6150. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  6151. return B->getBaseTypeLoc();
  6152. else
  6153. return Subobj.get<FieldDecl*>()->getLocation();
  6154. }
  6155. enum BasesToVisit {
  6156. /// Visit all non-virtual (direct) bases.
  6157. VisitNonVirtualBases,
  6158. /// Visit all direct bases, virtual or not.
  6159. VisitDirectBases,
  6160. /// Visit all non-virtual bases, and all virtual bases if the class
  6161. /// is not abstract.
  6162. VisitPotentiallyConstructedBases,
  6163. /// Visit all direct or virtual bases.
  6164. VisitAllBases
  6165. };
  6166. // Visit the bases and members of the class.
  6167. bool visit(BasesToVisit Bases) {
  6168. CXXRecordDecl *RD = MD->getParent();
  6169. if (Bases == VisitPotentiallyConstructedBases)
  6170. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  6171. for (auto &B : RD->bases())
  6172. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  6173. getDerived().visitBase(&B))
  6174. return true;
  6175. if (Bases == VisitAllBases)
  6176. for (auto &B : RD->vbases())
  6177. if (getDerived().visitBase(&B))
  6178. return true;
  6179. for (auto *F : RD->fields())
  6180. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  6181. getDerived().visitField(F))
  6182. return true;
  6183. return false;
  6184. }
  6185. };
  6186. }
  6187. namespace {
  6188. struct SpecialMemberDeletionInfo
  6189. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  6190. bool Diagnose;
  6191. SourceLocation Loc;
  6192. bool AllFieldsAreConst;
  6193. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  6194. Sema::CXXSpecialMember CSM,
  6195. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  6196. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  6197. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  6198. bool inUnion() const { return MD->getParent()->isUnion(); }
  6199. Sema::CXXSpecialMember getEffectiveCSM() {
  6200. return ICI ? Sema::CXXInvalid : CSM;
  6201. }
  6202. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  6203. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  6204. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  6205. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  6206. bool shouldDeleteForField(FieldDecl *FD);
  6207. bool shouldDeleteForAllConstMembers();
  6208. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  6209. unsigned Quals);
  6210. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  6211. Sema::SpecialMemberOverloadResult SMOR,
  6212. bool IsDtorCallInCtor);
  6213. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  6214. };
  6215. }
  6216. /// Is the given special member inaccessible when used on the given
  6217. /// sub-object.
  6218. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  6219. CXXMethodDecl *target) {
  6220. /// If we're operating on a base class, the object type is the
  6221. /// type of this special member.
  6222. QualType objectTy;
  6223. AccessSpecifier access = target->getAccess();
  6224. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  6225. objectTy = S.Context.getTypeDeclType(MD->getParent());
  6226. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  6227. // If we're operating on a field, the object type is the type of the field.
  6228. } else {
  6229. objectTy = S.Context.getTypeDeclType(target->getParent());
  6230. }
  6231. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  6232. }
  6233. /// Check whether we should delete a special member due to the implicit
  6234. /// definition containing a call to a special member of a subobject.
  6235. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  6236. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  6237. bool IsDtorCallInCtor) {
  6238. CXXMethodDecl *Decl = SMOR.getMethod();
  6239. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6240. int DiagKind = -1;
  6241. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  6242. DiagKind = !Decl ? 0 : 1;
  6243. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6244. DiagKind = 2;
  6245. else if (!isAccessible(Subobj, Decl))
  6246. DiagKind = 3;
  6247. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  6248. !Decl->isTrivial()) {
  6249. // A member of a union must have a trivial corresponding special member.
  6250. // As a weird special case, a destructor call from a union's constructor
  6251. // must be accessible and non-deleted, but need not be trivial. Such a
  6252. // destructor is never actually called, but is semantically checked as
  6253. // if it were.
  6254. DiagKind = 4;
  6255. }
  6256. if (DiagKind == -1)
  6257. return false;
  6258. if (Diagnose) {
  6259. if (Field) {
  6260. S.Diag(Field->getLocation(),
  6261. diag::note_deleted_special_member_class_subobject)
  6262. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  6263. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  6264. } else {
  6265. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  6266. S.Diag(Base->getBeginLoc(),
  6267. diag::note_deleted_special_member_class_subobject)
  6268. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6269. << Base->getType() << DiagKind << IsDtorCallInCtor
  6270. << /*IsObjCPtr*/false;
  6271. }
  6272. if (DiagKind == 1)
  6273. S.NoteDeletedFunction(Decl);
  6274. // FIXME: Explain inaccessibility if DiagKind == 3.
  6275. }
  6276. return true;
  6277. }
  6278. /// Check whether we should delete a special member function due to having a
  6279. /// direct or virtual base class or non-static data member of class type M.
  6280. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  6281. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  6282. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6283. bool IsMutable = Field && Field->isMutable();
  6284. // C++11 [class.ctor]p5:
  6285. // -- any direct or virtual base class, or non-static data member with no
  6286. // brace-or-equal-initializer, has class type M (or array thereof) and
  6287. // either M has no default constructor or overload resolution as applied
  6288. // to M's default constructor results in an ambiguity or in a function
  6289. // that is deleted or inaccessible
  6290. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6291. // -- a direct or virtual base class B that cannot be copied/moved because
  6292. // overload resolution, as applied to B's corresponding special member,
  6293. // results in an ambiguity or a function that is deleted or inaccessible
  6294. // from the defaulted special member
  6295. // C++11 [class.dtor]p5:
  6296. // -- any direct or virtual base class [...] has a type with a destructor
  6297. // that is deleted or inaccessible
  6298. if (!(CSM == Sema::CXXDefaultConstructor &&
  6299. Field && Field->hasInClassInitializer()) &&
  6300. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6301. false))
  6302. return true;
  6303. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6304. // -- any direct or virtual base class or non-static data member has a
  6305. // type with a destructor that is deleted or inaccessible
  6306. if (IsConstructor) {
  6307. Sema::SpecialMemberOverloadResult SMOR =
  6308. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6309. false, false, false, false, false);
  6310. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6311. return true;
  6312. }
  6313. return false;
  6314. }
  6315. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  6316. FieldDecl *FD, QualType FieldType) {
  6317. // The defaulted special functions are defined as deleted if this is a variant
  6318. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  6319. // type under ARC.
  6320. if (!FieldType.hasNonTrivialObjCLifetime())
  6321. return false;
  6322. // Don't make the defaulted default constructor defined as deleted if the
  6323. // member has an in-class initializer.
  6324. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  6325. return false;
  6326. if (Diagnose) {
  6327. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  6328. S.Diag(FD->getLocation(),
  6329. diag::note_deleted_special_member_class_subobject)
  6330. << getEffectiveCSM() << ParentClass << /*IsField*/true
  6331. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  6332. }
  6333. return true;
  6334. }
  6335. /// Check whether we should delete a special member function due to the class
  6336. /// having a particular direct or virtual base class.
  6337. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6338. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6339. // If program is correct, BaseClass cannot be null, but if it is, the error
  6340. // must be reported elsewhere.
  6341. if (!BaseClass)
  6342. return false;
  6343. // If we have an inheriting constructor, check whether we're calling an
  6344. // inherited constructor instead of a default constructor.
  6345. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6346. if (auto *BaseCtor = SMOR.getMethod()) {
  6347. // Note that we do not check access along this path; other than that,
  6348. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6349. // FIXME: Check that the base has a usable destructor! Sink this into
  6350. // shouldDeleteForClassSubobject.
  6351. if (BaseCtor->isDeleted() && Diagnose) {
  6352. S.Diag(Base->getBeginLoc(),
  6353. diag::note_deleted_special_member_class_subobject)
  6354. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6355. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  6356. << /*IsObjCPtr*/false;
  6357. S.NoteDeletedFunction(BaseCtor);
  6358. }
  6359. return BaseCtor->isDeleted();
  6360. }
  6361. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6362. }
  6363. /// Check whether we should delete a special member function due to the class
  6364. /// having a particular non-static data member.
  6365. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6366. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6367. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6368. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  6369. return true;
  6370. if (CSM == Sema::CXXDefaultConstructor) {
  6371. // For a default constructor, all references must be initialized in-class
  6372. // and, if a union, it must have a non-const member.
  6373. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6374. if (Diagnose)
  6375. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6376. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6377. return true;
  6378. }
  6379. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6380. // const-qualified type (or array thereof) with no
  6381. // brace-or-equal-initializer does not have a user-provided default
  6382. // constructor.
  6383. if (!inUnion() && FieldType.isConstQualified() &&
  6384. !FD->hasInClassInitializer() &&
  6385. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6386. if (Diagnose)
  6387. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6388. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6389. return true;
  6390. }
  6391. if (inUnion() && !FieldType.isConstQualified())
  6392. AllFieldsAreConst = false;
  6393. } else if (CSM == Sema::CXXCopyConstructor) {
  6394. // For a copy constructor, data members must not be of rvalue reference
  6395. // type.
  6396. if (FieldType->isRValueReferenceType()) {
  6397. if (Diagnose)
  6398. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6399. << MD->getParent() << FD << FieldType;
  6400. return true;
  6401. }
  6402. } else if (IsAssignment) {
  6403. // For an assignment operator, data members must not be of reference type.
  6404. if (FieldType->isReferenceType()) {
  6405. if (Diagnose)
  6406. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6407. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6408. return true;
  6409. }
  6410. if (!FieldRecord && FieldType.isConstQualified()) {
  6411. // C++11 [class.copy]p23:
  6412. // -- a non-static data member of const non-class type (or array thereof)
  6413. if (Diagnose)
  6414. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6415. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6416. return true;
  6417. }
  6418. }
  6419. if (FieldRecord) {
  6420. // Some additional restrictions exist on the variant members.
  6421. if (!inUnion() && FieldRecord->isUnion() &&
  6422. FieldRecord->isAnonymousStructOrUnion()) {
  6423. bool AllVariantFieldsAreConst = true;
  6424. // FIXME: Handle anonymous unions declared within anonymous unions.
  6425. for (auto *UI : FieldRecord->fields()) {
  6426. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6427. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  6428. return true;
  6429. if (!UnionFieldType.isConstQualified())
  6430. AllVariantFieldsAreConst = false;
  6431. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6432. if (UnionFieldRecord &&
  6433. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6434. UnionFieldType.getCVRQualifiers()))
  6435. return true;
  6436. }
  6437. // At least one member in each anonymous union must be non-const
  6438. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6439. !FieldRecord->field_empty()) {
  6440. if (Diagnose)
  6441. S.Diag(FieldRecord->getLocation(),
  6442. diag::note_deleted_default_ctor_all_const)
  6443. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6444. return true;
  6445. }
  6446. // Don't check the implicit member of the anonymous union type.
  6447. // This is technically non-conformant, but sanity demands it.
  6448. return false;
  6449. }
  6450. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6451. FieldType.getCVRQualifiers()))
  6452. return true;
  6453. }
  6454. return false;
  6455. }
  6456. /// C++11 [class.ctor] p5:
  6457. /// A defaulted default constructor for a class X is defined as deleted if
  6458. /// X is a union and all of its variant members are of const-qualified type.
  6459. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6460. // This is a silly definition, because it gives an empty union a deleted
  6461. // default constructor. Don't do that.
  6462. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6463. bool AnyFields = false;
  6464. for (auto *F : MD->getParent()->fields())
  6465. if ((AnyFields = !F->isUnnamedBitfield()))
  6466. break;
  6467. if (!AnyFields)
  6468. return false;
  6469. if (Diagnose)
  6470. S.Diag(MD->getParent()->getLocation(),
  6471. diag::note_deleted_default_ctor_all_const)
  6472. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6473. return true;
  6474. }
  6475. return false;
  6476. }
  6477. /// Determine whether a defaulted special member function should be defined as
  6478. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6479. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6480. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6481. InheritedConstructorInfo *ICI,
  6482. bool Diagnose) {
  6483. if (MD->isInvalidDecl())
  6484. return false;
  6485. CXXRecordDecl *RD = MD->getParent();
  6486. assert(!RD->isDependentType() && "do deletion after instantiation");
  6487. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6488. return false;
  6489. // C++11 [expr.lambda.prim]p19:
  6490. // The closure type associated with a lambda-expression has a
  6491. // deleted (8.4.3) default constructor and a deleted copy
  6492. // assignment operator.
  6493. // C++2a adds back these operators if the lambda has no lambda-capture.
  6494. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  6495. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6496. if (Diagnose)
  6497. Diag(RD->getLocation(), diag::note_lambda_decl);
  6498. return true;
  6499. }
  6500. // For an anonymous struct or union, the copy and assignment special members
  6501. // will never be used, so skip the check. For an anonymous union declared at
  6502. // namespace scope, the constructor and destructor are used.
  6503. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6504. RD->isAnonymousStructOrUnion())
  6505. return false;
  6506. // C++11 [class.copy]p7, p18:
  6507. // If the class definition declares a move constructor or move assignment
  6508. // operator, an implicitly declared copy constructor or copy assignment
  6509. // operator is defined as deleted.
  6510. if (MD->isImplicit() &&
  6511. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6512. CXXMethodDecl *UserDeclaredMove = nullptr;
  6513. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6514. // deletion of the corresponding copy operation, not both copy operations.
  6515. // MSVC 2015 has adopted the standards conforming behavior.
  6516. bool DeletesOnlyMatchingCopy =
  6517. getLangOpts().MSVCCompat &&
  6518. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6519. if (RD->hasUserDeclaredMoveConstructor() &&
  6520. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6521. if (!Diagnose) return true;
  6522. // Find any user-declared move constructor.
  6523. for (auto *I : RD->ctors()) {
  6524. if (I->isMoveConstructor()) {
  6525. UserDeclaredMove = I;
  6526. break;
  6527. }
  6528. }
  6529. assert(UserDeclaredMove);
  6530. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6531. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6532. if (!Diagnose) return true;
  6533. // Find any user-declared move assignment operator.
  6534. for (auto *I : RD->methods()) {
  6535. if (I->isMoveAssignmentOperator()) {
  6536. UserDeclaredMove = I;
  6537. break;
  6538. }
  6539. }
  6540. assert(UserDeclaredMove);
  6541. }
  6542. if (UserDeclaredMove) {
  6543. Diag(UserDeclaredMove->getLocation(),
  6544. diag::note_deleted_copy_user_declared_move)
  6545. << (CSM == CXXCopyAssignment) << RD
  6546. << UserDeclaredMove->isMoveAssignmentOperator();
  6547. return true;
  6548. }
  6549. }
  6550. // Do access control from the special member function
  6551. ContextRAII MethodContext(*this, MD);
  6552. // C++11 [class.dtor]p5:
  6553. // -- for a virtual destructor, lookup of the non-array deallocation function
  6554. // results in an ambiguity or in a function that is deleted or inaccessible
  6555. if (CSM == CXXDestructor && MD->isVirtual()) {
  6556. FunctionDecl *OperatorDelete = nullptr;
  6557. DeclarationName Name =
  6558. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6559. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6560. OperatorDelete, /*Diagnose*/false)) {
  6561. if (Diagnose)
  6562. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6563. return true;
  6564. }
  6565. }
  6566. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6567. // Per DR1611, do not consider virtual bases of constructors of abstract
  6568. // classes, since we are not going to construct them.
  6569. // Per DR1658, do not consider virtual bases of destructors of abstract
  6570. // classes either.
  6571. // Per DR2180, for assignment operators we only assign (and thus only
  6572. // consider) direct bases.
  6573. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6574. : SMI.VisitPotentiallyConstructedBases))
  6575. return true;
  6576. if (SMI.shouldDeleteForAllConstMembers())
  6577. return true;
  6578. if (getLangOpts().CUDA) {
  6579. // We should delete the special member in CUDA mode if target inference
  6580. // failed.
  6581. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  6582. // is treated as certain special member, which may not reflect what special
  6583. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  6584. // expects CSM to match MD, therefore recalculate CSM.
  6585. assert(ICI || CSM == getSpecialMember(MD));
  6586. auto RealCSM = CSM;
  6587. if (ICI)
  6588. RealCSM = getSpecialMember(MD);
  6589. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  6590. SMI.ConstArg, Diagnose);
  6591. }
  6592. return false;
  6593. }
  6594. /// Perform lookup for a special member of the specified kind, and determine
  6595. /// whether it is trivial. If the triviality can be determined without the
  6596. /// lookup, skip it. This is intended for use when determining whether a
  6597. /// special member of a containing object is trivial, and thus does not ever
  6598. /// perform overload resolution for default constructors.
  6599. ///
  6600. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6601. /// member that was most likely to be intended to be trivial, if any.
  6602. ///
  6603. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6604. /// determine whether the special member is trivial.
  6605. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6606. Sema::CXXSpecialMember CSM, unsigned Quals,
  6607. bool ConstRHS,
  6608. Sema::TrivialABIHandling TAH,
  6609. CXXMethodDecl **Selected) {
  6610. if (Selected)
  6611. *Selected = nullptr;
  6612. switch (CSM) {
  6613. case Sema::CXXInvalid:
  6614. llvm_unreachable("not a special member");
  6615. case Sema::CXXDefaultConstructor:
  6616. // C++11 [class.ctor]p5:
  6617. // A default constructor is trivial if:
  6618. // - all the [direct subobjects] have trivial default constructors
  6619. //
  6620. // Note, no overload resolution is performed in this case.
  6621. if (RD->hasTrivialDefaultConstructor())
  6622. return true;
  6623. if (Selected) {
  6624. // If there's a default constructor which could have been trivial, dig it
  6625. // out. Otherwise, if there's any user-provided default constructor, point
  6626. // to that as an example of why there's not a trivial one.
  6627. CXXConstructorDecl *DefCtor = nullptr;
  6628. if (RD->needsImplicitDefaultConstructor())
  6629. S.DeclareImplicitDefaultConstructor(RD);
  6630. for (auto *CI : RD->ctors()) {
  6631. if (!CI->isDefaultConstructor())
  6632. continue;
  6633. DefCtor = CI;
  6634. if (!DefCtor->isUserProvided())
  6635. break;
  6636. }
  6637. *Selected = DefCtor;
  6638. }
  6639. return false;
  6640. case Sema::CXXDestructor:
  6641. // C++11 [class.dtor]p5:
  6642. // A destructor is trivial if:
  6643. // - all the direct [subobjects] have trivial destructors
  6644. if (RD->hasTrivialDestructor() ||
  6645. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6646. RD->hasTrivialDestructorForCall()))
  6647. return true;
  6648. if (Selected) {
  6649. if (RD->needsImplicitDestructor())
  6650. S.DeclareImplicitDestructor(RD);
  6651. *Selected = RD->getDestructor();
  6652. }
  6653. return false;
  6654. case Sema::CXXCopyConstructor:
  6655. // C++11 [class.copy]p12:
  6656. // A copy constructor is trivial if:
  6657. // - the constructor selected to copy each direct [subobject] is trivial
  6658. if (RD->hasTrivialCopyConstructor() ||
  6659. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6660. RD->hasTrivialCopyConstructorForCall())) {
  6661. if (Quals == Qualifiers::Const)
  6662. // We must either select the trivial copy constructor or reach an
  6663. // ambiguity; no need to actually perform overload resolution.
  6664. return true;
  6665. } else if (!Selected) {
  6666. return false;
  6667. }
  6668. // In C++98, we are not supposed to perform overload resolution here, but we
  6669. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6670. // cases like B as having a non-trivial copy constructor:
  6671. // struct A { template<typename T> A(T&); };
  6672. // struct B { mutable A a; };
  6673. goto NeedOverloadResolution;
  6674. case Sema::CXXCopyAssignment:
  6675. // C++11 [class.copy]p25:
  6676. // A copy assignment operator is trivial if:
  6677. // - the assignment operator selected to copy each direct [subobject] is
  6678. // trivial
  6679. if (RD->hasTrivialCopyAssignment()) {
  6680. if (Quals == Qualifiers::Const)
  6681. return true;
  6682. } else if (!Selected) {
  6683. return false;
  6684. }
  6685. // In C++98, we are not supposed to perform overload resolution here, but we
  6686. // treat that as a language defect.
  6687. goto NeedOverloadResolution;
  6688. case Sema::CXXMoveConstructor:
  6689. case Sema::CXXMoveAssignment:
  6690. NeedOverloadResolution:
  6691. Sema::SpecialMemberOverloadResult SMOR =
  6692. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6693. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6694. // We treat it as not making the member non-trivial, just like the standard
  6695. // mandates for the default constructor. This should rarely matter, because
  6696. // the member will also be deleted.
  6697. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6698. return true;
  6699. if (!SMOR.getMethod()) {
  6700. assert(SMOR.getKind() ==
  6701. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6702. return false;
  6703. }
  6704. // We deliberately don't check if we found a deleted special member. We're
  6705. // not supposed to!
  6706. if (Selected)
  6707. *Selected = SMOR.getMethod();
  6708. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6709. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6710. return SMOR.getMethod()->isTrivialForCall();
  6711. return SMOR.getMethod()->isTrivial();
  6712. }
  6713. llvm_unreachable("unknown special method kind");
  6714. }
  6715. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6716. for (auto *CI : RD->ctors())
  6717. if (!CI->isImplicit())
  6718. return CI;
  6719. // Look for constructor templates.
  6720. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6721. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6722. if (CXXConstructorDecl *CD =
  6723. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6724. return CD;
  6725. }
  6726. return nullptr;
  6727. }
  6728. /// The kind of subobject we are checking for triviality. The values of this
  6729. /// enumeration are used in diagnostics.
  6730. enum TrivialSubobjectKind {
  6731. /// The subobject is a base class.
  6732. TSK_BaseClass,
  6733. /// The subobject is a non-static data member.
  6734. TSK_Field,
  6735. /// The object is actually the complete object.
  6736. TSK_CompleteObject
  6737. };
  6738. /// Check whether the special member selected for a given type would be trivial.
  6739. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6740. QualType SubType, bool ConstRHS,
  6741. Sema::CXXSpecialMember CSM,
  6742. TrivialSubobjectKind Kind,
  6743. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6744. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6745. if (!SubRD)
  6746. return true;
  6747. CXXMethodDecl *Selected;
  6748. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6749. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6750. return true;
  6751. if (Diagnose) {
  6752. if (ConstRHS)
  6753. SubType.addConst();
  6754. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6755. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6756. << Kind << SubType.getUnqualifiedType();
  6757. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6758. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6759. } else if (!Selected)
  6760. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6761. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6762. else if (Selected->isUserProvided()) {
  6763. if (Kind == TSK_CompleteObject)
  6764. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6765. << Kind << SubType.getUnqualifiedType() << CSM;
  6766. else {
  6767. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6768. << Kind << SubType.getUnqualifiedType() << CSM;
  6769. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6770. }
  6771. } else {
  6772. if (Kind != TSK_CompleteObject)
  6773. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6774. << Kind << SubType.getUnqualifiedType() << CSM;
  6775. // Explain why the defaulted or deleted special member isn't trivial.
  6776. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6777. Diagnose);
  6778. }
  6779. }
  6780. return false;
  6781. }
  6782. /// Check whether the members of a class type allow a special member to be
  6783. /// trivial.
  6784. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6785. Sema::CXXSpecialMember CSM,
  6786. bool ConstArg,
  6787. Sema::TrivialABIHandling TAH,
  6788. bool Diagnose) {
  6789. for (const auto *FI : RD->fields()) {
  6790. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6791. continue;
  6792. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6793. // Pretend anonymous struct or union members are members of this class.
  6794. if (FI->isAnonymousStructOrUnion()) {
  6795. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6796. CSM, ConstArg, TAH, Diagnose))
  6797. return false;
  6798. continue;
  6799. }
  6800. // C++11 [class.ctor]p5:
  6801. // A default constructor is trivial if [...]
  6802. // -- no non-static data member of its class has a
  6803. // brace-or-equal-initializer
  6804. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6805. if (Diagnose)
  6806. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6807. return false;
  6808. }
  6809. // Objective C ARC 4.3.5:
  6810. // [...] nontrivally ownership-qualified types are [...] not trivially
  6811. // default constructible, copy constructible, move constructible, copy
  6812. // assignable, move assignable, or destructible [...]
  6813. if (FieldType.hasNonTrivialObjCLifetime()) {
  6814. if (Diagnose)
  6815. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6816. << RD << FieldType.getObjCLifetime();
  6817. return false;
  6818. }
  6819. bool ConstRHS = ConstArg && !FI->isMutable();
  6820. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6821. CSM, TSK_Field, TAH, Diagnose))
  6822. return false;
  6823. }
  6824. return true;
  6825. }
  6826. /// Diagnose why the specified class does not have a trivial special member of
  6827. /// the given kind.
  6828. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6829. QualType Ty = Context.getRecordType(RD);
  6830. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6831. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6832. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6833. /*Diagnose*/true);
  6834. }
  6835. /// Determine whether a defaulted or deleted special member function is trivial,
  6836. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6837. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6838. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6839. TrivialABIHandling TAH, bool Diagnose) {
  6840. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6841. CXXRecordDecl *RD = MD->getParent();
  6842. bool ConstArg = false;
  6843. // C++11 [class.copy]p12, p25: [DR1593]
  6844. // A [special member] is trivial if [...] its parameter-type-list is
  6845. // equivalent to the parameter-type-list of an implicit declaration [...]
  6846. switch (CSM) {
  6847. case CXXDefaultConstructor:
  6848. case CXXDestructor:
  6849. // Trivial default constructors and destructors cannot have parameters.
  6850. break;
  6851. case CXXCopyConstructor:
  6852. case CXXCopyAssignment: {
  6853. // Trivial copy operations always have const, non-volatile parameter types.
  6854. ConstArg = true;
  6855. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6856. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6857. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6858. if (Diagnose)
  6859. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6860. << Param0->getSourceRange() << Param0->getType()
  6861. << Context.getLValueReferenceType(
  6862. Context.getRecordType(RD).withConst());
  6863. return false;
  6864. }
  6865. break;
  6866. }
  6867. case CXXMoveConstructor:
  6868. case CXXMoveAssignment: {
  6869. // Trivial move operations always have non-cv-qualified parameters.
  6870. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6871. const RValueReferenceType *RT =
  6872. Param0->getType()->getAs<RValueReferenceType>();
  6873. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6874. if (Diagnose)
  6875. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6876. << Param0->getSourceRange() << Param0->getType()
  6877. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6878. return false;
  6879. }
  6880. break;
  6881. }
  6882. case CXXInvalid:
  6883. llvm_unreachable("not a special member");
  6884. }
  6885. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6886. if (Diagnose)
  6887. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6888. diag::note_nontrivial_default_arg)
  6889. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6890. return false;
  6891. }
  6892. if (MD->isVariadic()) {
  6893. if (Diagnose)
  6894. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6895. return false;
  6896. }
  6897. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6898. // A copy/move [constructor or assignment operator] is trivial if
  6899. // -- the [member] selected to copy/move each direct base class subobject
  6900. // is trivial
  6901. //
  6902. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6903. // A [default constructor or destructor] is trivial if
  6904. // -- all the direct base classes have trivial [default constructors or
  6905. // destructors]
  6906. for (const auto &BI : RD->bases())
  6907. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6908. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6909. return false;
  6910. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6911. // A copy/move [constructor or assignment operator] for a class X is
  6912. // trivial if
  6913. // -- for each non-static data member of X that is of class type (or array
  6914. // thereof), the constructor selected to copy/move that member is
  6915. // trivial
  6916. //
  6917. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6918. // A [default constructor or destructor] is trivial if
  6919. // -- for all of the non-static data members of its class that are of class
  6920. // type (or array thereof), each such class has a trivial [default
  6921. // constructor or destructor]
  6922. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6923. return false;
  6924. // C++11 [class.dtor]p5:
  6925. // A destructor is trivial if [...]
  6926. // -- the destructor is not virtual
  6927. if (CSM == CXXDestructor && MD->isVirtual()) {
  6928. if (Diagnose)
  6929. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6930. return false;
  6931. }
  6932. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6933. // A [special member] for class X is trivial if [...]
  6934. // -- class X has no virtual functions and no virtual base classes
  6935. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6936. if (!Diagnose)
  6937. return false;
  6938. if (RD->getNumVBases()) {
  6939. // Check for virtual bases. We already know that the corresponding
  6940. // member in all bases is trivial, so vbases must all be direct.
  6941. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6942. assert(BS.isVirtual());
  6943. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6944. return false;
  6945. }
  6946. // Must have a virtual method.
  6947. for (const auto *MI : RD->methods()) {
  6948. if (MI->isVirtual()) {
  6949. SourceLocation MLoc = MI->getBeginLoc();
  6950. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6951. return false;
  6952. }
  6953. }
  6954. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6955. }
  6956. // Looks like it's trivial!
  6957. return true;
  6958. }
  6959. namespace {
  6960. struct FindHiddenVirtualMethod {
  6961. Sema *S;
  6962. CXXMethodDecl *Method;
  6963. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6964. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6965. private:
  6966. /// Check whether any most overridden method from MD in Methods
  6967. static bool CheckMostOverridenMethods(
  6968. const CXXMethodDecl *MD,
  6969. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6970. if (MD->size_overridden_methods() == 0)
  6971. return Methods.count(MD->getCanonicalDecl());
  6972. for (const CXXMethodDecl *O : MD->overridden_methods())
  6973. if (CheckMostOverridenMethods(O, Methods))
  6974. return true;
  6975. return false;
  6976. }
  6977. public:
  6978. /// Member lookup function that determines whether a given C++
  6979. /// method overloads virtual methods in a base class without overriding any,
  6980. /// to be used with CXXRecordDecl::lookupInBases().
  6981. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6982. RecordDecl *BaseRecord =
  6983. Specifier->getType()->castAs<RecordType>()->getDecl();
  6984. DeclarationName Name = Method->getDeclName();
  6985. assert(Name.getNameKind() == DeclarationName::Identifier);
  6986. bool foundSameNameMethod = false;
  6987. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6988. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6989. Path.Decls = Path.Decls.slice(1)) {
  6990. NamedDecl *D = Path.Decls.front();
  6991. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6992. MD = MD->getCanonicalDecl();
  6993. foundSameNameMethod = true;
  6994. // Interested only in hidden virtual methods.
  6995. if (!MD->isVirtual())
  6996. continue;
  6997. // If the method we are checking overrides a method from its base
  6998. // don't warn about the other overloaded methods. Clang deviates from
  6999. // GCC by only diagnosing overloads of inherited virtual functions that
  7000. // do not override any other virtual functions in the base. GCC's
  7001. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  7002. // function from a base class. These cases may be better served by a
  7003. // warning (not specific to virtual functions) on call sites when the
  7004. // call would select a different function from the base class, were it
  7005. // visible.
  7006. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  7007. if (!S->IsOverload(Method, MD, false))
  7008. return true;
  7009. // Collect the overload only if its hidden.
  7010. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  7011. overloadedMethods.push_back(MD);
  7012. }
  7013. }
  7014. if (foundSameNameMethod)
  7015. OverloadedMethods.append(overloadedMethods.begin(),
  7016. overloadedMethods.end());
  7017. return foundSameNameMethod;
  7018. }
  7019. };
  7020. } // end anonymous namespace
  7021. /// Add the most overriden methods from MD to Methods
  7022. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  7023. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  7024. if (MD->size_overridden_methods() == 0)
  7025. Methods.insert(MD->getCanonicalDecl());
  7026. else
  7027. for (const CXXMethodDecl *O : MD->overridden_methods())
  7028. AddMostOverridenMethods(O, Methods);
  7029. }
  7030. /// Check if a method overloads virtual methods in a base class without
  7031. /// overriding any.
  7032. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  7033. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  7034. if (!MD->getDeclName().isIdentifier())
  7035. return;
  7036. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  7037. /*bool RecordPaths=*/false,
  7038. /*bool DetectVirtual=*/false);
  7039. FindHiddenVirtualMethod FHVM;
  7040. FHVM.Method = MD;
  7041. FHVM.S = this;
  7042. // Keep the base methods that were overridden or introduced in the subclass
  7043. // by 'using' in a set. A base method not in this set is hidden.
  7044. CXXRecordDecl *DC = MD->getParent();
  7045. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  7046. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7047. NamedDecl *ND = *I;
  7048. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  7049. ND = shad->getTargetDecl();
  7050. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  7051. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  7052. }
  7053. if (DC->lookupInBases(FHVM, Paths))
  7054. OverloadedMethods = FHVM.OverloadedMethods;
  7055. }
  7056. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  7057. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  7058. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  7059. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  7060. PartialDiagnostic PD = PDiag(
  7061. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  7062. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  7063. Diag(overloadedMD->getLocation(), PD);
  7064. }
  7065. }
  7066. /// Diagnose methods which overload virtual methods in a base class
  7067. /// without overriding any.
  7068. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  7069. if (MD->isInvalidDecl())
  7070. return;
  7071. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  7072. return;
  7073. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  7074. FindHiddenVirtualMethods(MD, OverloadedMethods);
  7075. if (!OverloadedMethods.empty()) {
  7076. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  7077. << MD << (OverloadedMethods.size() > 1);
  7078. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  7079. }
  7080. }
  7081. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  7082. auto PrintDiagAndRemoveAttr = [&]() {
  7083. // No diagnostics if this is a template instantiation.
  7084. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  7085. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  7086. diag::ext_cannot_use_trivial_abi) << &RD;
  7087. RD.dropAttr<TrivialABIAttr>();
  7088. };
  7089. // Ill-formed if the struct has virtual functions.
  7090. if (RD.isPolymorphic()) {
  7091. PrintDiagAndRemoveAttr();
  7092. return;
  7093. }
  7094. for (const auto &B : RD.bases()) {
  7095. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  7096. // virtual base.
  7097. if ((!B.getType()->isDependentType() &&
  7098. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  7099. B.isVirtual()) {
  7100. PrintDiagAndRemoveAttr();
  7101. return;
  7102. }
  7103. }
  7104. for (const auto *FD : RD.fields()) {
  7105. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  7106. // non-trivial for the purpose of calls.
  7107. QualType FT = FD->getType();
  7108. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  7109. PrintDiagAndRemoveAttr();
  7110. return;
  7111. }
  7112. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  7113. if (!RT->isDependentType() &&
  7114. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  7115. PrintDiagAndRemoveAttr();
  7116. return;
  7117. }
  7118. }
  7119. }
  7120. void Sema::ActOnFinishCXXMemberSpecification(
  7121. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  7122. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  7123. if (!TagDecl)
  7124. return;
  7125. AdjustDeclIfTemplate(TagDecl);
  7126. for (const ParsedAttr &AL : AttrList) {
  7127. if (AL.getKind() != ParsedAttr::AT_Visibility)
  7128. continue;
  7129. AL.setInvalid();
  7130. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
  7131. }
  7132. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  7133. // strict aliasing violation!
  7134. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  7135. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  7136. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  7137. }
  7138. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  7139. /// special functions, such as the default constructor, copy
  7140. /// constructor, or destructor, to the given C++ class (C++
  7141. /// [special]p1). This routine can only be executed just before the
  7142. /// definition of the class is complete.
  7143. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  7144. if (ClassDecl->needsImplicitDefaultConstructor()) {
  7145. ++getASTContext().NumImplicitDefaultConstructors;
  7146. if (ClassDecl->hasInheritedConstructor())
  7147. DeclareImplicitDefaultConstructor(ClassDecl);
  7148. }
  7149. if (ClassDecl->needsImplicitCopyConstructor()) {
  7150. ++getASTContext().NumImplicitCopyConstructors;
  7151. // If the properties or semantics of the copy constructor couldn't be
  7152. // determined while the class was being declared, force a declaration
  7153. // of it now.
  7154. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  7155. ClassDecl->hasInheritedConstructor())
  7156. DeclareImplicitCopyConstructor(ClassDecl);
  7157. // For the MS ABI we need to know whether the copy ctor is deleted. A
  7158. // prerequisite for deleting the implicit copy ctor is that the class has a
  7159. // move ctor or move assignment that is either user-declared or whose
  7160. // semantics are inherited from a subobject. FIXME: We should provide a more
  7161. // direct way for CodeGen to ask whether the constructor was deleted.
  7162. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  7163. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  7164. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7165. ClassDecl->hasUserDeclaredMoveAssignment() ||
  7166. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  7167. DeclareImplicitCopyConstructor(ClassDecl);
  7168. }
  7169. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  7170. ++getASTContext().NumImplicitMoveConstructors;
  7171. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7172. ClassDecl->hasInheritedConstructor())
  7173. DeclareImplicitMoveConstructor(ClassDecl);
  7174. }
  7175. if (ClassDecl->needsImplicitCopyAssignment()) {
  7176. ++getASTContext().NumImplicitCopyAssignmentOperators;
  7177. // If we have a dynamic class, then the copy assignment operator may be
  7178. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  7179. // it shows up in the right place in the vtable and that we diagnose
  7180. // problems with the implicit exception specification.
  7181. if (ClassDecl->isDynamicClass() ||
  7182. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  7183. ClassDecl->hasInheritedAssignment())
  7184. DeclareImplicitCopyAssignment(ClassDecl);
  7185. }
  7186. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  7187. ++getASTContext().NumImplicitMoveAssignmentOperators;
  7188. // Likewise for the move assignment operator.
  7189. if (ClassDecl->isDynamicClass() ||
  7190. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  7191. ClassDecl->hasInheritedAssignment())
  7192. DeclareImplicitMoveAssignment(ClassDecl);
  7193. }
  7194. if (ClassDecl->needsImplicitDestructor()) {
  7195. ++getASTContext().NumImplicitDestructors;
  7196. // If we have a dynamic class, then the destructor may be virtual, so we
  7197. // have to declare the destructor immediately. This ensures that, e.g., it
  7198. // shows up in the right place in the vtable and that we diagnose problems
  7199. // with the implicit exception specification.
  7200. if (ClassDecl->isDynamicClass() ||
  7201. ClassDecl->needsOverloadResolutionForDestructor())
  7202. DeclareImplicitDestructor(ClassDecl);
  7203. }
  7204. }
  7205. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  7206. if (!D)
  7207. return 0;
  7208. // The order of template parameters is not important here. All names
  7209. // get added to the same scope.
  7210. SmallVector<TemplateParameterList *, 4> ParameterLists;
  7211. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  7212. D = TD->getTemplatedDecl();
  7213. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  7214. ParameterLists.push_back(PSD->getTemplateParameters());
  7215. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  7216. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  7217. ParameterLists.push_back(DD->getTemplateParameterList(i));
  7218. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7219. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  7220. ParameterLists.push_back(FTD->getTemplateParameters());
  7221. }
  7222. }
  7223. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7224. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  7225. ParameterLists.push_back(TD->getTemplateParameterList(i));
  7226. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  7227. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  7228. ParameterLists.push_back(CTD->getTemplateParameters());
  7229. }
  7230. }
  7231. unsigned Count = 0;
  7232. for (TemplateParameterList *Params : ParameterLists) {
  7233. if (Params->size() > 0)
  7234. // Ignore explicit specializations; they don't contribute to the template
  7235. // depth.
  7236. ++Count;
  7237. for (NamedDecl *Param : *Params) {
  7238. if (Param->getDeclName()) {
  7239. S->AddDecl(Param);
  7240. IdResolver.AddDecl(Param);
  7241. }
  7242. }
  7243. }
  7244. return Count;
  7245. }
  7246. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7247. if (!RecordD) return;
  7248. AdjustDeclIfTemplate(RecordD);
  7249. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  7250. PushDeclContext(S, Record);
  7251. }
  7252. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7253. if (!RecordD) return;
  7254. PopDeclContext();
  7255. }
  7256. /// This is used to implement the constant expression evaluation part of the
  7257. /// attribute enable_if extension. There is nothing in standard C++ which would
  7258. /// require reentering parameters.
  7259. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  7260. if (!Param)
  7261. return;
  7262. S->AddDecl(Param);
  7263. if (Param->getDeclName())
  7264. IdResolver.AddDecl(Param);
  7265. }
  7266. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  7267. /// parsing a top-level (non-nested) C++ class, and we are now
  7268. /// parsing those parts of the given Method declaration that could
  7269. /// not be parsed earlier (C++ [class.mem]p2), such as default
  7270. /// arguments. This action should enter the scope of the given
  7271. /// Method declaration as if we had just parsed the qualified method
  7272. /// name. However, it should not bring the parameters into scope;
  7273. /// that will be performed by ActOnDelayedCXXMethodParameter.
  7274. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7275. }
  7276. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  7277. /// C++ method declaration. We're (re-)introducing the given
  7278. /// function parameter into scope for use in parsing later parts of
  7279. /// the method declaration. For example, we could see an
  7280. /// ActOnParamDefaultArgument event for this parameter.
  7281. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  7282. if (!ParamD)
  7283. return;
  7284. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  7285. // If this parameter has an unparsed default argument, clear it out
  7286. // to make way for the parsed default argument.
  7287. if (Param->hasUnparsedDefaultArg())
  7288. Param->setDefaultArg(nullptr);
  7289. S->AddDecl(Param);
  7290. if (Param->getDeclName())
  7291. IdResolver.AddDecl(Param);
  7292. }
  7293. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  7294. /// processing the delayed method declaration for Method. The method
  7295. /// declaration is now considered finished. There may be a separate
  7296. /// ActOnStartOfFunctionDef action later (not necessarily
  7297. /// immediately!) for this method, if it was also defined inside the
  7298. /// class body.
  7299. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7300. if (!MethodD)
  7301. return;
  7302. AdjustDeclIfTemplate(MethodD);
  7303. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  7304. // Now that we have our default arguments, check the constructor
  7305. // again. It could produce additional diagnostics or affect whether
  7306. // the class has implicitly-declared destructors, among other
  7307. // things.
  7308. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  7309. CheckConstructor(Constructor);
  7310. // Check the default arguments, which we may have added.
  7311. if (!Method->isInvalidDecl())
  7312. CheckCXXDefaultArguments(Method);
  7313. }
  7314. // Emit the given diagnostic for each non-address-space qualifier.
  7315. // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
  7316. static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
  7317. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7318. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  7319. bool DiagOccured = false;
  7320. FTI.MethodQualifiers->forEachQualifier(
  7321. [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
  7322. SourceLocation SL) {
  7323. // This diagnostic should be emitted on any qualifier except an addr
  7324. // space qualifier. However, forEachQualifier currently doesn't visit
  7325. // addr space qualifiers, so there's no way to write this condition
  7326. // right now; we just diagnose on everything.
  7327. S.Diag(SL, DiagID) << QualName << SourceRange(SL);
  7328. DiagOccured = true;
  7329. });
  7330. if (DiagOccured)
  7331. D.setInvalidType();
  7332. }
  7333. }
  7334. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  7335. /// the well-formedness of the constructor declarator @p D with type @p
  7336. /// R. If there are any errors in the declarator, this routine will
  7337. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7338. /// will be updated to reflect a well-formed type for the constructor and
  7339. /// returned.
  7340. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7341. StorageClass &SC) {
  7342. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7343. // C++ [class.ctor]p3:
  7344. // A constructor shall not be virtual (10.3) or static (9.4). A
  7345. // constructor can be invoked for a const, volatile or const
  7346. // volatile object. A constructor shall not be declared const,
  7347. // volatile, or const volatile (9.3.2).
  7348. if (isVirtual) {
  7349. if (!D.isInvalidType())
  7350. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7351. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7352. << SourceRange(D.getIdentifierLoc());
  7353. D.setInvalidType();
  7354. }
  7355. if (SC == SC_Static) {
  7356. if (!D.isInvalidType())
  7357. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7358. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7359. << SourceRange(D.getIdentifierLoc());
  7360. D.setInvalidType();
  7361. SC = SC_None;
  7362. }
  7363. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7364. diagnoseIgnoredQualifiers(
  7365. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7366. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7367. D.getDeclSpec().getRestrictSpecLoc(),
  7368. D.getDeclSpec().getAtomicSpecLoc());
  7369. D.setInvalidType();
  7370. }
  7371. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
  7372. // C++0x [class.ctor]p4:
  7373. // A constructor shall not be declared with a ref-qualifier.
  7374. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7375. if (FTI.hasRefQualifier()) {
  7376. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7377. << FTI.RefQualifierIsLValueRef
  7378. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7379. D.setInvalidType();
  7380. }
  7381. // Rebuild the function type "R" without any type qualifiers (in
  7382. // case any of the errors above fired) and with "void" as the
  7383. // return type, since constructors don't have return types.
  7384. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7385. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7386. return R;
  7387. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7388. EPI.TypeQuals = Qualifiers();
  7389. EPI.RefQualifier = RQ_None;
  7390. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7391. }
  7392. /// CheckConstructor - Checks a fully-formed constructor for
  7393. /// well-formedness, issuing any diagnostics required. Returns true if
  7394. /// the constructor declarator is invalid.
  7395. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7396. CXXRecordDecl *ClassDecl
  7397. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7398. if (!ClassDecl)
  7399. return Constructor->setInvalidDecl();
  7400. // C++ [class.copy]p3:
  7401. // A declaration of a constructor for a class X is ill-formed if
  7402. // its first parameter is of type (optionally cv-qualified) X and
  7403. // either there are no other parameters or else all other
  7404. // parameters have default arguments.
  7405. if (!Constructor->isInvalidDecl() &&
  7406. ((Constructor->getNumParams() == 1) ||
  7407. (Constructor->getNumParams() > 1 &&
  7408. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7409. Constructor->getTemplateSpecializationKind()
  7410. != TSK_ImplicitInstantiation) {
  7411. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7412. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7413. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7414. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7415. const char *ConstRef
  7416. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7417. : " const &";
  7418. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7419. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7420. // FIXME: Rather that making the constructor invalid, we should endeavor
  7421. // to fix the type.
  7422. Constructor->setInvalidDecl();
  7423. }
  7424. }
  7425. }
  7426. /// CheckDestructor - Checks a fully-formed destructor definition for
  7427. /// well-formedness, issuing any diagnostics required. Returns true
  7428. /// on error.
  7429. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7430. CXXRecordDecl *RD = Destructor->getParent();
  7431. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7432. SourceLocation Loc;
  7433. if (!Destructor->isImplicit())
  7434. Loc = Destructor->getLocation();
  7435. else
  7436. Loc = RD->getLocation();
  7437. // If we have a virtual destructor, look up the deallocation function
  7438. if (FunctionDecl *OperatorDelete =
  7439. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7440. Expr *ThisArg = nullptr;
  7441. // If the notional 'delete this' expression requires a non-trivial
  7442. // conversion from 'this' to the type of a destroying operator delete's
  7443. // first parameter, perform that conversion now.
  7444. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7445. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7446. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7447. // C++ [class.dtor]p13:
  7448. // ... as if for the expression 'delete this' appearing in a
  7449. // non-virtual destructor of the destructor's class.
  7450. ContextRAII SwitchContext(*this, Destructor);
  7451. ExprResult This =
  7452. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7453. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7454. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7455. if (This.isInvalid()) {
  7456. // FIXME: Register this as a context note so that it comes out
  7457. // in the right order.
  7458. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7459. return true;
  7460. }
  7461. ThisArg = This.get();
  7462. }
  7463. }
  7464. DiagnoseUseOfDecl(OperatorDelete, Loc);
  7465. MarkFunctionReferenced(Loc, OperatorDelete);
  7466. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7467. }
  7468. }
  7469. return false;
  7470. }
  7471. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7472. /// the well-formednes of the destructor declarator @p D with type @p
  7473. /// R. If there are any errors in the declarator, this routine will
  7474. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7475. /// will be updated to reflect a well-formed type for the destructor and
  7476. /// returned.
  7477. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7478. StorageClass& SC) {
  7479. // C++ [class.dtor]p1:
  7480. // [...] A typedef-name that names a class is a class-name
  7481. // (7.1.3); however, a typedef-name that names a class shall not
  7482. // be used as the identifier in the declarator for a destructor
  7483. // declaration.
  7484. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7485. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7486. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7487. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7488. else if (const TemplateSpecializationType *TST =
  7489. DeclaratorType->getAs<TemplateSpecializationType>())
  7490. if (TST->isTypeAlias())
  7491. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7492. << DeclaratorType << 1;
  7493. // C++ [class.dtor]p2:
  7494. // A destructor is used to destroy objects of its class type. A
  7495. // destructor takes no parameters, and no return type can be
  7496. // specified for it (not even void). The address of a destructor
  7497. // shall not be taken. A destructor shall not be static. A
  7498. // destructor can be invoked for a const, volatile or const
  7499. // volatile object. A destructor shall not be declared const,
  7500. // volatile or const volatile (9.3.2).
  7501. if (SC == SC_Static) {
  7502. if (!D.isInvalidType())
  7503. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7504. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7505. << SourceRange(D.getIdentifierLoc())
  7506. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7507. SC = SC_None;
  7508. }
  7509. if (!D.isInvalidType()) {
  7510. // Destructors don't have return types, but the parser will
  7511. // happily parse something like:
  7512. //
  7513. // class X {
  7514. // float ~X();
  7515. // };
  7516. //
  7517. // The return type will be eliminated later.
  7518. if (D.getDeclSpec().hasTypeSpecifier())
  7519. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7520. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7521. << SourceRange(D.getIdentifierLoc());
  7522. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7523. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7524. SourceLocation(),
  7525. D.getDeclSpec().getConstSpecLoc(),
  7526. D.getDeclSpec().getVolatileSpecLoc(),
  7527. D.getDeclSpec().getRestrictSpecLoc(),
  7528. D.getDeclSpec().getAtomicSpecLoc());
  7529. D.setInvalidType();
  7530. }
  7531. }
  7532. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
  7533. // C++0x [class.dtor]p2:
  7534. // A destructor shall not be declared with a ref-qualifier.
  7535. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7536. if (FTI.hasRefQualifier()) {
  7537. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7538. << FTI.RefQualifierIsLValueRef
  7539. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7540. D.setInvalidType();
  7541. }
  7542. // Make sure we don't have any parameters.
  7543. if (FTIHasNonVoidParameters(FTI)) {
  7544. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7545. // Delete the parameters.
  7546. FTI.freeParams();
  7547. D.setInvalidType();
  7548. }
  7549. // Make sure the destructor isn't variadic.
  7550. if (FTI.isVariadic) {
  7551. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7552. D.setInvalidType();
  7553. }
  7554. // Rebuild the function type "R" without any type qualifiers or
  7555. // parameters (in case any of the errors above fired) and with
  7556. // "void" as the return type, since destructors don't have return
  7557. // types.
  7558. if (!D.isInvalidType())
  7559. return R;
  7560. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7561. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7562. EPI.Variadic = false;
  7563. EPI.TypeQuals = Qualifiers();
  7564. EPI.RefQualifier = RQ_None;
  7565. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7566. }
  7567. static void extendLeft(SourceRange &R, SourceRange Before) {
  7568. if (Before.isInvalid())
  7569. return;
  7570. R.setBegin(Before.getBegin());
  7571. if (R.getEnd().isInvalid())
  7572. R.setEnd(Before.getEnd());
  7573. }
  7574. static void extendRight(SourceRange &R, SourceRange After) {
  7575. if (After.isInvalid())
  7576. return;
  7577. if (R.getBegin().isInvalid())
  7578. R.setBegin(After.getBegin());
  7579. R.setEnd(After.getEnd());
  7580. }
  7581. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7582. /// well-formednes of the conversion function declarator @p D with
  7583. /// type @p R. If there are any errors in the declarator, this routine
  7584. /// will emit diagnostics and return true. Otherwise, it will return
  7585. /// false. Either way, the type @p R will be updated to reflect a
  7586. /// well-formed type for the conversion operator.
  7587. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7588. StorageClass& SC) {
  7589. // C++ [class.conv.fct]p1:
  7590. // Neither parameter types nor return type can be specified. The
  7591. // type of a conversion function (8.3.5) is "function taking no
  7592. // parameter returning conversion-type-id."
  7593. if (SC == SC_Static) {
  7594. if (!D.isInvalidType())
  7595. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7596. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7597. << D.getName().getSourceRange();
  7598. D.setInvalidType();
  7599. SC = SC_None;
  7600. }
  7601. TypeSourceInfo *ConvTSI = nullptr;
  7602. QualType ConvType =
  7603. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7604. const DeclSpec &DS = D.getDeclSpec();
  7605. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7606. // Conversion functions don't have return types, but the parser will
  7607. // happily parse something like:
  7608. //
  7609. // class X {
  7610. // float operator bool();
  7611. // };
  7612. //
  7613. // The return type will be changed later anyway.
  7614. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7615. << SourceRange(DS.getTypeSpecTypeLoc())
  7616. << SourceRange(D.getIdentifierLoc());
  7617. D.setInvalidType();
  7618. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7619. // It's also plausible that the user writes type qualifiers in the wrong
  7620. // place, such as:
  7621. // struct S { const operator int(); };
  7622. // FIXME: we could provide a fixit to move the qualifiers onto the
  7623. // conversion type.
  7624. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7625. << SourceRange(D.getIdentifierLoc()) << 0;
  7626. D.setInvalidType();
  7627. }
  7628. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7629. // Make sure we don't have any parameters.
  7630. if (Proto->getNumParams() > 0) {
  7631. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7632. // Delete the parameters.
  7633. D.getFunctionTypeInfo().freeParams();
  7634. D.setInvalidType();
  7635. } else if (Proto->isVariadic()) {
  7636. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7637. D.setInvalidType();
  7638. }
  7639. // Diagnose "&operator bool()" and other such nonsense. This
  7640. // is actually a gcc extension which we don't support.
  7641. if (Proto->getReturnType() != ConvType) {
  7642. bool NeedsTypedef = false;
  7643. SourceRange Before, After;
  7644. // Walk the chunks and extract information on them for our diagnostic.
  7645. bool PastFunctionChunk = false;
  7646. for (auto &Chunk : D.type_objects()) {
  7647. switch (Chunk.Kind) {
  7648. case DeclaratorChunk::Function:
  7649. if (!PastFunctionChunk) {
  7650. if (Chunk.Fun.HasTrailingReturnType) {
  7651. TypeSourceInfo *TRT = nullptr;
  7652. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7653. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7654. }
  7655. PastFunctionChunk = true;
  7656. break;
  7657. }
  7658. LLVM_FALLTHROUGH;
  7659. case DeclaratorChunk::Array:
  7660. NeedsTypedef = true;
  7661. extendRight(After, Chunk.getSourceRange());
  7662. break;
  7663. case DeclaratorChunk::Pointer:
  7664. case DeclaratorChunk::BlockPointer:
  7665. case DeclaratorChunk::Reference:
  7666. case DeclaratorChunk::MemberPointer:
  7667. case DeclaratorChunk::Pipe:
  7668. extendLeft(Before, Chunk.getSourceRange());
  7669. break;
  7670. case DeclaratorChunk::Paren:
  7671. extendLeft(Before, Chunk.Loc);
  7672. extendRight(After, Chunk.EndLoc);
  7673. break;
  7674. }
  7675. }
  7676. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7677. After.isValid() ? After.getBegin() :
  7678. D.getIdentifierLoc();
  7679. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7680. DB << Before << After;
  7681. if (!NeedsTypedef) {
  7682. DB << /*don't need a typedef*/0;
  7683. // If we can provide a correct fix-it hint, do so.
  7684. if (After.isInvalid() && ConvTSI) {
  7685. SourceLocation InsertLoc =
  7686. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7687. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7688. << FixItHint::CreateInsertionFromRange(
  7689. InsertLoc, CharSourceRange::getTokenRange(Before))
  7690. << FixItHint::CreateRemoval(Before);
  7691. }
  7692. } else if (!Proto->getReturnType()->isDependentType()) {
  7693. DB << /*typedef*/1 << Proto->getReturnType();
  7694. } else if (getLangOpts().CPlusPlus11) {
  7695. DB << /*alias template*/2 << Proto->getReturnType();
  7696. } else {
  7697. DB << /*might not be fixable*/3;
  7698. }
  7699. // Recover by incorporating the other type chunks into the result type.
  7700. // Note, this does *not* change the name of the function. This is compatible
  7701. // with the GCC extension:
  7702. // struct S { &operator int(); } s;
  7703. // int &r = s.operator int(); // ok in GCC
  7704. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7705. ConvType = Proto->getReturnType();
  7706. }
  7707. // C++ [class.conv.fct]p4:
  7708. // The conversion-type-id shall not represent a function type nor
  7709. // an array type.
  7710. if (ConvType->isArrayType()) {
  7711. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7712. ConvType = Context.getPointerType(ConvType);
  7713. D.setInvalidType();
  7714. } else if (ConvType->isFunctionType()) {
  7715. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7716. ConvType = Context.getPointerType(ConvType);
  7717. D.setInvalidType();
  7718. }
  7719. // Rebuild the function type "R" without any parameters (in case any
  7720. // of the errors above fired) and with the conversion type as the
  7721. // return type.
  7722. if (D.isInvalidType())
  7723. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7724. // C++0x explicit conversion operators.
  7725. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
  7726. Diag(DS.getExplicitSpecLoc(),
  7727. getLangOpts().CPlusPlus11
  7728. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7729. : diag::ext_explicit_conversion_functions)
  7730. << SourceRange(DS.getExplicitSpecRange());
  7731. }
  7732. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7733. /// the declaration of the given C++ conversion function. This routine
  7734. /// is responsible for recording the conversion function in the C++
  7735. /// class, if possible.
  7736. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7737. assert(Conversion && "Expected to receive a conversion function declaration");
  7738. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7739. // Make sure we aren't redeclaring the conversion function.
  7740. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7741. // C++ [class.conv.fct]p1:
  7742. // [...] A conversion function is never used to convert a
  7743. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7744. // same object type (or a reference to it), to a (possibly
  7745. // cv-qualified) base class of that type (or a reference to it),
  7746. // or to (possibly cv-qualified) void.
  7747. // FIXME: Suppress this warning if the conversion function ends up being a
  7748. // virtual function that overrides a virtual function in a base class.
  7749. QualType ClassType
  7750. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7751. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7752. ConvType = ConvTypeRef->getPointeeType();
  7753. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7754. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7755. /* Suppress diagnostics for instantiations. */;
  7756. else if (ConvType->isRecordType()) {
  7757. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7758. if (ConvType == ClassType)
  7759. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7760. << ClassType;
  7761. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7762. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7763. << ClassType << ConvType;
  7764. } else if (ConvType->isVoidType()) {
  7765. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7766. << ClassType << ConvType;
  7767. }
  7768. if (FunctionTemplateDecl *ConversionTemplate
  7769. = Conversion->getDescribedFunctionTemplate())
  7770. return ConversionTemplate;
  7771. return Conversion;
  7772. }
  7773. namespace {
  7774. /// Utility class to accumulate and print a diagnostic listing the invalid
  7775. /// specifier(s) on a declaration.
  7776. struct BadSpecifierDiagnoser {
  7777. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7778. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7779. ~BadSpecifierDiagnoser() {
  7780. Diagnostic << Specifiers;
  7781. }
  7782. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7783. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7784. }
  7785. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7786. return check(SpecLoc,
  7787. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7788. }
  7789. void check(SourceLocation SpecLoc, const char *Spec) {
  7790. if (SpecLoc.isInvalid()) return;
  7791. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7792. if (!Specifiers.empty()) Specifiers += " ";
  7793. Specifiers += Spec;
  7794. }
  7795. Sema &S;
  7796. Sema::SemaDiagnosticBuilder Diagnostic;
  7797. std::string Specifiers;
  7798. };
  7799. }
  7800. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7801. /// These aren't actually declarators in the grammar, so we need to check that
  7802. /// the user didn't specify any pieces that are not part of the deduction-guide
  7803. /// grammar.
  7804. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7805. StorageClass &SC) {
  7806. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7807. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7808. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7809. // C++ [temp.deduct.guide]p3:
  7810. // A deduction-gide shall be declared in the same scope as the
  7811. // corresponding class template.
  7812. if (!CurContext->getRedeclContext()->Equals(
  7813. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7814. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7815. << GuidedTemplateDecl;
  7816. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7817. }
  7818. auto &DS = D.getMutableDeclSpec();
  7819. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7820. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7821. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7822. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  7823. BadSpecifierDiagnoser Diagnoser(
  7824. *this, D.getIdentifierLoc(),
  7825. diag::err_deduction_guide_invalid_specifier);
  7826. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7827. DS.ClearStorageClassSpecs();
  7828. SC = SC_None;
  7829. // 'explicit' is permitted.
  7830. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7831. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7832. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7833. DS.ClearConstexprSpec();
  7834. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7835. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7836. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7837. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7838. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7839. DS.ClearTypeQualifiers();
  7840. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7841. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7842. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7843. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7844. DS.ClearTypeSpecType();
  7845. }
  7846. if (D.isInvalidType())
  7847. return;
  7848. // Check the declarator is simple enough.
  7849. bool FoundFunction = false;
  7850. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7851. if (Chunk.Kind == DeclaratorChunk::Paren)
  7852. continue;
  7853. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7854. Diag(D.getDeclSpec().getBeginLoc(),
  7855. diag::err_deduction_guide_with_complex_decl)
  7856. << D.getSourceRange();
  7857. break;
  7858. }
  7859. if (!Chunk.Fun.hasTrailingReturnType()) {
  7860. Diag(D.getName().getBeginLoc(),
  7861. diag::err_deduction_guide_no_trailing_return_type);
  7862. break;
  7863. }
  7864. // Check that the return type is written as a specialization of
  7865. // the template specified as the deduction-guide's name.
  7866. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7867. TypeSourceInfo *TSI = nullptr;
  7868. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7869. assert(TSI && "deduction guide has valid type but invalid return type?");
  7870. bool AcceptableReturnType = false;
  7871. bool MightInstantiateToSpecialization = false;
  7872. if (auto RetTST =
  7873. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7874. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7875. bool TemplateMatches =
  7876. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7877. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7878. AcceptableReturnType = true;
  7879. else {
  7880. // This could still instantiate to the right type, unless we know it
  7881. // names the wrong class template.
  7882. auto *TD = SpecifiedName.getAsTemplateDecl();
  7883. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7884. !TemplateMatches);
  7885. }
  7886. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7887. MightInstantiateToSpecialization = true;
  7888. }
  7889. if (!AcceptableReturnType) {
  7890. Diag(TSI->getTypeLoc().getBeginLoc(),
  7891. diag::err_deduction_guide_bad_trailing_return_type)
  7892. << GuidedTemplate << TSI->getType()
  7893. << MightInstantiateToSpecialization
  7894. << TSI->getTypeLoc().getSourceRange();
  7895. }
  7896. // Keep going to check that we don't have any inner declarator pieces (we
  7897. // could still have a function returning a pointer to a function).
  7898. FoundFunction = true;
  7899. }
  7900. if (D.isFunctionDefinition())
  7901. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7902. }
  7903. //===----------------------------------------------------------------------===//
  7904. // Namespace Handling
  7905. //===----------------------------------------------------------------------===//
  7906. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7907. /// reopened.
  7908. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7909. SourceLocation Loc,
  7910. IdentifierInfo *II, bool *IsInline,
  7911. NamespaceDecl *PrevNS) {
  7912. assert(*IsInline != PrevNS->isInline());
  7913. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7914. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7915. // inline namespaces, with the intention of bringing names into namespace std.
  7916. //
  7917. // We support this just well enough to get that case working; this is not
  7918. // sufficient to support reopening namespaces as inline in general.
  7919. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7920. S.getSourceManager().isInSystemHeader(Loc)) {
  7921. // Mark all prior declarations of the namespace as inline.
  7922. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7923. NS = NS->getPreviousDecl())
  7924. NS->setInline(*IsInline);
  7925. // Patch up the lookup table for the containing namespace. This isn't really
  7926. // correct, but it's good enough for this particular case.
  7927. for (auto *I : PrevNS->decls())
  7928. if (auto *ND = dyn_cast<NamedDecl>(I))
  7929. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7930. return;
  7931. }
  7932. if (PrevNS->isInline())
  7933. // The user probably just forgot the 'inline', so suggest that it
  7934. // be added back.
  7935. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7936. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7937. else
  7938. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7939. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7940. *IsInline = PrevNS->isInline();
  7941. }
  7942. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7943. /// definition.
  7944. Decl *Sema::ActOnStartNamespaceDef(
  7945. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7946. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7947. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7948. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7949. // For anonymous namespace, take the location of the left brace.
  7950. SourceLocation Loc = II ? IdentLoc : LBrace;
  7951. bool IsInline = InlineLoc.isValid();
  7952. bool IsInvalid = false;
  7953. bool IsStd = false;
  7954. bool AddToKnown = false;
  7955. Scope *DeclRegionScope = NamespcScope->getParent();
  7956. NamespaceDecl *PrevNS = nullptr;
  7957. if (II) {
  7958. // C++ [namespace.def]p2:
  7959. // The identifier in an original-namespace-definition shall not
  7960. // have been previously defined in the declarative region in
  7961. // which the original-namespace-definition appears. The
  7962. // identifier in an original-namespace-definition is the name of
  7963. // the namespace. Subsequently in that declarative region, it is
  7964. // treated as an original-namespace-name.
  7965. //
  7966. // Since namespace names are unique in their scope, and we don't
  7967. // look through using directives, just look for any ordinary names
  7968. // as if by qualified name lookup.
  7969. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7970. ForExternalRedeclaration);
  7971. LookupQualifiedName(R, CurContext->getRedeclContext());
  7972. NamedDecl *PrevDecl =
  7973. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7974. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7975. if (PrevNS) {
  7976. // This is an extended namespace definition.
  7977. if (IsInline != PrevNS->isInline())
  7978. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7979. &IsInline, PrevNS);
  7980. } else if (PrevDecl) {
  7981. // This is an invalid name redefinition.
  7982. Diag(Loc, diag::err_redefinition_different_kind)
  7983. << II;
  7984. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7985. IsInvalid = true;
  7986. // Continue on to push Namespc as current DeclContext and return it.
  7987. } else if (II->isStr("std") &&
  7988. CurContext->getRedeclContext()->isTranslationUnit()) {
  7989. // This is the first "real" definition of the namespace "std", so update
  7990. // our cache of the "std" namespace to point at this definition.
  7991. PrevNS = getStdNamespace();
  7992. IsStd = true;
  7993. AddToKnown = !IsInline;
  7994. } else {
  7995. // We've seen this namespace for the first time.
  7996. AddToKnown = !IsInline;
  7997. }
  7998. } else {
  7999. // Anonymous namespaces.
  8000. // Determine whether the parent already has an anonymous namespace.
  8001. DeclContext *Parent = CurContext->getRedeclContext();
  8002. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  8003. PrevNS = TU->getAnonymousNamespace();
  8004. } else {
  8005. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  8006. PrevNS = ND->getAnonymousNamespace();
  8007. }
  8008. if (PrevNS && IsInline != PrevNS->isInline())
  8009. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  8010. &IsInline, PrevNS);
  8011. }
  8012. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  8013. StartLoc, Loc, II, PrevNS);
  8014. if (IsInvalid)
  8015. Namespc->setInvalidDecl();
  8016. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  8017. AddPragmaAttributes(DeclRegionScope, Namespc);
  8018. // FIXME: Should we be merging attributes?
  8019. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  8020. PushNamespaceVisibilityAttr(Attr, Loc);
  8021. if (IsStd)
  8022. StdNamespace = Namespc;
  8023. if (AddToKnown)
  8024. KnownNamespaces[Namespc] = false;
  8025. if (II) {
  8026. PushOnScopeChains(Namespc, DeclRegionScope);
  8027. } else {
  8028. // Link the anonymous namespace into its parent.
  8029. DeclContext *Parent = CurContext->getRedeclContext();
  8030. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  8031. TU->setAnonymousNamespace(Namespc);
  8032. } else {
  8033. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  8034. }
  8035. CurContext->addDecl(Namespc);
  8036. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  8037. // behaves as if it were replaced by
  8038. // namespace unique { /* empty body */ }
  8039. // using namespace unique;
  8040. // namespace unique { namespace-body }
  8041. // where all occurrences of 'unique' in a translation unit are
  8042. // replaced by the same identifier and this identifier differs
  8043. // from all other identifiers in the entire program.
  8044. // We just create the namespace with an empty name and then add an
  8045. // implicit using declaration, just like the standard suggests.
  8046. //
  8047. // CodeGen enforces the "universally unique" aspect by giving all
  8048. // declarations semantically contained within an anonymous
  8049. // namespace internal linkage.
  8050. if (!PrevNS) {
  8051. UD = UsingDirectiveDecl::Create(Context, Parent,
  8052. /* 'using' */ LBrace,
  8053. /* 'namespace' */ SourceLocation(),
  8054. /* qualifier */ NestedNameSpecifierLoc(),
  8055. /* identifier */ SourceLocation(),
  8056. Namespc,
  8057. /* Ancestor */ Parent);
  8058. UD->setImplicit();
  8059. Parent->addDecl(UD);
  8060. }
  8061. }
  8062. ActOnDocumentableDecl(Namespc);
  8063. // Although we could have an invalid decl (i.e. the namespace name is a
  8064. // redefinition), push it as current DeclContext and try to continue parsing.
  8065. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  8066. // for the namespace has the declarations that showed up in that particular
  8067. // namespace definition.
  8068. PushDeclContext(NamespcScope, Namespc);
  8069. return Namespc;
  8070. }
  8071. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  8072. /// is a namespace alias, returns the namespace it points to.
  8073. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  8074. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  8075. return AD->getNamespace();
  8076. return dyn_cast_or_null<NamespaceDecl>(D);
  8077. }
  8078. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  8079. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  8080. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  8081. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  8082. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  8083. Namespc->setRBraceLoc(RBrace);
  8084. PopDeclContext();
  8085. if (Namespc->hasAttr<VisibilityAttr>())
  8086. PopPragmaVisibility(true, RBrace);
  8087. // If this namespace contains an export-declaration, export it now.
  8088. if (DeferredExportedNamespaces.erase(Namespc))
  8089. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  8090. }
  8091. CXXRecordDecl *Sema::getStdBadAlloc() const {
  8092. return cast_or_null<CXXRecordDecl>(
  8093. StdBadAlloc.get(Context.getExternalSource()));
  8094. }
  8095. EnumDecl *Sema::getStdAlignValT() const {
  8096. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  8097. }
  8098. NamespaceDecl *Sema::getStdNamespace() const {
  8099. return cast_or_null<NamespaceDecl>(
  8100. StdNamespace.get(Context.getExternalSource()));
  8101. }
  8102. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  8103. if (!StdExperimentalNamespaceCache) {
  8104. if (auto Std = getStdNamespace()) {
  8105. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  8106. SourceLocation(), LookupNamespaceName);
  8107. if (!LookupQualifiedName(Result, Std) ||
  8108. !(StdExperimentalNamespaceCache =
  8109. Result.getAsSingle<NamespaceDecl>()))
  8110. Result.suppressDiagnostics();
  8111. }
  8112. }
  8113. return StdExperimentalNamespaceCache;
  8114. }
  8115. namespace {
  8116. enum UnsupportedSTLSelect {
  8117. USS_InvalidMember,
  8118. USS_MissingMember,
  8119. USS_NonTrivial,
  8120. USS_Other
  8121. };
  8122. struct InvalidSTLDiagnoser {
  8123. Sema &S;
  8124. SourceLocation Loc;
  8125. QualType TyForDiags;
  8126. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  8127. const VarDecl *VD = nullptr) {
  8128. {
  8129. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  8130. << TyForDiags << ((int)Sel);
  8131. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  8132. assert(!Name.empty());
  8133. D << Name;
  8134. }
  8135. }
  8136. if (Sel == USS_InvalidMember) {
  8137. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  8138. << VD << VD->getSourceRange();
  8139. }
  8140. return QualType();
  8141. }
  8142. };
  8143. } // namespace
  8144. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  8145. SourceLocation Loc) {
  8146. assert(getLangOpts().CPlusPlus &&
  8147. "Looking for comparison category type outside of C++.");
  8148. // Check if we've already successfully checked the comparison category type
  8149. // before. If so, skip checking it again.
  8150. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  8151. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  8152. return Info->getType();
  8153. // If lookup failed
  8154. if (!Info) {
  8155. std::string NameForDiags = "std::";
  8156. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  8157. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  8158. << NameForDiags;
  8159. return QualType();
  8160. }
  8161. assert(Info->Kind == Kind);
  8162. assert(Info->Record);
  8163. // Update the Record decl in case we encountered a forward declaration on our
  8164. // first pass. FIXME: This is a bit of a hack.
  8165. if (Info->Record->hasDefinition())
  8166. Info->Record = Info->Record->getDefinition();
  8167. // Use an elaborated type for diagnostics which has a name containing the
  8168. // prepended 'std' namespace but not any inline namespace names.
  8169. QualType TyForDiags = [&]() {
  8170. auto *NNS =
  8171. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  8172. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  8173. }();
  8174. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  8175. return QualType();
  8176. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  8177. if (!Info->Record->isTriviallyCopyable())
  8178. return UnsupportedSTLError(USS_NonTrivial);
  8179. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  8180. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  8181. // Tolerate empty base classes.
  8182. if (Base->isEmpty())
  8183. continue;
  8184. // Reject STL implementations which have at least one non-empty base.
  8185. return UnsupportedSTLError();
  8186. }
  8187. // Check that the STL has implemented the types using a single integer field.
  8188. // This expectation allows better codegen for builtin operators. We require:
  8189. // (1) The class has exactly one field.
  8190. // (2) The field is an integral or enumeration type.
  8191. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  8192. if (std::distance(FIt, FEnd) != 1 ||
  8193. !FIt->getType()->isIntegralOrEnumerationType()) {
  8194. return UnsupportedSTLError();
  8195. }
  8196. // Build each of the require values and store them in Info.
  8197. for (ComparisonCategoryResult CCR :
  8198. ComparisonCategories::getPossibleResultsForType(Kind)) {
  8199. StringRef MemName = ComparisonCategories::getResultString(CCR);
  8200. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  8201. if (!ValInfo)
  8202. return UnsupportedSTLError(USS_MissingMember, MemName);
  8203. VarDecl *VD = ValInfo->VD;
  8204. assert(VD && "should not be null!");
  8205. // Attempt to diagnose reasons why the STL definition of this type
  8206. // might be foobar, including it failing to be a constant expression.
  8207. // TODO Handle more ways the lookup or result can be invalid.
  8208. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  8209. !VD->checkInitIsICE())
  8210. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  8211. // Attempt to evaluate the var decl as a constant expression and extract
  8212. // the value of its first field as a ICE. If this fails, the STL
  8213. // implementation is not supported.
  8214. if (!ValInfo->hasValidIntValue())
  8215. return UnsupportedSTLError();
  8216. MarkVariableReferenced(Loc, VD);
  8217. }
  8218. // We've successfully built the required types and expressions. Update
  8219. // the cache and return the newly cached value.
  8220. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  8221. return Info->getType();
  8222. }
  8223. /// Retrieve the special "std" namespace, which may require us to
  8224. /// implicitly define the namespace.
  8225. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  8226. if (!StdNamespace) {
  8227. // The "std" namespace has not yet been defined, so build one implicitly.
  8228. StdNamespace = NamespaceDecl::Create(Context,
  8229. Context.getTranslationUnitDecl(),
  8230. /*Inline=*/false,
  8231. SourceLocation(), SourceLocation(),
  8232. &PP.getIdentifierTable().get("std"),
  8233. /*PrevDecl=*/nullptr);
  8234. getStdNamespace()->setImplicit(true);
  8235. }
  8236. return getStdNamespace();
  8237. }
  8238. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  8239. assert(getLangOpts().CPlusPlus &&
  8240. "Looking for std::initializer_list outside of C++.");
  8241. // We're looking for implicit instantiations of
  8242. // template <typename E> class std::initializer_list.
  8243. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  8244. return false;
  8245. ClassTemplateDecl *Template = nullptr;
  8246. const TemplateArgument *Arguments = nullptr;
  8247. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  8248. ClassTemplateSpecializationDecl *Specialization =
  8249. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8250. if (!Specialization)
  8251. return false;
  8252. Template = Specialization->getSpecializedTemplate();
  8253. Arguments = Specialization->getTemplateArgs().data();
  8254. } else if (const TemplateSpecializationType *TST =
  8255. Ty->getAs<TemplateSpecializationType>()) {
  8256. Template = dyn_cast_or_null<ClassTemplateDecl>(
  8257. TST->getTemplateName().getAsTemplateDecl());
  8258. Arguments = TST->getArgs();
  8259. }
  8260. if (!Template)
  8261. return false;
  8262. if (!StdInitializerList) {
  8263. // Haven't recognized std::initializer_list yet, maybe this is it.
  8264. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  8265. if (TemplateClass->getIdentifier() !=
  8266. &PP.getIdentifierTable().get("initializer_list") ||
  8267. !getStdNamespace()->InEnclosingNamespaceSetOf(
  8268. TemplateClass->getDeclContext()))
  8269. return false;
  8270. // This is a template called std::initializer_list, but is it the right
  8271. // template?
  8272. TemplateParameterList *Params = Template->getTemplateParameters();
  8273. if (Params->getMinRequiredArguments() != 1)
  8274. return false;
  8275. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  8276. return false;
  8277. // It's the right template.
  8278. StdInitializerList = Template;
  8279. }
  8280. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  8281. return false;
  8282. // This is an instance of std::initializer_list. Find the argument type.
  8283. if (Element)
  8284. *Element = Arguments[0].getAsType();
  8285. return true;
  8286. }
  8287. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  8288. NamespaceDecl *Std = S.getStdNamespace();
  8289. if (!Std) {
  8290. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8291. return nullptr;
  8292. }
  8293. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  8294. Loc, Sema::LookupOrdinaryName);
  8295. if (!S.LookupQualifiedName(Result, Std)) {
  8296. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8297. return nullptr;
  8298. }
  8299. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  8300. if (!Template) {
  8301. Result.suppressDiagnostics();
  8302. // We found something weird. Complain about the first thing we found.
  8303. NamedDecl *Found = *Result.begin();
  8304. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  8305. return nullptr;
  8306. }
  8307. // We found some template called std::initializer_list. Now verify that it's
  8308. // correct.
  8309. TemplateParameterList *Params = Template->getTemplateParameters();
  8310. if (Params->getMinRequiredArguments() != 1 ||
  8311. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  8312. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  8313. return nullptr;
  8314. }
  8315. return Template;
  8316. }
  8317. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  8318. if (!StdInitializerList) {
  8319. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8320. if (!StdInitializerList)
  8321. return QualType();
  8322. }
  8323. TemplateArgumentListInfo Args(Loc, Loc);
  8324. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8325. Context.getTrivialTypeSourceInfo(Element,
  8326. Loc)));
  8327. return Context.getCanonicalType(
  8328. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8329. }
  8330. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8331. // C++ [dcl.init.list]p2:
  8332. // A constructor is an initializer-list constructor if its first parameter
  8333. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8334. // std::initializer_list<E> for some type E, and either there are no other
  8335. // parameters or else all other parameters have default arguments.
  8336. if (Ctor->getNumParams() < 1 ||
  8337. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8338. return false;
  8339. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8340. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8341. ArgType = RT->getPointeeType().getUnqualifiedType();
  8342. return isStdInitializerList(ArgType, nullptr);
  8343. }
  8344. /// Determine whether a using statement is in a context where it will be
  8345. /// apply in all contexts.
  8346. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8347. switch (CurContext->getDeclKind()) {
  8348. case Decl::TranslationUnit:
  8349. return true;
  8350. case Decl::LinkageSpec:
  8351. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8352. default:
  8353. return false;
  8354. }
  8355. }
  8356. namespace {
  8357. // Callback to only accept typo corrections that are namespaces.
  8358. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  8359. public:
  8360. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8361. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8362. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8363. return false;
  8364. }
  8365. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8366. return std::make_unique<NamespaceValidatorCCC>(*this);
  8367. }
  8368. };
  8369. }
  8370. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8371. CXXScopeSpec &SS,
  8372. SourceLocation IdentLoc,
  8373. IdentifierInfo *Ident) {
  8374. R.clear();
  8375. NamespaceValidatorCCC CCC{};
  8376. if (TypoCorrection Corrected =
  8377. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  8378. Sema::CTK_ErrorRecovery)) {
  8379. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8380. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8381. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8382. Ident->getName().equals(CorrectedStr);
  8383. S.diagnoseTypo(Corrected,
  8384. S.PDiag(diag::err_using_directive_member_suggest)
  8385. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8386. S.PDiag(diag::note_namespace_defined_here));
  8387. } else {
  8388. S.diagnoseTypo(Corrected,
  8389. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8390. S.PDiag(diag::note_namespace_defined_here));
  8391. }
  8392. R.addDecl(Corrected.getFoundDecl());
  8393. return true;
  8394. }
  8395. return false;
  8396. }
  8397. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8398. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8399. SourceLocation IdentLoc,
  8400. IdentifierInfo *NamespcName,
  8401. const ParsedAttributesView &AttrList) {
  8402. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8403. assert(NamespcName && "Invalid NamespcName.");
  8404. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8405. // This can only happen along a recovery path.
  8406. while (S->isTemplateParamScope())
  8407. S = S->getParent();
  8408. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8409. UsingDirectiveDecl *UDir = nullptr;
  8410. NestedNameSpecifier *Qualifier = nullptr;
  8411. if (SS.isSet())
  8412. Qualifier = SS.getScopeRep();
  8413. // Lookup namespace name.
  8414. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8415. LookupParsedName(R, S, &SS);
  8416. if (R.isAmbiguous())
  8417. return nullptr;
  8418. if (R.empty()) {
  8419. R.clear();
  8420. // Allow "using namespace std;" or "using namespace ::std;" even if
  8421. // "std" hasn't been defined yet, for GCC compatibility.
  8422. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8423. NamespcName->isStr("std")) {
  8424. Diag(IdentLoc, diag::ext_using_undefined_std);
  8425. R.addDecl(getOrCreateStdNamespace());
  8426. R.resolveKind();
  8427. }
  8428. // Otherwise, attempt typo correction.
  8429. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8430. }
  8431. if (!R.empty()) {
  8432. NamedDecl *Named = R.getRepresentativeDecl();
  8433. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8434. assert(NS && "expected namespace decl");
  8435. // The use of a nested name specifier may trigger deprecation warnings.
  8436. DiagnoseUseOfDecl(Named, IdentLoc);
  8437. // C++ [namespace.udir]p1:
  8438. // A using-directive specifies that the names in the nominated
  8439. // namespace can be used in the scope in which the
  8440. // using-directive appears after the using-directive. During
  8441. // unqualified name lookup (3.4.1), the names appear as if they
  8442. // were declared in the nearest enclosing namespace which
  8443. // contains both the using-directive and the nominated
  8444. // namespace. [Note: in this context, "contains" means "contains
  8445. // directly or indirectly". ]
  8446. // Find enclosing context containing both using-directive and
  8447. // nominated namespace.
  8448. DeclContext *CommonAncestor = NS;
  8449. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8450. CommonAncestor = CommonAncestor->getParent();
  8451. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8452. SS.getWithLocInContext(Context),
  8453. IdentLoc, Named, CommonAncestor);
  8454. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8455. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8456. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8457. }
  8458. PushUsingDirective(S, UDir);
  8459. } else {
  8460. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8461. }
  8462. if (UDir)
  8463. ProcessDeclAttributeList(S, UDir, AttrList);
  8464. return UDir;
  8465. }
  8466. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8467. // If the scope has an associated entity and the using directive is at
  8468. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8469. // its lookup structure so qualified name lookup can find it.
  8470. DeclContext *Ctx = S->getEntity();
  8471. if (Ctx && !Ctx->isFunctionOrMethod())
  8472. Ctx->addDecl(UDir);
  8473. else
  8474. // Otherwise, it is at block scope. The using-directives will affect lookup
  8475. // only to the end of the scope.
  8476. S->PushUsingDirective(UDir);
  8477. }
  8478. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8479. SourceLocation UsingLoc,
  8480. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8481. UnqualifiedId &Name,
  8482. SourceLocation EllipsisLoc,
  8483. const ParsedAttributesView &AttrList) {
  8484. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8485. if (SS.isEmpty()) {
  8486. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8487. return nullptr;
  8488. }
  8489. switch (Name.getKind()) {
  8490. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8491. case UnqualifiedIdKind::IK_Identifier:
  8492. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8493. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8494. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8495. break;
  8496. case UnqualifiedIdKind::IK_ConstructorName:
  8497. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8498. // C++11 inheriting constructors.
  8499. Diag(Name.getBeginLoc(),
  8500. getLangOpts().CPlusPlus11
  8501. ? diag::warn_cxx98_compat_using_decl_constructor
  8502. : diag::err_using_decl_constructor)
  8503. << SS.getRange();
  8504. if (getLangOpts().CPlusPlus11) break;
  8505. return nullptr;
  8506. case UnqualifiedIdKind::IK_DestructorName:
  8507. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8508. return nullptr;
  8509. case UnqualifiedIdKind::IK_TemplateId:
  8510. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8511. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8512. return nullptr;
  8513. case UnqualifiedIdKind::IK_DeductionGuideName:
  8514. llvm_unreachable("cannot parse qualified deduction guide name");
  8515. }
  8516. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8517. DeclarationName TargetName = TargetNameInfo.getName();
  8518. if (!TargetName)
  8519. return nullptr;
  8520. // Warn about access declarations.
  8521. if (UsingLoc.isInvalid()) {
  8522. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8523. ? diag::err_access_decl
  8524. : diag::warn_access_decl_deprecated)
  8525. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8526. }
  8527. if (EllipsisLoc.isInvalid()) {
  8528. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8529. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8530. return nullptr;
  8531. } else {
  8532. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8533. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8534. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8535. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8536. EllipsisLoc = SourceLocation();
  8537. }
  8538. }
  8539. NamedDecl *UD =
  8540. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8541. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8542. /*IsInstantiation*/false);
  8543. if (UD)
  8544. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8545. return UD;
  8546. }
  8547. /// Determine whether a using declaration considers the given
  8548. /// declarations as "equivalent", e.g., if they are redeclarations of
  8549. /// the same entity or are both typedefs of the same type.
  8550. static bool
  8551. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8552. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8553. return true;
  8554. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8555. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8556. return Context.hasSameType(TD1->getUnderlyingType(),
  8557. TD2->getUnderlyingType());
  8558. return false;
  8559. }
  8560. /// Determines whether to create a using shadow decl for a particular
  8561. /// decl, given the set of decls existing prior to this using lookup.
  8562. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8563. const LookupResult &Previous,
  8564. UsingShadowDecl *&PrevShadow) {
  8565. // Diagnose finding a decl which is not from a base class of the
  8566. // current class. We do this now because there are cases where this
  8567. // function will silently decide not to build a shadow decl, which
  8568. // will pre-empt further diagnostics.
  8569. //
  8570. // We don't need to do this in C++11 because we do the check once on
  8571. // the qualifier.
  8572. //
  8573. // FIXME: diagnose the following if we care enough:
  8574. // struct A { int foo; };
  8575. // struct B : A { using A::foo; };
  8576. // template <class T> struct C : A {};
  8577. // template <class T> struct D : C<T> { using B::foo; } // <---
  8578. // This is invalid (during instantiation) in C++03 because B::foo
  8579. // resolves to the using decl in B, which is not a base class of D<T>.
  8580. // We can't diagnose it immediately because C<T> is an unknown
  8581. // specialization. The UsingShadowDecl in D<T> then points directly
  8582. // to A::foo, which will look well-formed when we instantiate.
  8583. // The right solution is to not collapse the shadow-decl chain.
  8584. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8585. DeclContext *OrigDC = Orig->getDeclContext();
  8586. // Handle enums and anonymous structs.
  8587. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8588. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8589. while (OrigRec->isAnonymousStructOrUnion())
  8590. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8591. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8592. if (OrigDC == CurContext) {
  8593. Diag(Using->getLocation(),
  8594. diag::err_using_decl_nested_name_specifier_is_current_class)
  8595. << Using->getQualifierLoc().getSourceRange();
  8596. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8597. Using->setInvalidDecl();
  8598. return true;
  8599. }
  8600. Diag(Using->getQualifierLoc().getBeginLoc(),
  8601. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8602. << Using->getQualifier()
  8603. << cast<CXXRecordDecl>(CurContext)
  8604. << Using->getQualifierLoc().getSourceRange();
  8605. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8606. Using->setInvalidDecl();
  8607. return true;
  8608. }
  8609. }
  8610. if (Previous.empty()) return false;
  8611. NamedDecl *Target = Orig;
  8612. if (isa<UsingShadowDecl>(Target))
  8613. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8614. // If the target happens to be one of the previous declarations, we
  8615. // don't have a conflict.
  8616. //
  8617. // FIXME: but we might be increasing its access, in which case we
  8618. // should redeclare it.
  8619. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8620. bool FoundEquivalentDecl = false;
  8621. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8622. I != E; ++I) {
  8623. NamedDecl *D = (*I)->getUnderlyingDecl();
  8624. // We can have UsingDecls in our Previous results because we use the same
  8625. // LookupResult for checking whether the UsingDecl itself is a valid
  8626. // redeclaration.
  8627. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8628. continue;
  8629. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8630. // C++ [class.mem]p19:
  8631. // If T is the name of a class, then [every named member other than
  8632. // a non-static data member] shall have a name different from T
  8633. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8634. !isa<IndirectFieldDecl>(Target) &&
  8635. !isa<UnresolvedUsingValueDecl>(Target) &&
  8636. DiagnoseClassNameShadow(
  8637. CurContext,
  8638. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8639. return true;
  8640. }
  8641. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8642. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8643. PrevShadow = Shadow;
  8644. FoundEquivalentDecl = true;
  8645. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8646. // We don't conflict with an existing using shadow decl of an equivalent
  8647. // declaration, but we're not a redeclaration of it.
  8648. FoundEquivalentDecl = true;
  8649. }
  8650. if (isVisible(D))
  8651. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8652. }
  8653. if (FoundEquivalentDecl)
  8654. return false;
  8655. if (FunctionDecl *FD = Target->getAsFunction()) {
  8656. NamedDecl *OldDecl = nullptr;
  8657. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8658. /*IsForUsingDecl*/ true)) {
  8659. case Ovl_Overload:
  8660. return false;
  8661. case Ovl_NonFunction:
  8662. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8663. break;
  8664. // We found a decl with the exact signature.
  8665. case Ovl_Match:
  8666. // If we're in a record, we want to hide the target, so we
  8667. // return true (without a diagnostic) to tell the caller not to
  8668. // build a shadow decl.
  8669. if (CurContext->isRecord())
  8670. return true;
  8671. // If we're not in a record, this is an error.
  8672. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8673. break;
  8674. }
  8675. Diag(Target->getLocation(), diag::note_using_decl_target);
  8676. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8677. Using->setInvalidDecl();
  8678. return true;
  8679. }
  8680. // Target is not a function.
  8681. if (isa<TagDecl>(Target)) {
  8682. // No conflict between a tag and a non-tag.
  8683. if (!Tag) return false;
  8684. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8685. Diag(Target->getLocation(), diag::note_using_decl_target);
  8686. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8687. Using->setInvalidDecl();
  8688. return true;
  8689. }
  8690. // No conflict between a tag and a non-tag.
  8691. if (!NonTag) return false;
  8692. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8693. Diag(Target->getLocation(), diag::note_using_decl_target);
  8694. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8695. Using->setInvalidDecl();
  8696. return true;
  8697. }
  8698. /// Determine whether a direct base class is a virtual base class.
  8699. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8700. if (!Derived->getNumVBases())
  8701. return false;
  8702. for (auto &B : Derived->bases())
  8703. if (B.getType()->getAsCXXRecordDecl() == Base)
  8704. return B.isVirtual();
  8705. llvm_unreachable("not a direct base class");
  8706. }
  8707. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8708. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8709. UsingDecl *UD,
  8710. NamedDecl *Orig,
  8711. UsingShadowDecl *PrevDecl) {
  8712. // If we resolved to another shadow declaration, just coalesce them.
  8713. NamedDecl *Target = Orig;
  8714. if (isa<UsingShadowDecl>(Target)) {
  8715. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8716. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8717. }
  8718. NamedDecl *NonTemplateTarget = Target;
  8719. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8720. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8721. UsingShadowDecl *Shadow;
  8722. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8723. bool IsVirtualBase =
  8724. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8725. UD->getQualifier()->getAsRecordDecl());
  8726. Shadow = ConstructorUsingShadowDecl::Create(
  8727. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8728. } else {
  8729. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8730. Target);
  8731. }
  8732. UD->addShadowDecl(Shadow);
  8733. Shadow->setAccess(UD->getAccess());
  8734. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8735. Shadow->setInvalidDecl();
  8736. Shadow->setPreviousDecl(PrevDecl);
  8737. if (S)
  8738. PushOnScopeChains(Shadow, S);
  8739. else
  8740. CurContext->addDecl(Shadow);
  8741. return Shadow;
  8742. }
  8743. /// Hides a using shadow declaration. This is required by the current
  8744. /// using-decl implementation when a resolvable using declaration in a
  8745. /// class is followed by a declaration which would hide or override
  8746. /// one or more of the using decl's targets; for example:
  8747. ///
  8748. /// struct Base { void foo(int); };
  8749. /// struct Derived : Base {
  8750. /// using Base::foo;
  8751. /// void foo(int);
  8752. /// };
  8753. ///
  8754. /// The governing language is C++03 [namespace.udecl]p12:
  8755. ///
  8756. /// When a using-declaration brings names from a base class into a
  8757. /// derived class scope, member functions in the derived class
  8758. /// override and/or hide member functions with the same name and
  8759. /// parameter types in a base class (rather than conflicting).
  8760. ///
  8761. /// There are two ways to implement this:
  8762. /// (1) optimistically create shadow decls when they're not hidden
  8763. /// by existing declarations, or
  8764. /// (2) don't create any shadow decls (or at least don't make them
  8765. /// visible) until we've fully parsed/instantiated the class.
  8766. /// The problem with (1) is that we might have to retroactively remove
  8767. /// a shadow decl, which requires several O(n) operations because the
  8768. /// decl structures are (very reasonably) not designed for removal.
  8769. /// (2) avoids this but is very fiddly and phase-dependent.
  8770. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8771. if (Shadow->getDeclName().getNameKind() ==
  8772. DeclarationName::CXXConversionFunctionName)
  8773. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8774. // Remove it from the DeclContext...
  8775. Shadow->getDeclContext()->removeDecl(Shadow);
  8776. // ...and the scope, if applicable...
  8777. if (S) {
  8778. S->RemoveDecl(Shadow);
  8779. IdResolver.RemoveDecl(Shadow);
  8780. }
  8781. // ...and the using decl.
  8782. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8783. // TODO: complain somehow if Shadow was used. It shouldn't
  8784. // be possible for this to happen, because...?
  8785. }
  8786. /// Find the base specifier for a base class with the given type.
  8787. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8788. QualType DesiredBase,
  8789. bool &AnyDependentBases) {
  8790. // Check whether the named type is a direct base class.
  8791. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
  8792. .getUnqualifiedType();
  8793. for (auto &Base : Derived->bases()) {
  8794. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8795. if (CanonicalDesiredBase == BaseType)
  8796. return &Base;
  8797. if (BaseType->isDependentType())
  8798. AnyDependentBases = true;
  8799. }
  8800. return nullptr;
  8801. }
  8802. namespace {
  8803. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  8804. public:
  8805. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8806. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8807. : HasTypenameKeyword(HasTypenameKeyword),
  8808. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8809. RequireMemberOf(RequireMemberOf) {}
  8810. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8811. NamedDecl *ND = Candidate.getCorrectionDecl();
  8812. // Keywords are not valid here.
  8813. if (!ND || isa<NamespaceDecl>(ND))
  8814. return false;
  8815. // Completely unqualified names are invalid for a 'using' declaration.
  8816. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8817. return false;
  8818. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8819. // reject.
  8820. if (RequireMemberOf) {
  8821. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8822. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8823. // No-one ever wants a using-declaration to name an injected-class-name
  8824. // of a base class, unless they're declaring an inheriting constructor.
  8825. ASTContext &Ctx = ND->getASTContext();
  8826. if (!Ctx.getLangOpts().CPlusPlus11)
  8827. return false;
  8828. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8829. // Check that the injected-class-name is named as a member of its own
  8830. // type; we don't want to suggest 'using Derived::Base;', since that
  8831. // means something else.
  8832. NestedNameSpecifier *Specifier =
  8833. Candidate.WillReplaceSpecifier()
  8834. ? Candidate.getCorrectionSpecifier()
  8835. : OldNNS;
  8836. if (!Specifier->getAsType() ||
  8837. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8838. return false;
  8839. // Check that this inheriting constructor declaration actually names a
  8840. // direct base class of the current class.
  8841. bool AnyDependentBases = false;
  8842. if (!findDirectBaseWithType(RequireMemberOf,
  8843. Ctx.getRecordType(FoundRecord),
  8844. AnyDependentBases) &&
  8845. !AnyDependentBases)
  8846. return false;
  8847. } else {
  8848. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8849. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8850. return false;
  8851. // FIXME: Check that the base class member is accessible?
  8852. }
  8853. } else {
  8854. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8855. if (FoundRecord && FoundRecord->isInjectedClassName())
  8856. return false;
  8857. }
  8858. if (isa<TypeDecl>(ND))
  8859. return HasTypenameKeyword || !IsInstantiation;
  8860. return !HasTypenameKeyword;
  8861. }
  8862. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8863. return std::make_unique<UsingValidatorCCC>(*this);
  8864. }
  8865. private:
  8866. bool HasTypenameKeyword;
  8867. bool IsInstantiation;
  8868. NestedNameSpecifier *OldNNS;
  8869. CXXRecordDecl *RequireMemberOf;
  8870. };
  8871. } // end anonymous namespace
  8872. /// Builds a using declaration.
  8873. ///
  8874. /// \param IsInstantiation - Whether this call arises from an
  8875. /// instantiation of an unresolved using declaration. We treat
  8876. /// the lookup differently for these declarations.
  8877. NamedDecl *Sema::BuildUsingDeclaration(
  8878. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8879. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8880. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8881. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8882. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8883. SourceLocation IdentLoc = NameInfo.getLoc();
  8884. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8885. // FIXME: We ignore attributes for now.
  8886. // For an inheriting constructor declaration, the name of the using
  8887. // declaration is the name of a constructor in this class, not in the
  8888. // base class.
  8889. DeclarationNameInfo UsingName = NameInfo;
  8890. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8891. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8892. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8893. Context.getCanonicalType(Context.getRecordType(RD))));
  8894. // Do the redeclaration lookup in the current scope.
  8895. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8896. ForVisibleRedeclaration);
  8897. Previous.setHideTags(false);
  8898. if (S) {
  8899. LookupName(Previous, S);
  8900. // It is really dumb that we have to do this.
  8901. LookupResult::Filter F = Previous.makeFilter();
  8902. while (F.hasNext()) {
  8903. NamedDecl *D = F.next();
  8904. if (!isDeclInScope(D, CurContext, S))
  8905. F.erase();
  8906. // If we found a local extern declaration that's not ordinarily visible,
  8907. // and this declaration is being added to a non-block scope, ignore it.
  8908. // We're only checking for scope conflicts here, not also for violations
  8909. // of the linkage rules.
  8910. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8911. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8912. F.erase();
  8913. }
  8914. F.done();
  8915. } else {
  8916. assert(IsInstantiation && "no scope in non-instantiation");
  8917. if (CurContext->isRecord())
  8918. LookupQualifiedName(Previous, CurContext);
  8919. else {
  8920. // No redeclaration check is needed here; in non-member contexts we
  8921. // diagnosed all possible conflicts with other using-declarations when
  8922. // building the template:
  8923. //
  8924. // For a dependent non-type using declaration, the only valid case is
  8925. // if we instantiate to a single enumerator. We check for conflicts
  8926. // between shadow declarations we introduce, and we check in the template
  8927. // definition for conflicts between a non-type using declaration and any
  8928. // other declaration, which together covers all cases.
  8929. //
  8930. // A dependent typename using declaration will never successfully
  8931. // instantiate, since it will always name a class member, so we reject
  8932. // that in the template definition.
  8933. }
  8934. }
  8935. // Check for invalid redeclarations.
  8936. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8937. SS, IdentLoc, Previous))
  8938. return nullptr;
  8939. // Check for bad qualifiers.
  8940. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8941. IdentLoc))
  8942. return nullptr;
  8943. DeclContext *LookupContext = computeDeclContext(SS);
  8944. NamedDecl *D;
  8945. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8946. if (!LookupContext || EllipsisLoc.isValid()) {
  8947. if (HasTypenameKeyword) {
  8948. // FIXME: not all declaration name kinds are legal here
  8949. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8950. UsingLoc, TypenameLoc,
  8951. QualifierLoc,
  8952. IdentLoc, NameInfo.getName(),
  8953. EllipsisLoc);
  8954. } else {
  8955. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8956. QualifierLoc, NameInfo, EllipsisLoc);
  8957. }
  8958. D->setAccess(AS);
  8959. CurContext->addDecl(D);
  8960. return D;
  8961. }
  8962. auto Build = [&](bool Invalid) {
  8963. UsingDecl *UD =
  8964. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8965. UsingName, HasTypenameKeyword);
  8966. UD->setAccess(AS);
  8967. CurContext->addDecl(UD);
  8968. UD->setInvalidDecl(Invalid);
  8969. return UD;
  8970. };
  8971. auto BuildInvalid = [&]{ return Build(true); };
  8972. auto BuildValid = [&]{ return Build(false); };
  8973. if (RequireCompleteDeclContext(SS, LookupContext))
  8974. return BuildInvalid();
  8975. // Look up the target name.
  8976. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8977. // Unlike most lookups, we don't always want to hide tag
  8978. // declarations: tag names are visible through the using declaration
  8979. // even if hidden by ordinary names, *except* in a dependent context
  8980. // where it's important for the sanity of two-phase lookup.
  8981. if (!IsInstantiation)
  8982. R.setHideTags(false);
  8983. // For the purposes of this lookup, we have a base object type
  8984. // equal to that of the current context.
  8985. if (CurContext->isRecord()) {
  8986. R.setBaseObjectType(
  8987. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8988. }
  8989. LookupQualifiedName(R, LookupContext);
  8990. // Try to correct typos if possible. If constructor name lookup finds no
  8991. // results, that means the named class has no explicit constructors, and we
  8992. // suppressed declaring implicit ones (probably because it's dependent or
  8993. // invalid).
  8994. if (R.empty() &&
  8995. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8996. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8997. // it will believe that glibc provides a ::gets in cases where it does not,
  8998. // and will try to pull it into namespace std with a using-declaration.
  8999. // Just ignore the using-declaration in that case.
  9000. auto *II = NameInfo.getName().getAsIdentifierInfo();
  9001. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  9002. CurContext->isStdNamespace() &&
  9003. isa<TranslationUnitDecl>(LookupContext) &&
  9004. getSourceManager().isInSystemHeader(UsingLoc))
  9005. return nullptr;
  9006. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  9007. dyn_cast<CXXRecordDecl>(CurContext));
  9008. if (TypoCorrection Corrected =
  9009. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  9010. CTK_ErrorRecovery)) {
  9011. // We reject candidates where DroppedSpecifier == true, hence the
  9012. // literal '0' below.
  9013. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  9014. << NameInfo.getName() << LookupContext << 0
  9015. << SS.getRange());
  9016. // If we picked a correction with no attached Decl we can't do anything
  9017. // useful with it, bail out.
  9018. NamedDecl *ND = Corrected.getCorrectionDecl();
  9019. if (!ND)
  9020. return BuildInvalid();
  9021. // If we corrected to an inheriting constructor, handle it as one.
  9022. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  9023. if (RD && RD->isInjectedClassName()) {
  9024. // The parent of the injected class name is the class itself.
  9025. RD = cast<CXXRecordDecl>(RD->getParent());
  9026. // Fix up the information we'll use to build the using declaration.
  9027. if (Corrected.WillReplaceSpecifier()) {
  9028. NestedNameSpecifierLocBuilder Builder;
  9029. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  9030. QualifierLoc.getSourceRange());
  9031. QualifierLoc = Builder.getWithLocInContext(Context);
  9032. }
  9033. // In this case, the name we introduce is the name of a derived class
  9034. // constructor.
  9035. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  9036. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  9037. Context.getCanonicalType(Context.getRecordType(CurClass))));
  9038. UsingName.setNamedTypeInfo(nullptr);
  9039. for (auto *Ctor : LookupConstructors(RD))
  9040. R.addDecl(Ctor);
  9041. R.resolveKind();
  9042. } else {
  9043. // FIXME: Pick up all the declarations if we found an overloaded
  9044. // function.
  9045. UsingName.setName(ND->getDeclName());
  9046. R.addDecl(ND);
  9047. }
  9048. } else {
  9049. Diag(IdentLoc, diag::err_no_member)
  9050. << NameInfo.getName() << LookupContext << SS.getRange();
  9051. return BuildInvalid();
  9052. }
  9053. }
  9054. if (R.isAmbiguous())
  9055. return BuildInvalid();
  9056. if (HasTypenameKeyword) {
  9057. // If we asked for a typename and got a non-type decl, error out.
  9058. if (!R.getAsSingle<TypeDecl>()) {
  9059. Diag(IdentLoc, diag::err_using_typename_non_type);
  9060. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9061. Diag((*I)->getUnderlyingDecl()->getLocation(),
  9062. diag::note_using_decl_target);
  9063. return BuildInvalid();
  9064. }
  9065. } else {
  9066. // If we asked for a non-typename and we got a type, error out,
  9067. // but only if this is an instantiation of an unresolved using
  9068. // decl. Otherwise just silently find the type name.
  9069. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  9070. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  9071. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  9072. return BuildInvalid();
  9073. }
  9074. }
  9075. // C++14 [namespace.udecl]p6:
  9076. // A using-declaration shall not name a namespace.
  9077. if (R.getAsSingle<NamespaceDecl>()) {
  9078. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  9079. << SS.getRange();
  9080. return BuildInvalid();
  9081. }
  9082. // C++14 [namespace.udecl]p7:
  9083. // A using-declaration shall not name a scoped enumerator.
  9084. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  9085. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  9086. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  9087. << SS.getRange();
  9088. return BuildInvalid();
  9089. }
  9090. }
  9091. UsingDecl *UD = BuildValid();
  9092. // Some additional rules apply to inheriting constructors.
  9093. if (UsingName.getName().getNameKind() ==
  9094. DeclarationName::CXXConstructorName) {
  9095. // Suppress access diagnostics; the access check is instead performed at the
  9096. // point of use for an inheriting constructor.
  9097. R.suppressDiagnostics();
  9098. if (CheckInheritingConstructorUsingDecl(UD))
  9099. return UD;
  9100. }
  9101. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  9102. UsingShadowDecl *PrevDecl = nullptr;
  9103. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  9104. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  9105. }
  9106. return UD;
  9107. }
  9108. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  9109. ArrayRef<NamedDecl *> Expansions) {
  9110. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  9111. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  9112. isa<UsingPackDecl>(InstantiatedFrom));
  9113. auto *UPD =
  9114. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  9115. UPD->setAccess(InstantiatedFrom->getAccess());
  9116. CurContext->addDecl(UPD);
  9117. return UPD;
  9118. }
  9119. /// Additional checks for a using declaration referring to a constructor name.
  9120. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  9121. assert(!UD->hasTypename() && "expecting a constructor name");
  9122. const Type *SourceType = UD->getQualifier()->getAsType();
  9123. assert(SourceType &&
  9124. "Using decl naming constructor doesn't have type in scope spec.");
  9125. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  9126. // Check whether the named type is a direct base class.
  9127. bool AnyDependentBases = false;
  9128. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  9129. AnyDependentBases);
  9130. if (!Base && !AnyDependentBases) {
  9131. Diag(UD->getUsingLoc(),
  9132. diag::err_using_decl_constructor_not_in_direct_base)
  9133. << UD->getNameInfo().getSourceRange()
  9134. << QualType(SourceType, 0) << TargetClass;
  9135. UD->setInvalidDecl();
  9136. return true;
  9137. }
  9138. if (Base)
  9139. Base->setInheritConstructors();
  9140. return false;
  9141. }
  9142. /// Checks that the given using declaration is not an invalid
  9143. /// redeclaration. Note that this is checking only for the using decl
  9144. /// itself, not for any ill-formedness among the UsingShadowDecls.
  9145. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  9146. bool HasTypenameKeyword,
  9147. const CXXScopeSpec &SS,
  9148. SourceLocation NameLoc,
  9149. const LookupResult &Prev) {
  9150. NestedNameSpecifier *Qual = SS.getScopeRep();
  9151. // C++03 [namespace.udecl]p8:
  9152. // C++0x [namespace.udecl]p10:
  9153. // A using-declaration is a declaration and can therefore be used
  9154. // repeatedly where (and only where) multiple declarations are
  9155. // allowed.
  9156. //
  9157. // That's in non-member contexts.
  9158. if (!CurContext->getRedeclContext()->isRecord()) {
  9159. // A dependent qualifier outside a class can only ever resolve to an
  9160. // enumeration type. Therefore it conflicts with any other non-type
  9161. // declaration in the same scope.
  9162. // FIXME: How should we check for dependent type-type conflicts at block
  9163. // scope?
  9164. if (Qual->isDependent() && !HasTypenameKeyword) {
  9165. for (auto *D : Prev) {
  9166. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  9167. bool OldCouldBeEnumerator =
  9168. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  9169. Diag(NameLoc,
  9170. OldCouldBeEnumerator ? diag::err_redefinition
  9171. : diag::err_redefinition_different_kind)
  9172. << Prev.getLookupName();
  9173. Diag(D->getLocation(), diag::note_previous_definition);
  9174. return true;
  9175. }
  9176. }
  9177. }
  9178. return false;
  9179. }
  9180. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  9181. NamedDecl *D = *I;
  9182. bool DTypename;
  9183. NestedNameSpecifier *DQual;
  9184. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  9185. DTypename = UD->hasTypename();
  9186. DQual = UD->getQualifier();
  9187. } else if (UnresolvedUsingValueDecl *UD
  9188. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  9189. DTypename = false;
  9190. DQual = UD->getQualifier();
  9191. } else if (UnresolvedUsingTypenameDecl *UD
  9192. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  9193. DTypename = true;
  9194. DQual = UD->getQualifier();
  9195. } else continue;
  9196. // using decls differ if one says 'typename' and the other doesn't.
  9197. // FIXME: non-dependent using decls?
  9198. if (HasTypenameKeyword != DTypename) continue;
  9199. // using decls differ if they name different scopes (but note that
  9200. // template instantiation can cause this check to trigger when it
  9201. // didn't before instantiation).
  9202. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  9203. Context.getCanonicalNestedNameSpecifier(DQual))
  9204. continue;
  9205. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  9206. Diag(D->getLocation(), diag::note_using_decl) << 1;
  9207. return true;
  9208. }
  9209. return false;
  9210. }
  9211. /// Checks that the given nested-name qualifier used in a using decl
  9212. /// in the current context is appropriately related to the current
  9213. /// scope. If an error is found, diagnoses it and returns true.
  9214. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  9215. bool HasTypename,
  9216. const CXXScopeSpec &SS,
  9217. const DeclarationNameInfo &NameInfo,
  9218. SourceLocation NameLoc) {
  9219. DeclContext *NamedContext = computeDeclContext(SS);
  9220. if (!CurContext->isRecord()) {
  9221. // C++03 [namespace.udecl]p3:
  9222. // C++0x [namespace.udecl]p8:
  9223. // A using-declaration for a class member shall be a member-declaration.
  9224. // If we weren't able to compute a valid scope, it might validly be a
  9225. // dependent class scope or a dependent enumeration unscoped scope. If
  9226. // we have a 'typename' keyword, the scope must resolve to a class type.
  9227. if ((HasTypename && !NamedContext) ||
  9228. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  9229. auto *RD = NamedContext
  9230. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  9231. : nullptr;
  9232. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  9233. RD = nullptr;
  9234. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  9235. << SS.getRange();
  9236. // If we have a complete, non-dependent source type, try to suggest a
  9237. // way to get the same effect.
  9238. if (!RD)
  9239. return true;
  9240. // Find what this using-declaration was referring to.
  9241. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  9242. R.setHideTags(false);
  9243. R.suppressDiagnostics();
  9244. LookupQualifiedName(R, RD);
  9245. if (R.getAsSingle<TypeDecl>()) {
  9246. if (getLangOpts().CPlusPlus11) {
  9247. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  9248. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  9249. << 0 // alias declaration
  9250. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  9251. NameInfo.getName().getAsString() +
  9252. " = ");
  9253. } else {
  9254. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  9255. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  9256. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  9257. << 1 // typedef declaration
  9258. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  9259. << FixItHint::CreateInsertion(
  9260. InsertLoc, " " + NameInfo.getName().getAsString());
  9261. }
  9262. } else if (R.getAsSingle<VarDecl>()) {
  9263. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9264. // repeating the type of the static data member here.
  9265. FixItHint FixIt;
  9266. if (getLangOpts().CPlusPlus11) {
  9267. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9268. FixIt = FixItHint::CreateReplacement(
  9269. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  9270. }
  9271. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9272. << 2 // reference declaration
  9273. << FixIt;
  9274. } else if (R.getAsSingle<EnumConstantDecl>()) {
  9275. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9276. // repeating the type of the enumeration here, and we can't do so if
  9277. // the type is anonymous.
  9278. FixItHint FixIt;
  9279. if (getLangOpts().CPlusPlus11) {
  9280. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9281. FixIt = FixItHint::CreateReplacement(
  9282. UsingLoc,
  9283. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  9284. }
  9285. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9286. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  9287. << FixIt;
  9288. }
  9289. return true;
  9290. }
  9291. // Otherwise, this might be valid.
  9292. return false;
  9293. }
  9294. // The current scope is a record.
  9295. // If the named context is dependent, we can't decide much.
  9296. if (!NamedContext) {
  9297. // FIXME: in C++0x, we can diagnose if we can prove that the
  9298. // nested-name-specifier does not refer to a base class, which is
  9299. // still possible in some cases.
  9300. // Otherwise we have to conservatively report that things might be
  9301. // okay.
  9302. return false;
  9303. }
  9304. if (!NamedContext->isRecord()) {
  9305. // Ideally this would point at the last name in the specifier,
  9306. // but we don't have that level of source info.
  9307. Diag(SS.getRange().getBegin(),
  9308. diag::err_using_decl_nested_name_specifier_is_not_class)
  9309. << SS.getScopeRep() << SS.getRange();
  9310. return true;
  9311. }
  9312. if (!NamedContext->isDependentContext() &&
  9313. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  9314. return true;
  9315. if (getLangOpts().CPlusPlus11) {
  9316. // C++11 [namespace.udecl]p3:
  9317. // In a using-declaration used as a member-declaration, the
  9318. // nested-name-specifier shall name a base class of the class
  9319. // being defined.
  9320. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  9321. cast<CXXRecordDecl>(NamedContext))) {
  9322. if (CurContext == NamedContext) {
  9323. Diag(NameLoc,
  9324. diag::err_using_decl_nested_name_specifier_is_current_class)
  9325. << SS.getRange();
  9326. return true;
  9327. }
  9328. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9329. Diag(SS.getRange().getBegin(),
  9330. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9331. << SS.getScopeRep()
  9332. << cast<CXXRecordDecl>(CurContext)
  9333. << SS.getRange();
  9334. }
  9335. return true;
  9336. }
  9337. return false;
  9338. }
  9339. // C++03 [namespace.udecl]p4:
  9340. // A using-declaration used as a member-declaration shall refer
  9341. // to a member of a base class of the class being defined [etc.].
  9342. // Salient point: SS doesn't have to name a base class as long as
  9343. // lookup only finds members from base classes. Therefore we can
  9344. // diagnose here only if we can prove that that can't happen,
  9345. // i.e. if the class hierarchies provably don't intersect.
  9346. // TODO: it would be nice if "definitely valid" results were cached
  9347. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9348. // need to be repeated.
  9349. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9350. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9351. Bases.insert(Base);
  9352. return true;
  9353. };
  9354. // Collect all bases. Return false if we find a dependent base.
  9355. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9356. return false;
  9357. // Returns true if the base is dependent or is one of the accumulated base
  9358. // classes.
  9359. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9360. return !Bases.count(Base);
  9361. };
  9362. // Return false if the class has a dependent base or if it or one
  9363. // of its bases is present in the base set of the current context.
  9364. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9365. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9366. return false;
  9367. Diag(SS.getRange().getBegin(),
  9368. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9369. << SS.getScopeRep()
  9370. << cast<CXXRecordDecl>(CurContext)
  9371. << SS.getRange();
  9372. return true;
  9373. }
  9374. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9375. MultiTemplateParamsArg TemplateParamLists,
  9376. SourceLocation UsingLoc, UnqualifiedId &Name,
  9377. const ParsedAttributesView &AttrList,
  9378. TypeResult Type, Decl *DeclFromDeclSpec) {
  9379. // Skip up to the relevant declaration scope.
  9380. while (S->isTemplateParamScope())
  9381. S = S->getParent();
  9382. assert((S->getFlags() & Scope::DeclScope) &&
  9383. "got alias-declaration outside of declaration scope");
  9384. if (Type.isInvalid())
  9385. return nullptr;
  9386. bool Invalid = false;
  9387. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9388. TypeSourceInfo *TInfo = nullptr;
  9389. GetTypeFromParser(Type.get(), &TInfo);
  9390. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9391. return nullptr;
  9392. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9393. UPPC_DeclarationType)) {
  9394. Invalid = true;
  9395. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9396. TInfo->getTypeLoc().getBeginLoc());
  9397. }
  9398. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9399. TemplateParamLists.size()
  9400. ? forRedeclarationInCurContext()
  9401. : ForVisibleRedeclaration);
  9402. LookupName(Previous, S);
  9403. // Warn about shadowing the name of a template parameter.
  9404. if (Previous.isSingleResult() &&
  9405. Previous.getFoundDecl()->isTemplateParameter()) {
  9406. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9407. Previous.clear();
  9408. }
  9409. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9410. "name in alias declaration must be an identifier");
  9411. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9412. Name.StartLocation,
  9413. Name.Identifier, TInfo);
  9414. NewTD->setAccess(AS);
  9415. if (Invalid)
  9416. NewTD->setInvalidDecl();
  9417. ProcessDeclAttributeList(S, NewTD, AttrList);
  9418. AddPragmaAttributes(S, NewTD);
  9419. CheckTypedefForVariablyModifiedType(S, NewTD);
  9420. Invalid |= NewTD->isInvalidDecl();
  9421. bool Redeclaration = false;
  9422. NamedDecl *NewND;
  9423. if (TemplateParamLists.size()) {
  9424. TypeAliasTemplateDecl *OldDecl = nullptr;
  9425. TemplateParameterList *OldTemplateParams = nullptr;
  9426. if (TemplateParamLists.size() != 1) {
  9427. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9428. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9429. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9430. }
  9431. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9432. // Check that we can declare a template here.
  9433. if (CheckTemplateDeclScope(S, TemplateParams))
  9434. return nullptr;
  9435. // Only consider previous declarations in the same scope.
  9436. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9437. /*ExplicitInstantiationOrSpecialization*/false);
  9438. if (!Previous.empty()) {
  9439. Redeclaration = true;
  9440. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9441. if (!OldDecl && !Invalid) {
  9442. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9443. << Name.Identifier;
  9444. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9445. if (OldD->getLocation().isValid())
  9446. Diag(OldD->getLocation(), diag::note_previous_definition);
  9447. Invalid = true;
  9448. }
  9449. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9450. if (TemplateParameterListsAreEqual(TemplateParams,
  9451. OldDecl->getTemplateParameters(),
  9452. /*Complain=*/true,
  9453. TPL_TemplateMatch))
  9454. OldTemplateParams =
  9455. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9456. else
  9457. Invalid = true;
  9458. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9459. if (!Invalid &&
  9460. !Context.hasSameType(OldTD->getUnderlyingType(),
  9461. NewTD->getUnderlyingType())) {
  9462. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9463. // but we can't reasonably accept it.
  9464. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9465. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9466. if (OldTD->getLocation().isValid())
  9467. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9468. Invalid = true;
  9469. }
  9470. }
  9471. }
  9472. // Merge any previous default template arguments into our parameters,
  9473. // and check the parameter list.
  9474. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9475. TPC_TypeAliasTemplate))
  9476. return nullptr;
  9477. TypeAliasTemplateDecl *NewDecl =
  9478. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9479. Name.Identifier, TemplateParams,
  9480. NewTD);
  9481. NewTD->setDescribedAliasTemplate(NewDecl);
  9482. NewDecl->setAccess(AS);
  9483. if (Invalid)
  9484. NewDecl->setInvalidDecl();
  9485. else if (OldDecl) {
  9486. NewDecl->setPreviousDecl(OldDecl);
  9487. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9488. }
  9489. NewND = NewDecl;
  9490. } else {
  9491. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9492. setTagNameForLinkagePurposes(TD, NewTD);
  9493. handleTagNumbering(TD, S);
  9494. }
  9495. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9496. NewND = NewTD;
  9497. }
  9498. PushOnScopeChains(NewND, S);
  9499. ActOnDocumentableDecl(NewND);
  9500. return NewND;
  9501. }
  9502. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9503. SourceLocation AliasLoc,
  9504. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9505. SourceLocation IdentLoc,
  9506. IdentifierInfo *Ident) {
  9507. // Lookup the namespace name.
  9508. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9509. LookupParsedName(R, S, &SS);
  9510. if (R.isAmbiguous())
  9511. return nullptr;
  9512. if (R.empty()) {
  9513. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9514. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9515. return nullptr;
  9516. }
  9517. }
  9518. assert(!R.isAmbiguous() && !R.empty());
  9519. NamedDecl *ND = R.getRepresentativeDecl();
  9520. // Check if we have a previous declaration with the same name.
  9521. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9522. ForVisibleRedeclaration);
  9523. LookupName(PrevR, S);
  9524. // Check we're not shadowing a template parameter.
  9525. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9526. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9527. PrevR.clear();
  9528. }
  9529. // Filter out any other lookup result from an enclosing scope.
  9530. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9531. /*AllowInlineNamespace*/false);
  9532. // Find the previous declaration and check that we can redeclare it.
  9533. NamespaceAliasDecl *Prev = nullptr;
  9534. if (PrevR.isSingleResult()) {
  9535. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9536. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9537. // We already have an alias with the same name that points to the same
  9538. // namespace; check that it matches.
  9539. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9540. Prev = AD;
  9541. } else if (isVisible(PrevDecl)) {
  9542. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9543. << Alias;
  9544. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9545. << AD->getNamespace();
  9546. return nullptr;
  9547. }
  9548. } else if (isVisible(PrevDecl)) {
  9549. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9550. ? diag::err_redefinition
  9551. : diag::err_redefinition_different_kind;
  9552. Diag(AliasLoc, DiagID) << Alias;
  9553. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9554. return nullptr;
  9555. }
  9556. }
  9557. // The use of a nested name specifier may trigger deprecation warnings.
  9558. DiagnoseUseOfDecl(ND, IdentLoc);
  9559. NamespaceAliasDecl *AliasDecl =
  9560. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9561. Alias, SS.getWithLocInContext(Context),
  9562. IdentLoc, ND);
  9563. if (Prev)
  9564. AliasDecl->setPreviousDecl(Prev);
  9565. PushOnScopeChains(AliasDecl, S);
  9566. return AliasDecl;
  9567. }
  9568. namespace {
  9569. struct SpecialMemberExceptionSpecInfo
  9570. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9571. SourceLocation Loc;
  9572. Sema::ImplicitExceptionSpecification ExceptSpec;
  9573. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9574. Sema::CXXSpecialMember CSM,
  9575. Sema::InheritedConstructorInfo *ICI,
  9576. SourceLocation Loc)
  9577. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9578. bool visitBase(CXXBaseSpecifier *Base);
  9579. bool visitField(FieldDecl *FD);
  9580. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9581. unsigned Quals);
  9582. void visitSubobjectCall(Subobject Subobj,
  9583. Sema::SpecialMemberOverloadResult SMOR);
  9584. };
  9585. }
  9586. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9587. auto *RT = Base->getType()->getAs<RecordType>();
  9588. if (!RT)
  9589. return false;
  9590. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9591. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9592. if (auto *BaseCtor = SMOR.getMethod()) {
  9593. visitSubobjectCall(Base, BaseCtor);
  9594. return false;
  9595. }
  9596. visitClassSubobject(BaseClass, Base, 0);
  9597. return false;
  9598. }
  9599. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9600. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9601. Expr *E = FD->getInClassInitializer();
  9602. if (!E)
  9603. // FIXME: It's a little wasteful to build and throw away a
  9604. // CXXDefaultInitExpr here.
  9605. // FIXME: We should have a single context note pointing at Loc, and
  9606. // this location should be MD->getLocation() instead, since that's
  9607. // the location where we actually use the default init expression.
  9608. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9609. if (E)
  9610. ExceptSpec.CalledExpr(E);
  9611. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9612. ->getAs<RecordType>()) {
  9613. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9614. FD->getType().getCVRQualifiers());
  9615. }
  9616. return false;
  9617. }
  9618. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9619. Subobject Subobj,
  9620. unsigned Quals) {
  9621. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9622. bool IsMutable = Field && Field->isMutable();
  9623. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9624. }
  9625. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9626. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9627. // Note, if lookup fails, it doesn't matter what exception specification we
  9628. // choose because the special member will be deleted.
  9629. if (CXXMethodDecl *MD = SMOR.getMethod())
  9630. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9631. }
  9632. namespace {
  9633. /// RAII object to register a special member as being currently declared.
  9634. struct ComputingExceptionSpec {
  9635. Sema &S;
  9636. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9637. : S(S) {
  9638. Sema::CodeSynthesisContext Ctx;
  9639. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9640. Ctx.PointOfInstantiation = Loc;
  9641. Ctx.Entity = MD;
  9642. S.pushCodeSynthesisContext(Ctx);
  9643. }
  9644. ~ComputingExceptionSpec() {
  9645. S.popCodeSynthesisContext();
  9646. }
  9647. };
  9648. }
  9649. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  9650. llvm::APSInt Result;
  9651. ExprResult Converted = CheckConvertedConstantExpression(
  9652. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  9653. ExplicitSpec.setExpr(Converted.get());
  9654. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  9655. ExplicitSpec.setKind(Result.getBoolValue()
  9656. ? ExplicitSpecKind::ResolvedTrue
  9657. : ExplicitSpecKind::ResolvedFalse);
  9658. return true;
  9659. }
  9660. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  9661. return false;
  9662. }
  9663. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  9664. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  9665. if (!ExplicitExpr->isTypeDependent())
  9666. tryResolveExplicitSpecifier(ES);
  9667. return ES;
  9668. }
  9669. static Sema::ImplicitExceptionSpecification
  9670. ComputeDefaultedSpecialMemberExceptionSpec(
  9671. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9672. Sema::InheritedConstructorInfo *ICI) {
  9673. ComputingExceptionSpec CES(S, MD, Loc);
  9674. CXXRecordDecl *ClassDecl = MD->getParent();
  9675. // C++ [except.spec]p14:
  9676. // An implicitly declared special member function (Clause 12) shall have an
  9677. // exception-specification. [...]
  9678. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9679. if (ClassDecl->isInvalidDecl())
  9680. return Info.ExceptSpec;
  9681. // FIXME: If this diagnostic fires, we're probably missing a check for
  9682. // attempting to resolve an exception specification before it's known
  9683. // at a higher level.
  9684. if (S.RequireCompleteType(MD->getLocation(),
  9685. S.Context.getRecordType(ClassDecl),
  9686. diag::err_exception_spec_incomplete_type))
  9687. return Info.ExceptSpec;
  9688. // C++1z [except.spec]p7:
  9689. // [Look for exceptions thrown by] a constructor selected [...] to
  9690. // initialize a potentially constructed subobject,
  9691. // C++1z [except.spec]p8:
  9692. // The exception specification for an implicitly-declared destructor, or a
  9693. // destructor without a noexcept-specifier, is potentially-throwing if and
  9694. // only if any of the destructors for any of its potentially constructed
  9695. // subojects is potentially throwing.
  9696. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9697. // in the second rule to resolve a core issue (no number yet) that would have
  9698. // us reject:
  9699. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9700. // struct B : A {};
  9701. // struct C : B { void f(); };
  9702. // ... due to giving B::~B() a non-throwing exception specification.
  9703. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9704. : Info.VisitAllBases);
  9705. return Info.ExceptSpec;
  9706. }
  9707. namespace {
  9708. /// RAII object to register a special member as being currently declared.
  9709. struct DeclaringSpecialMember {
  9710. Sema &S;
  9711. Sema::SpecialMemberDecl D;
  9712. Sema::ContextRAII SavedContext;
  9713. bool WasAlreadyBeingDeclared;
  9714. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9715. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9716. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9717. if (WasAlreadyBeingDeclared)
  9718. // This almost never happens, but if it does, ensure that our cache
  9719. // doesn't contain a stale result.
  9720. S.SpecialMemberCache.clear();
  9721. else {
  9722. // Register a note to be produced if we encounter an error while
  9723. // declaring the special member.
  9724. Sema::CodeSynthesisContext Ctx;
  9725. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9726. // FIXME: We don't have a location to use here. Using the class's
  9727. // location maintains the fiction that we declare all special members
  9728. // with the class, but (1) it's not clear that lying about that helps our
  9729. // users understand what's going on, and (2) there may be outer contexts
  9730. // on the stack (some of which are relevant) and printing them exposes
  9731. // our lies.
  9732. Ctx.PointOfInstantiation = RD->getLocation();
  9733. Ctx.Entity = RD;
  9734. Ctx.SpecialMember = CSM;
  9735. S.pushCodeSynthesisContext(Ctx);
  9736. }
  9737. }
  9738. ~DeclaringSpecialMember() {
  9739. if (!WasAlreadyBeingDeclared) {
  9740. S.SpecialMembersBeingDeclared.erase(D);
  9741. S.popCodeSynthesisContext();
  9742. }
  9743. }
  9744. /// Are we already trying to declare this special member?
  9745. bool isAlreadyBeingDeclared() const {
  9746. return WasAlreadyBeingDeclared;
  9747. }
  9748. };
  9749. }
  9750. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9751. // Look up any existing declarations, but don't trigger declaration of all
  9752. // implicit special members with this name.
  9753. DeclarationName Name = FD->getDeclName();
  9754. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9755. ForExternalRedeclaration);
  9756. for (auto *D : FD->getParent()->lookup(Name))
  9757. if (auto *Acceptable = R.getAcceptableDecl(D))
  9758. R.addDecl(Acceptable);
  9759. R.resolveKind();
  9760. R.suppressDiagnostics();
  9761. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9762. }
  9763. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  9764. QualType ResultTy,
  9765. ArrayRef<QualType> Args) {
  9766. // Build an exception specification pointing back at this constructor.
  9767. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  9768. if (getLangOpts().OpenCLCPlusPlus) {
  9769. // OpenCL: Implicitly defaulted special member are of the generic address
  9770. // space.
  9771. EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
  9772. }
  9773. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  9774. SpecialMem->setType(QT);
  9775. }
  9776. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9777. CXXRecordDecl *ClassDecl) {
  9778. // C++ [class.ctor]p5:
  9779. // A default constructor for a class X is a constructor of class X
  9780. // that can be called without an argument. If there is no
  9781. // user-declared constructor for class X, a default constructor is
  9782. // implicitly declared. An implicitly-declared default constructor
  9783. // is an inline public member of its class.
  9784. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9785. "Should not build implicit default constructor!");
  9786. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9787. if (DSM.isAlreadyBeingDeclared())
  9788. return nullptr;
  9789. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9790. CXXDefaultConstructor,
  9791. false);
  9792. // Create the actual constructor declaration.
  9793. CanQualType ClassType
  9794. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9795. SourceLocation ClassLoc = ClassDecl->getLocation();
  9796. DeclarationName Name
  9797. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9798. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9799. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9800. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  9801. /*TInfo=*/nullptr, ExplicitSpecifier(),
  9802. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9803. Constexpr ? CSK_constexpr : CSK_unspecified);
  9804. DefaultCon->setAccess(AS_public);
  9805. DefaultCon->setDefaulted();
  9806. if (getLangOpts().CUDA) {
  9807. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9808. DefaultCon,
  9809. /* ConstRHS */ false,
  9810. /* Diagnose */ false);
  9811. }
  9812. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
  9813. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9814. // constructors is easy to compute.
  9815. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9816. // Note that we have declared this constructor.
  9817. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  9818. Scope *S = getScopeForContext(ClassDecl);
  9819. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9820. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9821. SetDeclDeleted(DefaultCon, ClassLoc);
  9822. if (S)
  9823. PushOnScopeChains(DefaultCon, S, false);
  9824. ClassDecl->addDecl(DefaultCon);
  9825. return DefaultCon;
  9826. }
  9827. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9828. CXXConstructorDecl *Constructor) {
  9829. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9830. !Constructor->doesThisDeclarationHaveABody() &&
  9831. !Constructor->isDeleted()) &&
  9832. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9833. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9834. return;
  9835. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9836. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9837. SynthesizedFunctionScope Scope(*this, Constructor);
  9838. // The exception specification is needed because we are defining the
  9839. // function.
  9840. ResolveExceptionSpec(CurrentLocation,
  9841. Constructor->getType()->castAs<FunctionProtoType>());
  9842. MarkVTableUsed(CurrentLocation, ClassDecl);
  9843. // Add a context note for diagnostics produced after this point.
  9844. Scope.addContextNote(CurrentLocation);
  9845. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9846. Constructor->setInvalidDecl();
  9847. return;
  9848. }
  9849. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9850. ? Constructor->getEndLoc()
  9851. : Constructor->getLocation();
  9852. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9853. Constructor->markUsed(Context);
  9854. if (ASTMutationListener *L = getASTMutationListener()) {
  9855. L->CompletedImplicitDefinition(Constructor);
  9856. }
  9857. DiagnoseUninitializedFields(*this, Constructor);
  9858. }
  9859. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9860. // Perform any delayed checks on exception specifications.
  9861. CheckDelayedMemberExceptionSpecs();
  9862. }
  9863. /// Find or create the fake constructor we synthesize to model constructing an
  9864. /// object of a derived class via a constructor of a base class.
  9865. CXXConstructorDecl *
  9866. Sema::findInheritingConstructor(SourceLocation Loc,
  9867. CXXConstructorDecl *BaseCtor,
  9868. ConstructorUsingShadowDecl *Shadow) {
  9869. CXXRecordDecl *Derived = Shadow->getParent();
  9870. SourceLocation UsingLoc = Shadow->getLocation();
  9871. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9872. // For now we use the name of the base class constructor as a member of the
  9873. // derived class to indicate a (fake) inherited constructor name.
  9874. DeclarationName Name = BaseCtor->getDeclName();
  9875. // Check to see if we already have a fake constructor for this inherited
  9876. // constructor call.
  9877. for (NamedDecl *Ctor : Derived->lookup(Name))
  9878. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9879. ->getInheritedConstructor()
  9880. .getConstructor(),
  9881. BaseCtor))
  9882. return cast<CXXConstructorDecl>(Ctor);
  9883. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9884. TypeSourceInfo *TInfo =
  9885. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9886. FunctionProtoTypeLoc ProtoLoc =
  9887. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9888. // Check the inherited constructor is valid and find the list of base classes
  9889. // from which it was inherited.
  9890. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9891. bool Constexpr =
  9892. BaseCtor->isConstexpr() &&
  9893. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9894. false, BaseCtor, &ICI);
  9895. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9896. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9897. BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
  9898. /*isImplicitlyDeclared=*/true,
  9899. Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
  9900. InheritedConstructor(Shadow, BaseCtor));
  9901. if (Shadow->isInvalidDecl())
  9902. DerivedCtor->setInvalidDecl();
  9903. // Build an unevaluated exception specification for this fake constructor.
  9904. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9905. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9906. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9907. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9908. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9909. FPT->getParamTypes(), EPI));
  9910. // Build the parameter declarations.
  9911. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9912. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9913. TypeSourceInfo *TInfo =
  9914. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9915. ParmVarDecl *PD = ParmVarDecl::Create(
  9916. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9917. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  9918. PD->setScopeInfo(0, I);
  9919. PD->setImplicit();
  9920. // Ensure attributes are propagated onto parameters (this matters for
  9921. // format, pass_object_size, ...).
  9922. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9923. ParamDecls.push_back(PD);
  9924. ProtoLoc.setParam(I, PD);
  9925. }
  9926. // Set up the new constructor.
  9927. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9928. DerivedCtor->setAccess(BaseCtor->getAccess());
  9929. DerivedCtor->setParams(ParamDecls);
  9930. Derived->addDecl(DerivedCtor);
  9931. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9932. SetDeclDeleted(DerivedCtor, UsingLoc);
  9933. return DerivedCtor;
  9934. }
  9935. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9936. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9937. Ctor->getInheritedConstructor().getShadowDecl());
  9938. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9939. /*Diagnose*/true);
  9940. }
  9941. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9942. CXXConstructorDecl *Constructor) {
  9943. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9944. assert(Constructor->getInheritedConstructor() &&
  9945. !Constructor->doesThisDeclarationHaveABody() &&
  9946. !Constructor->isDeleted());
  9947. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9948. return;
  9949. // Initializations are performed "as if by a defaulted default constructor",
  9950. // so enter the appropriate scope.
  9951. SynthesizedFunctionScope Scope(*this, Constructor);
  9952. // The exception specification is needed because we are defining the
  9953. // function.
  9954. ResolveExceptionSpec(CurrentLocation,
  9955. Constructor->getType()->castAs<FunctionProtoType>());
  9956. MarkVTableUsed(CurrentLocation, ClassDecl);
  9957. // Add a context note for diagnostics produced after this point.
  9958. Scope.addContextNote(CurrentLocation);
  9959. ConstructorUsingShadowDecl *Shadow =
  9960. Constructor->getInheritedConstructor().getShadowDecl();
  9961. CXXConstructorDecl *InheritedCtor =
  9962. Constructor->getInheritedConstructor().getConstructor();
  9963. // [class.inhctor.init]p1:
  9964. // initialization proceeds as if a defaulted default constructor is used to
  9965. // initialize the D object and each base class subobject from which the
  9966. // constructor was inherited
  9967. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9968. CXXRecordDecl *RD = Shadow->getParent();
  9969. SourceLocation InitLoc = Shadow->getLocation();
  9970. // Build explicit initializers for all base classes from which the
  9971. // constructor was inherited.
  9972. SmallVector<CXXCtorInitializer*, 8> Inits;
  9973. for (bool VBase : {false, true}) {
  9974. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9975. if (B.isVirtual() != VBase)
  9976. continue;
  9977. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9978. if (!BaseRD)
  9979. continue;
  9980. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9981. if (!BaseCtor.first)
  9982. continue;
  9983. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9984. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9985. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9986. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9987. Inits.push_back(new (Context) CXXCtorInitializer(
  9988. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9989. SourceLocation()));
  9990. }
  9991. }
  9992. // We now proceed as if for a defaulted default constructor, with the relevant
  9993. // initializers replaced.
  9994. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  9995. Constructor->setInvalidDecl();
  9996. return;
  9997. }
  9998. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9999. Constructor->markUsed(Context);
  10000. if (ASTMutationListener *L = getASTMutationListener()) {
  10001. L->CompletedImplicitDefinition(Constructor);
  10002. }
  10003. DiagnoseUninitializedFields(*this, Constructor);
  10004. }
  10005. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  10006. // C++ [class.dtor]p2:
  10007. // If a class has no user-declared destructor, a destructor is
  10008. // declared implicitly. An implicitly-declared destructor is an
  10009. // inline public member of its class.
  10010. assert(ClassDecl->needsImplicitDestructor());
  10011. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  10012. if (DSM.isAlreadyBeingDeclared())
  10013. return nullptr;
  10014. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10015. CXXDestructor,
  10016. false);
  10017. // Create the actual destructor declaration.
  10018. CanQualType ClassType
  10019. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  10020. SourceLocation ClassLoc = ClassDecl->getLocation();
  10021. DeclarationName Name
  10022. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  10023. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10024. CXXDestructorDecl *Destructor =
  10025. CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  10026. QualType(), nullptr, /*isInline=*/true,
  10027. /*isImplicitlyDeclared=*/true,
  10028. Constexpr ? CSK_constexpr : CSK_unspecified);
  10029. Destructor->setAccess(AS_public);
  10030. Destructor->setDefaulted();
  10031. if (getLangOpts().CUDA) {
  10032. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  10033. Destructor,
  10034. /* ConstRHS */ false,
  10035. /* Diagnose */ false);
  10036. }
  10037. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
  10038. // We don't need to use SpecialMemberIsTrivial here; triviality for
  10039. // destructors is easy to compute.
  10040. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  10041. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  10042. ClassDecl->hasTrivialDestructorForCall());
  10043. // Note that we have declared this destructor.
  10044. ++getASTContext().NumImplicitDestructorsDeclared;
  10045. Scope *S = getScopeForContext(ClassDecl);
  10046. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  10047. // We can't check whether an implicit destructor is deleted before we complete
  10048. // the definition of the class, because its validity depends on the alignment
  10049. // of the class. We'll check this from ActOnFields once the class is complete.
  10050. if (ClassDecl->isCompleteDefinition() &&
  10051. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  10052. SetDeclDeleted(Destructor, ClassLoc);
  10053. // Introduce this destructor into its scope.
  10054. if (S)
  10055. PushOnScopeChains(Destructor, S, false);
  10056. ClassDecl->addDecl(Destructor);
  10057. return Destructor;
  10058. }
  10059. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  10060. CXXDestructorDecl *Destructor) {
  10061. assert((Destructor->isDefaulted() &&
  10062. !Destructor->doesThisDeclarationHaveABody() &&
  10063. !Destructor->isDeleted()) &&
  10064. "DefineImplicitDestructor - call it for implicit default dtor");
  10065. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  10066. return;
  10067. CXXRecordDecl *ClassDecl = Destructor->getParent();
  10068. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  10069. SynthesizedFunctionScope Scope(*this, Destructor);
  10070. // The exception specification is needed because we are defining the
  10071. // function.
  10072. ResolveExceptionSpec(CurrentLocation,
  10073. Destructor->getType()->castAs<FunctionProtoType>());
  10074. MarkVTableUsed(CurrentLocation, ClassDecl);
  10075. // Add a context note for diagnostics produced after this point.
  10076. Scope.addContextNote(CurrentLocation);
  10077. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  10078. Destructor->getParent());
  10079. if (CheckDestructor(Destructor)) {
  10080. Destructor->setInvalidDecl();
  10081. return;
  10082. }
  10083. SourceLocation Loc = Destructor->getEndLoc().isValid()
  10084. ? Destructor->getEndLoc()
  10085. : Destructor->getLocation();
  10086. Destructor->setBody(new (Context) CompoundStmt(Loc));
  10087. Destructor->markUsed(Context);
  10088. if (ASTMutationListener *L = getASTMutationListener()) {
  10089. L->CompletedImplicitDefinition(Destructor);
  10090. }
  10091. }
  10092. /// Perform any semantic analysis which needs to be delayed until all
  10093. /// pending class member declarations have been parsed.
  10094. void Sema::ActOnFinishCXXMemberDecls() {
  10095. // If the context is an invalid C++ class, just suppress these checks.
  10096. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  10097. if (Record->isInvalidDecl()) {
  10098. DelayedOverridingExceptionSpecChecks.clear();
  10099. DelayedEquivalentExceptionSpecChecks.clear();
  10100. return;
  10101. }
  10102. checkForMultipleExportedDefaultConstructors(*this, Record);
  10103. }
  10104. }
  10105. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  10106. referenceDLLExportedClassMethods();
  10107. if (!DelayedDllExportMemberFunctions.empty()) {
  10108. SmallVector<CXXMethodDecl*, 4> WorkList;
  10109. std::swap(DelayedDllExportMemberFunctions, WorkList);
  10110. for (CXXMethodDecl *M : WorkList) {
  10111. DefineImplicitSpecialMember(*this, M, M->getLocation());
  10112. // Pass the method to the consumer to get emitted. This is not necessary
  10113. // for explicit instantiation definitions, as they will get emitted
  10114. // anyway.
  10115. if (M->getParent()->getTemplateSpecializationKind() !=
  10116. TSK_ExplicitInstantiationDefinition)
  10117. ActOnFinishInlineFunctionDef(M);
  10118. }
  10119. }
  10120. }
  10121. void Sema::referenceDLLExportedClassMethods() {
  10122. if (!DelayedDllExportClasses.empty()) {
  10123. // Calling ReferenceDllExportedMembers might cause the current function to
  10124. // be called again, so use a local copy of DelayedDllExportClasses.
  10125. SmallVector<CXXRecordDecl *, 4> WorkList;
  10126. std::swap(DelayedDllExportClasses, WorkList);
  10127. for (CXXRecordDecl *Class : WorkList)
  10128. ReferenceDllExportedMembers(*this, Class);
  10129. }
  10130. }
  10131. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  10132. assert(getLangOpts().CPlusPlus11 &&
  10133. "adjusting dtor exception specs was introduced in c++11");
  10134. if (Destructor->isDependentContext())
  10135. return;
  10136. // C++11 [class.dtor]p3:
  10137. // A declaration of a destructor that does not have an exception-
  10138. // specification is implicitly considered to have the same exception-
  10139. // specification as an implicit declaration.
  10140. const FunctionProtoType *DtorType = Destructor->getType()->
  10141. getAs<FunctionProtoType>();
  10142. if (DtorType->hasExceptionSpec())
  10143. return;
  10144. // Replace the destructor's type, building off the existing one. Fortunately,
  10145. // the only thing of interest in the destructor type is its extended info.
  10146. // The return and arguments are fixed.
  10147. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  10148. EPI.ExceptionSpec.Type = EST_Unevaluated;
  10149. EPI.ExceptionSpec.SourceDecl = Destructor;
  10150. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  10151. // FIXME: If the destructor has a body that could throw, and the newly created
  10152. // spec doesn't allow exceptions, we should emit a warning, because this
  10153. // change in behavior can break conforming C++03 programs at runtime.
  10154. // However, we don't have a body or an exception specification yet, so it
  10155. // needs to be done somewhere else.
  10156. }
  10157. namespace {
  10158. /// An abstract base class for all helper classes used in building the
  10159. // copy/move operators. These classes serve as factory functions and help us
  10160. // avoid using the same Expr* in the AST twice.
  10161. class ExprBuilder {
  10162. ExprBuilder(const ExprBuilder&) = delete;
  10163. ExprBuilder &operator=(const ExprBuilder&) = delete;
  10164. protected:
  10165. static Expr *assertNotNull(Expr *E) {
  10166. assert(E && "Expression construction must not fail.");
  10167. return E;
  10168. }
  10169. public:
  10170. ExprBuilder() {}
  10171. virtual ~ExprBuilder() {}
  10172. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  10173. };
  10174. class RefBuilder: public ExprBuilder {
  10175. VarDecl *Var;
  10176. QualType VarType;
  10177. public:
  10178. Expr *build(Sema &S, SourceLocation Loc) const override {
  10179. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  10180. }
  10181. RefBuilder(VarDecl *Var, QualType VarType)
  10182. : Var(Var), VarType(VarType) {}
  10183. };
  10184. class ThisBuilder: public ExprBuilder {
  10185. public:
  10186. Expr *build(Sema &S, SourceLocation Loc) const override {
  10187. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  10188. }
  10189. };
  10190. class CastBuilder: public ExprBuilder {
  10191. const ExprBuilder &Builder;
  10192. QualType Type;
  10193. ExprValueKind Kind;
  10194. const CXXCastPath &Path;
  10195. public:
  10196. Expr *build(Sema &S, SourceLocation Loc) const override {
  10197. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  10198. CK_UncheckedDerivedToBase, Kind,
  10199. &Path).get());
  10200. }
  10201. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  10202. const CXXCastPath &Path)
  10203. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  10204. };
  10205. class DerefBuilder: public ExprBuilder {
  10206. const ExprBuilder &Builder;
  10207. public:
  10208. Expr *build(Sema &S, SourceLocation Loc) const override {
  10209. return assertNotNull(
  10210. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  10211. }
  10212. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10213. };
  10214. class MemberBuilder: public ExprBuilder {
  10215. const ExprBuilder &Builder;
  10216. QualType Type;
  10217. CXXScopeSpec SS;
  10218. bool IsArrow;
  10219. LookupResult &MemberLookup;
  10220. public:
  10221. Expr *build(Sema &S, SourceLocation Loc) const override {
  10222. return assertNotNull(S.BuildMemberReferenceExpr(
  10223. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  10224. nullptr, MemberLookup, nullptr, nullptr).get());
  10225. }
  10226. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  10227. LookupResult &MemberLookup)
  10228. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  10229. MemberLookup(MemberLookup) {}
  10230. };
  10231. class MoveCastBuilder: public ExprBuilder {
  10232. const ExprBuilder &Builder;
  10233. public:
  10234. Expr *build(Sema &S, SourceLocation Loc) const override {
  10235. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  10236. }
  10237. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10238. };
  10239. class LvalueConvBuilder: public ExprBuilder {
  10240. const ExprBuilder &Builder;
  10241. public:
  10242. Expr *build(Sema &S, SourceLocation Loc) const override {
  10243. return assertNotNull(
  10244. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  10245. }
  10246. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10247. };
  10248. class SubscriptBuilder: public ExprBuilder {
  10249. const ExprBuilder &Base;
  10250. const ExprBuilder &Index;
  10251. public:
  10252. Expr *build(Sema &S, SourceLocation Loc) const override {
  10253. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  10254. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  10255. }
  10256. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  10257. : Base(Base), Index(Index) {}
  10258. };
  10259. } // end anonymous namespace
  10260. /// When generating a defaulted copy or move assignment operator, if a field
  10261. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  10262. /// do so. This optimization only applies for arrays of scalars, and for arrays
  10263. /// of class type where the selected copy/move-assignment operator is trivial.
  10264. static StmtResult
  10265. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  10266. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  10267. // Compute the size of the memory buffer to be copied.
  10268. QualType SizeType = S.Context.getSizeType();
  10269. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  10270. S.Context.getTypeSizeInChars(T).getQuantity());
  10271. // Take the address of the field references for "from" and "to". We
  10272. // directly construct UnaryOperators here because semantic analysis
  10273. // does not permit us to take the address of an xvalue.
  10274. Expr *From = FromB.build(S, Loc);
  10275. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  10276. S.Context.getPointerType(From->getType()),
  10277. VK_RValue, OK_Ordinary, Loc, false);
  10278. Expr *To = ToB.build(S, Loc);
  10279. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  10280. S.Context.getPointerType(To->getType()),
  10281. VK_RValue, OK_Ordinary, Loc, false);
  10282. const Type *E = T->getBaseElementTypeUnsafe();
  10283. bool NeedsCollectableMemCpy =
  10284. E->isRecordType() &&
  10285. E->castAs<RecordType>()->getDecl()->hasObjectMember();
  10286. // Create a reference to the __builtin_objc_memmove_collectable function
  10287. StringRef MemCpyName = NeedsCollectableMemCpy ?
  10288. "__builtin_objc_memmove_collectable" :
  10289. "__builtin_memcpy";
  10290. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  10291. Sema::LookupOrdinaryName);
  10292. S.LookupName(R, S.TUScope, true);
  10293. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  10294. if (!MemCpy)
  10295. // Something went horribly wrong earlier, and we will have complained
  10296. // about it.
  10297. return StmtError();
  10298. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  10299. VK_RValue, Loc, nullptr);
  10300. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  10301. Expr *CallArgs[] = {
  10302. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  10303. };
  10304. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  10305. Loc, CallArgs, Loc);
  10306. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  10307. return Call.getAs<Stmt>();
  10308. }
  10309. /// Builds a statement that copies/moves the given entity from \p From to
  10310. /// \c To.
  10311. ///
  10312. /// This routine is used to copy/move the members of a class with an
  10313. /// implicitly-declared copy/move assignment operator. When the entities being
  10314. /// copied are arrays, this routine builds for loops to copy them.
  10315. ///
  10316. /// \param S The Sema object used for type-checking.
  10317. ///
  10318. /// \param Loc The location where the implicit copy/move is being generated.
  10319. ///
  10320. /// \param T The type of the expressions being copied/moved. Both expressions
  10321. /// must have this type.
  10322. ///
  10323. /// \param To The expression we are copying/moving to.
  10324. ///
  10325. /// \param From The expression we are copying/moving from.
  10326. ///
  10327. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  10328. /// Otherwise, it's a non-static member subobject.
  10329. ///
  10330. /// \param Copying Whether we're copying or moving.
  10331. ///
  10332. /// \param Depth Internal parameter recording the depth of the recursion.
  10333. ///
  10334. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  10335. /// if a memcpy should be used instead.
  10336. static StmtResult
  10337. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  10338. const ExprBuilder &To, const ExprBuilder &From,
  10339. bool CopyingBaseSubobject, bool Copying,
  10340. unsigned Depth = 0) {
  10341. // C++11 [class.copy]p28:
  10342. // Each subobject is assigned in the manner appropriate to its type:
  10343. //
  10344. // - if the subobject is of class type, as if by a call to operator= with
  10345. // the subobject as the object expression and the corresponding
  10346. // subobject of x as a single function argument (as if by explicit
  10347. // qualification; that is, ignoring any possible virtual overriding
  10348. // functions in more derived classes);
  10349. //
  10350. // C++03 [class.copy]p13:
  10351. // - if the subobject is of class type, the copy assignment operator for
  10352. // the class is used (as if by explicit qualification; that is,
  10353. // ignoring any possible virtual overriding functions in more derived
  10354. // classes);
  10355. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  10356. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  10357. // Look for operator=.
  10358. DeclarationName Name
  10359. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10360. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  10361. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  10362. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  10363. // operator.
  10364. if (!S.getLangOpts().CPlusPlus11) {
  10365. LookupResult::Filter F = OpLookup.makeFilter();
  10366. while (F.hasNext()) {
  10367. NamedDecl *D = F.next();
  10368. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  10369. if (Method->isCopyAssignmentOperator() ||
  10370. (!Copying && Method->isMoveAssignmentOperator()))
  10371. continue;
  10372. F.erase();
  10373. }
  10374. F.done();
  10375. }
  10376. // Suppress the protected check (C++ [class.protected]) for each of the
  10377. // assignment operators we found. This strange dance is required when
  10378. // we're assigning via a base classes's copy-assignment operator. To
  10379. // ensure that we're getting the right base class subobject (without
  10380. // ambiguities), we need to cast "this" to that subobject type; to
  10381. // ensure that we don't go through the virtual call mechanism, we need
  10382. // to qualify the operator= name with the base class (see below). However,
  10383. // this means that if the base class has a protected copy assignment
  10384. // operator, the protected member access check will fail. So, we
  10385. // rewrite "protected" access to "public" access in this case, since we
  10386. // know by construction that we're calling from a derived class.
  10387. if (CopyingBaseSubobject) {
  10388. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10389. L != LEnd; ++L) {
  10390. if (L.getAccess() == AS_protected)
  10391. L.setAccess(AS_public);
  10392. }
  10393. }
  10394. // Create the nested-name-specifier that will be used to qualify the
  10395. // reference to operator=; this is required to suppress the virtual
  10396. // call mechanism.
  10397. CXXScopeSpec SS;
  10398. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10399. SS.MakeTrivial(S.Context,
  10400. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10401. CanonicalT),
  10402. Loc);
  10403. // Create the reference to operator=.
  10404. ExprResult OpEqualRef
  10405. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  10406. SS, /*TemplateKWLoc=*/SourceLocation(),
  10407. /*FirstQualifierInScope=*/nullptr,
  10408. OpLookup,
  10409. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10410. /*SuppressQualifierCheck=*/true);
  10411. if (OpEqualRef.isInvalid())
  10412. return StmtError();
  10413. // Build the call to the assignment operator.
  10414. Expr *FromInst = From.build(S, Loc);
  10415. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10416. OpEqualRef.getAs<Expr>(),
  10417. Loc, FromInst, Loc);
  10418. if (Call.isInvalid())
  10419. return StmtError();
  10420. // If we built a call to a trivial 'operator=' while copying an array,
  10421. // bail out. We'll replace the whole shebang with a memcpy.
  10422. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10423. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10424. return StmtResult((Stmt*)nullptr);
  10425. // Convert to an expression-statement, and clean up any produced
  10426. // temporaries.
  10427. return S.ActOnExprStmt(Call);
  10428. }
  10429. // - if the subobject is of scalar type, the built-in assignment
  10430. // operator is used.
  10431. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10432. if (!ArrayTy) {
  10433. ExprResult Assignment = S.CreateBuiltinBinOp(
  10434. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10435. if (Assignment.isInvalid())
  10436. return StmtError();
  10437. return S.ActOnExprStmt(Assignment);
  10438. }
  10439. // - if the subobject is an array, each element is assigned, in the
  10440. // manner appropriate to the element type;
  10441. // Construct a loop over the array bounds, e.g.,
  10442. //
  10443. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10444. //
  10445. // that will copy each of the array elements.
  10446. QualType SizeType = S.Context.getSizeType();
  10447. // Create the iteration variable.
  10448. IdentifierInfo *IterationVarName = nullptr;
  10449. {
  10450. SmallString<8> Str;
  10451. llvm::raw_svector_ostream OS(Str);
  10452. OS << "__i" << Depth;
  10453. IterationVarName = &S.Context.Idents.get(OS.str());
  10454. }
  10455. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10456. IterationVarName, SizeType,
  10457. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10458. SC_None);
  10459. // Initialize the iteration variable to zero.
  10460. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10461. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10462. // Creates a reference to the iteration variable.
  10463. RefBuilder IterationVarRef(IterationVar, SizeType);
  10464. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10465. // Create the DeclStmt that holds the iteration variable.
  10466. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10467. // Subscript the "from" and "to" expressions with the iteration variable.
  10468. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10469. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10470. const ExprBuilder *FromIndex;
  10471. if (Copying)
  10472. FromIndex = &FromIndexCopy;
  10473. else
  10474. FromIndex = &FromIndexMove;
  10475. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10476. // Build the copy/move for an individual element of the array.
  10477. StmtResult Copy =
  10478. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10479. ToIndex, *FromIndex, CopyingBaseSubobject,
  10480. Copying, Depth + 1);
  10481. // Bail out if copying fails or if we determined that we should use memcpy.
  10482. if (Copy.isInvalid() || !Copy.get())
  10483. return Copy;
  10484. // Create the comparison against the array bound.
  10485. llvm::APInt Upper
  10486. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10487. Expr *Comparison
  10488. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10489. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10490. BO_NE, S.Context.BoolTy,
  10491. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10492. // Create the pre-increment of the iteration variable. We can determine
  10493. // whether the increment will overflow based on the value of the array
  10494. // bound.
  10495. Expr *Increment = new (S.Context)
  10496. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10497. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10498. // Construct the loop that copies all elements of this array.
  10499. return S.ActOnForStmt(
  10500. Loc, Loc, InitStmt,
  10501. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10502. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10503. }
  10504. static StmtResult
  10505. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10506. const ExprBuilder &To, const ExprBuilder &From,
  10507. bool CopyingBaseSubobject, bool Copying) {
  10508. // Maybe we should use a memcpy?
  10509. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10510. T.isTriviallyCopyableType(S.Context))
  10511. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10512. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10513. CopyingBaseSubobject,
  10514. Copying, 0));
  10515. // If we ended up picking a trivial assignment operator for an array of a
  10516. // non-trivially-copyable class type, just emit a memcpy.
  10517. if (!Result.isInvalid() && !Result.get())
  10518. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10519. return Result;
  10520. }
  10521. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10522. // Note: The following rules are largely analoguous to the copy
  10523. // constructor rules. Note that virtual bases are not taken into account
  10524. // for determining the argument type of the operator. Note also that
  10525. // operators taking an object instead of a reference are allowed.
  10526. assert(ClassDecl->needsImplicitCopyAssignment());
  10527. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10528. if (DSM.isAlreadyBeingDeclared())
  10529. return nullptr;
  10530. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10531. if (Context.getLangOpts().OpenCLCPlusPlus)
  10532. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10533. QualType RetType = Context.getLValueReferenceType(ArgType);
  10534. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10535. if (Const)
  10536. ArgType = ArgType.withConst();
  10537. ArgType = Context.getLValueReferenceType(ArgType);
  10538. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10539. CXXCopyAssignment,
  10540. Const);
  10541. // An implicitly-declared copy assignment operator is an inline public
  10542. // member of its class.
  10543. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10544. SourceLocation ClassLoc = ClassDecl->getLocation();
  10545. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10546. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  10547. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10548. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10549. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10550. SourceLocation());
  10551. CopyAssignment->setAccess(AS_public);
  10552. CopyAssignment->setDefaulted();
  10553. CopyAssignment->setImplicit();
  10554. if (getLangOpts().CUDA) {
  10555. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10556. CopyAssignment,
  10557. /* ConstRHS */ Const,
  10558. /* Diagnose */ false);
  10559. }
  10560. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  10561. // Add the parameter to the operator.
  10562. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10563. ClassLoc, ClassLoc,
  10564. /*Id=*/nullptr, ArgType,
  10565. /*TInfo=*/nullptr, SC_None,
  10566. nullptr);
  10567. CopyAssignment->setParams(FromParam);
  10568. CopyAssignment->setTrivial(
  10569. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10570. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10571. : ClassDecl->hasTrivialCopyAssignment());
  10572. // Note that we have added this copy-assignment operator.
  10573. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  10574. Scope *S = getScopeForContext(ClassDecl);
  10575. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10576. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10577. SetDeclDeleted(CopyAssignment, ClassLoc);
  10578. if (S)
  10579. PushOnScopeChains(CopyAssignment, S, false);
  10580. ClassDecl->addDecl(CopyAssignment);
  10581. return CopyAssignment;
  10582. }
  10583. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10584. /// which is deprecated because the class has a user-declared copy constructor,
  10585. /// copy assignment operator, or destructor.
  10586. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10587. assert(CopyOp->isImplicit());
  10588. CXXRecordDecl *RD = CopyOp->getParent();
  10589. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10590. // In Microsoft mode, assignment operations don't affect constructors and
  10591. // vice versa.
  10592. if (RD->hasUserDeclaredDestructor()) {
  10593. UserDeclaredOperation = RD->getDestructor();
  10594. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10595. RD->hasUserDeclaredCopyConstructor() &&
  10596. !S.getLangOpts().MSVCCompat) {
  10597. // Find any user-declared copy constructor.
  10598. for (auto *I : RD->ctors()) {
  10599. if (I->isCopyConstructor()) {
  10600. UserDeclaredOperation = I;
  10601. break;
  10602. }
  10603. }
  10604. assert(UserDeclaredOperation);
  10605. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10606. RD->hasUserDeclaredCopyAssignment() &&
  10607. !S.getLangOpts().MSVCCompat) {
  10608. // Find any user-declared move assignment operator.
  10609. for (auto *I : RD->methods()) {
  10610. if (I->isCopyAssignmentOperator()) {
  10611. UserDeclaredOperation = I;
  10612. break;
  10613. }
  10614. }
  10615. assert(UserDeclaredOperation);
  10616. }
  10617. if (UserDeclaredOperation) {
  10618. S.Diag(UserDeclaredOperation->getLocation(),
  10619. diag::warn_deprecated_copy_operation)
  10620. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10621. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10622. }
  10623. }
  10624. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10625. CXXMethodDecl *CopyAssignOperator) {
  10626. assert((CopyAssignOperator->isDefaulted() &&
  10627. CopyAssignOperator->isOverloadedOperator() &&
  10628. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10629. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10630. !CopyAssignOperator->isDeleted()) &&
  10631. "DefineImplicitCopyAssignment called for wrong function");
  10632. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10633. return;
  10634. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10635. if (ClassDecl->isInvalidDecl()) {
  10636. CopyAssignOperator->setInvalidDecl();
  10637. return;
  10638. }
  10639. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10640. // The exception specification is needed because we are defining the
  10641. // function.
  10642. ResolveExceptionSpec(CurrentLocation,
  10643. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10644. // Add a context note for diagnostics produced after this point.
  10645. Scope.addContextNote(CurrentLocation);
  10646. // C++11 [class.copy]p18:
  10647. // The [definition of an implicitly declared copy assignment operator] is
  10648. // deprecated if the class has a user-declared copy constructor or a
  10649. // user-declared destructor.
  10650. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10651. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10652. // C++0x [class.copy]p30:
  10653. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10654. // for a non-union class X performs memberwise copy assignment of its
  10655. // subobjects. The direct base classes of X are assigned first, in the
  10656. // order of their declaration in the base-specifier-list, and then the
  10657. // immediate non-static data members of X are assigned, in the order in
  10658. // which they were declared in the class definition.
  10659. // The statements that form the synthesized function body.
  10660. SmallVector<Stmt*, 8> Statements;
  10661. // The parameter for the "other" object, which we are copying from.
  10662. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10663. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10664. QualType OtherRefType = Other->getType();
  10665. if (const LValueReferenceType *OtherRef
  10666. = OtherRefType->getAs<LValueReferenceType>()) {
  10667. OtherRefType = OtherRef->getPointeeType();
  10668. OtherQuals = OtherRefType.getQualifiers();
  10669. }
  10670. // Our location for everything implicitly-generated.
  10671. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10672. ? CopyAssignOperator->getEndLoc()
  10673. : CopyAssignOperator->getLocation();
  10674. // Builds a DeclRefExpr for the "other" object.
  10675. RefBuilder OtherRef(Other, OtherRefType);
  10676. // Builds the "this" pointer.
  10677. ThisBuilder This;
  10678. // Assign base classes.
  10679. bool Invalid = false;
  10680. for (auto &Base : ClassDecl->bases()) {
  10681. // Form the assignment:
  10682. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10683. QualType BaseType = Base.getType().getUnqualifiedType();
  10684. if (!BaseType->isRecordType()) {
  10685. Invalid = true;
  10686. continue;
  10687. }
  10688. CXXCastPath BasePath;
  10689. BasePath.push_back(&Base);
  10690. // Construct the "from" expression, which is an implicit cast to the
  10691. // appropriately-qualified base type.
  10692. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10693. VK_LValue, BasePath);
  10694. // Dereference "this".
  10695. DerefBuilder DerefThis(This);
  10696. CastBuilder To(DerefThis,
  10697. Context.getQualifiedType(
  10698. BaseType, CopyAssignOperator->getMethodQualifiers()),
  10699. VK_LValue, BasePath);
  10700. // Build the copy.
  10701. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10702. To, From,
  10703. /*CopyingBaseSubobject=*/true,
  10704. /*Copying=*/true);
  10705. if (Copy.isInvalid()) {
  10706. CopyAssignOperator->setInvalidDecl();
  10707. return;
  10708. }
  10709. // Success! Record the copy.
  10710. Statements.push_back(Copy.getAs<Expr>());
  10711. }
  10712. // Assign non-static members.
  10713. for (auto *Field : ClassDecl->fields()) {
  10714. // FIXME: We should form some kind of AST representation for the implied
  10715. // memcpy in a union copy operation.
  10716. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10717. continue;
  10718. if (Field->isInvalidDecl()) {
  10719. Invalid = true;
  10720. continue;
  10721. }
  10722. // Check for members of reference type; we can't copy those.
  10723. if (Field->getType()->isReferenceType()) {
  10724. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10725. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10726. Diag(Field->getLocation(), diag::note_declared_at);
  10727. Invalid = true;
  10728. continue;
  10729. }
  10730. // Check for members of const-qualified, non-class type.
  10731. QualType BaseType = Context.getBaseElementType(Field->getType());
  10732. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10733. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10734. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10735. Diag(Field->getLocation(), diag::note_declared_at);
  10736. Invalid = true;
  10737. continue;
  10738. }
  10739. // Suppress assigning zero-width bitfields.
  10740. if (Field->isZeroLengthBitField(Context))
  10741. continue;
  10742. QualType FieldType = Field->getType().getNonReferenceType();
  10743. if (FieldType->isIncompleteArrayType()) {
  10744. assert(ClassDecl->hasFlexibleArrayMember() &&
  10745. "Incomplete array type is not valid");
  10746. continue;
  10747. }
  10748. // Build references to the field in the object we're copying from and to.
  10749. CXXScopeSpec SS; // Intentionally empty
  10750. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10751. LookupMemberName);
  10752. MemberLookup.addDecl(Field);
  10753. MemberLookup.resolveKind();
  10754. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10755. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10756. // Build the copy of this field.
  10757. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10758. To, From,
  10759. /*CopyingBaseSubobject=*/false,
  10760. /*Copying=*/true);
  10761. if (Copy.isInvalid()) {
  10762. CopyAssignOperator->setInvalidDecl();
  10763. return;
  10764. }
  10765. // Success! Record the copy.
  10766. Statements.push_back(Copy.getAs<Stmt>());
  10767. }
  10768. if (!Invalid) {
  10769. // Add a "return *this;"
  10770. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10771. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10772. if (Return.isInvalid())
  10773. Invalid = true;
  10774. else
  10775. Statements.push_back(Return.getAs<Stmt>());
  10776. }
  10777. if (Invalid) {
  10778. CopyAssignOperator->setInvalidDecl();
  10779. return;
  10780. }
  10781. StmtResult Body;
  10782. {
  10783. CompoundScopeRAII CompoundScope(*this);
  10784. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10785. /*isStmtExpr=*/false);
  10786. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10787. }
  10788. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10789. CopyAssignOperator->markUsed(Context);
  10790. if (ASTMutationListener *L = getASTMutationListener()) {
  10791. L->CompletedImplicitDefinition(CopyAssignOperator);
  10792. }
  10793. }
  10794. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10795. assert(ClassDecl->needsImplicitMoveAssignment());
  10796. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10797. if (DSM.isAlreadyBeingDeclared())
  10798. return nullptr;
  10799. // Note: The following rules are largely analoguous to the move
  10800. // constructor rules.
  10801. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10802. if (Context.getLangOpts().OpenCLCPlusPlus)
  10803. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10804. QualType RetType = Context.getLValueReferenceType(ArgType);
  10805. ArgType = Context.getRValueReferenceType(ArgType);
  10806. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10807. CXXMoveAssignment,
  10808. false);
  10809. // An implicitly-declared move assignment operator is an inline public
  10810. // member of its class.
  10811. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10812. SourceLocation ClassLoc = ClassDecl->getLocation();
  10813. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10814. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  10815. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10816. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10817. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10818. SourceLocation());
  10819. MoveAssignment->setAccess(AS_public);
  10820. MoveAssignment->setDefaulted();
  10821. MoveAssignment->setImplicit();
  10822. if (getLangOpts().CUDA) {
  10823. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10824. MoveAssignment,
  10825. /* ConstRHS */ false,
  10826. /* Diagnose */ false);
  10827. }
  10828. // Build an exception specification pointing back at this member.
  10829. FunctionProtoType::ExtProtoInfo EPI =
  10830. getImplicitMethodEPI(*this, MoveAssignment);
  10831. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10832. // Add the parameter to the operator.
  10833. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10834. ClassLoc, ClassLoc,
  10835. /*Id=*/nullptr, ArgType,
  10836. /*TInfo=*/nullptr, SC_None,
  10837. nullptr);
  10838. MoveAssignment->setParams(FromParam);
  10839. MoveAssignment->setTrivial(
  10840. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10841. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10842. : ClassDecl->hasTrivialMoveAssignment());
  10843. // Note that we have added this copy-assignment operator.
  10844. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  10845. Scope *S = getScopeForContext(ClassDecl);
  10846. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10847. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10848. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10849. SetDeclDeleted(MoveAssignment, ClassLoc);
  10850. }
  10851. if (S)
  10852. PushOnScopeChains(MoveAssignment, S, false);
  10853. ClassDecl->addDecl(MoveAssignment);
  10854. return MoveAssignment;
  10855. }
  10856. /// Check if we're implicitly defining a move assignment operator for a class
  10857. /// with virtual bases. Such a move assignment might move-assign the virtual
  10858. /// base multiple times.
  10859. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10860. SourceLocation CurrentLocation) {
  10861. assert(!Class->isDependentContext() && "should not define dependent move");
  10862. // Only a virtual base could get implicitly move-assigned multiple times.
  10863. // Only a non-trivial move assignment can observe this. We only want to
  10864. // diagnose if we implicitly define an assignment operator that assigns
  10865. // two base classes, both of which move-assign the same virtual base.
  10866. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10867. Class->getNumBases() < 2)
  10868. return;
  10869. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10870. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10871. VBaseMap VBases;
  10872. for (auto &BI : Class->bases()) {
  10873. Worklist.push_back(&BI);
  10874. while (!Worklist.empty()) {
  10875. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10876. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10877. // If the base has no non-trivial move assignment operators,
  10878. // we don't care about moves from it.
  10879. if (!Base->hasNonTrivialMoveAssignment())
  10880. continue;
  10881. // If there's nothing virtual here, skip it.
  10882. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10883. continue;
  10884. // If we're not actually going to call a move assignment for this base,
  10885. // or the selected move assignment is trivial, skip it.
  10886. Sema::SpecialMemberOverloadResult SMOR =
  10887. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10888. /*ConstArg*/false, /*VolatileArg*/false,
  10889. /*RValueThis*/true, /*ConstThis*/false,
  10890. /*VolatileThis*/false);
  10891. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10892. !SMOR.getMethod()->isMoveAssignmentOperator())
  10893. continue;
  10894. if (BaseSpec->isVirtual()) {
  10895. // We're going to move-assign this virtual base, and its move
  10896. // assignment operator is not trivial. If this can happen for
  10897. // multiple distinct direct bases of Class, diagnose it. (If it
  10898. // only happens in one base, we'll diagnose it when synthesizing
  10899. // that base class's move assignment operator.)
  10900. CXXBaseSpecifier *&Existing =
  10901. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10902. .first->second;
  10903. if (Existing && Existing != &BI) {
  10904. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10905. << Class << Base;
  10906. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10907. << (Base->getCanonicalDecl() ==
  10908. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10909. << Base << Existing->getType() << Existing->getSourceRange();
  10910. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10911. << (Base->getCanonicalDecl() ==
  10912. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10913. << Base << BI.getType() << BaseSpec->getSourceRange();
  10914. // Only diagnose each vbase once.
  10915. Existing = nullptr;
  10916. }
  10917. } else {
  10918. // Only walk over bases that have defaulted move assignment operators.
  10919. // We assume that any user-provided move assignment operator handles
  10920. // the multiple-moves-of-vbase case itself somehow.
  10921. if (!SMOR.getMethod()->isDefaulted())
  10922. continue;
  10923. // We're going to move the base classes of Base. Add them to the list.
  10924. for (auto &BI : Base->bases())
  10925. Worklist.push_back(&BI);
  10926. }
  10927. }
  10928. }
  10929. }
  10930. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10931. CXXMethodDecl *MoveAssignOperator) {
  10932. assert((MoveAssignOperator->isDefaulted() &&
  10933. MoveAssignOperator->isOverloadedOperator() &&
  10934. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10935. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10936. !MoveAssignOperator->isDeleted()) &&
  10937. "DefineImplicitMoveAssignment called for wrong function");
  10938. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10939. return;
  10940. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10941. if (ClassDecl->isInvalidDecl()) {
  10942. MoveAssignOperator->setInvalidDecl();
  10943. return;
  10944. }
  10945. // C++0x [class.copy]p28:
  10946. // The implicitly-defined or move assignment operator for a non-union class
  10947. // X performs memberwise move assignment of its subobjects. The direct base
  10948. // classes of X are assigned first, in the order of their declaration in the
  10949. // base-specifier-list, and then the immediate non-static data members of X
  10950. // are assigned, in the order in which they were declared in the class
  10951. // definition.
  10952. // Issue a warning if our implicit move assignment operator will move
  10953. // from a virtual base more than once.
  10954. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10955. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10956. // The exception specification is needed because we are defining the
  10957. // function.
  10958. ResolveExceptionSpec(CurrentLocation,
  10959. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10960. // Add a context note for diagnostics produced after this point.
  10961. Scope.addContextNote(CurrentLocation);
  10962. // The statements that form the synthesized function body.
  10963. SmallVector<Stmt*, 8> Statements;
  10964. // The parameter for the "other" object, which we are move from.
  10965. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10966. QualType OtherRefType = Other->getType()->
  10967. getAs<RValueReferenceType>()->getPointeeType();
  10968. // Our location for everything implicitly-generated.
  10969. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10970. ? MoveAssignOperator->getEndLoc()
  10971. : MoveAssignOperator->getLocation();
  10972. // Builds a reference to the "other" object.
  10973. RefBuilder OtherRef(Other, OtherRefType);
  10974. // Cast to rvalue.
  10975. MoveCastBuilder MoveOther(OtherRef);
  10976. // Builds the "this" pointer.
  10977. ThisBuilder This;
  10978. // Assign base classes.
  10979. bool Invalid = false;
  10980. for (auto &Base : ClassDecl->bases()) {
  10981. // C++11 [class.copy]p28:
  10982. // It is unspecified whether subobjects representing virtual base classes
  10983. // are assigned more than once by the implicitly-defined copy assignment
  10984. // operator.
  10985. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10986. // class. For a move-assignment, this can result in the vbase being moved
  10987. // multiple times.
  10988. // Form the assignment:
  10989. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10990. QualType BaseType = Base.getType().getUnqualifiedType();
  10991. if (!BaseType->isRecordType()) {
  10992. Invalid = true;
  10993. continue;
  10994. }
  10995. CXXCastPath BasePath;
  10996. BasePath.push_back(&Base);
  10997. // Construct the "from" expression, which is an implicit cast to the
  10998. // appropriately-qualified base type.
  10999. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  11000. // Dereference "this".
  11001. DerefBuilder DerefThis(This);
  11002. // Implicitly cast "this" to the appropriately-qualified base type.
  11003. CastBuilder To(DerefThis,
  11004. Context.getQualifiedType(
  11005. BaseType, MoveAssignOperator->getMethodQualifiers()),
  11006. VK_LValue, BasePath);
  11007. // Build the move.
  11008. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  11009. To, From,
  11010. /*CopyingBaseSubobject=*/true,
  11011. /*Copying=*/false);
  11012. if (Move.isInvalid()) {
  11013. MoveAssignOperator->setInvalidDecl();
  11014. return;
  11015. }
  11016. // Success! Record the move.
  11017. Statements.push_back(Move.getAs<Expr>());
  11018. }
  11019. // Assign non-static members.
  11020. for (auto *Field : ClassDecl->fields()) {
  11021. // FIXME: We should form some kind of AST representation for the implied
  11022. // memcpy in a union copy operation.
  11023. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  11024. continue;
  11025. if (Field->isInvalidDecl()) {
  11026. Invalid = true;
  11027. continue;
  11028. }
  11029. // Check for members of reference type; we can't move those.
  11030. if (Field->getType()->isReferenceType()) {
  11031. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  11032. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  11033. Diag(Field->getLocation(), diag::note_declared_at);
  11034. Invalid = true;
  11035. continue;
  11036. }
  11037. // Check for members of const-qualified, non-class type.
  11038. QualType BaseType = Context.getBaseElementType(Field->getType());
  11039. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  11040. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  11041. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  11042. Diag(Field->getLocation(), diag::note_declared_at);
  11043. Invalid = true;
  11044. continue;
  11045. }
  11046. // Suppress assigning zero-width bitfields.
  11047. if (Field->isZeroLengthBitField(Context))
  11048. continue;
  11049. QualType FieldType = Field->getType().getNonReferenceType();
  11050. if (FieldType->isIncompleteArrayType()) {
  11051. assert(ClassDecl->hasFlexibleArrayMember() &&
  11052. "Incomplete array type is not valid");
  11053. continue;
  11054. }
  11055. // Build references to the field in the object we're copying from and to.
  11056. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  11057. LookupMemberName);
  11058. MemberLookup.addDecl(Field);
  11059. MemberLookup.resolveKind();
  11060. MemberBuilder From(MoveOther, OtherRefType,
  11061. /*IsArrow=*/false, MemberLookup);
  11062. MemberBuilder To(This, getCurrentThisType(),
  11063. /*IsArrow=*/true, MemberLookup);
  11064. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  11065. "Member reference with rvalue base must be rvalue except for reference "
  11066. "members, which aren't allowed for move assignment.");
  11067. // Build the move of this field.
  11068. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  11069. To, From,
  11070. /*CopyingBaseSubobject=*/false,
  11071. /*Copying=*/false);
  11072. if (Move.isInvalid()) {
  11073. MoveAssignOperator->setInvalidDecl();
  11074. return;
  11075. }
  11076. // Success! Record the copy.
  11077. Statements.push_back(Move.getAs<Stmt>());
  11078. }
  11079. if (!Invalid) {
  11080. // Add a "return *this;"
  11081. ExprResult ThisObj =
  11082. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  11083. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  11084. if (Return.isInvalid())
  11085. Invalid = true;
  11086. else
  11087. Statements.push_back(Return.getAs<Stmt>());
  11088. }
  11089. if (Invalid) {
  11090. MoveAssignOperator->setInvalidDecl();
  11091. return;
  11092. }
  11093. StmtResult Body;
  11094. {
  11095. CompoundScopeRAII CompoundScope(*this);
  11096. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  11097. /*isStmtExpr=*/false);
  11098. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  11099. }
  11100. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  11101. MoveAssignOperator->markUsed(Context);
  11102. if (ASTMutationListener *L = getASTMutationListener()) {
  11103. L->CompletedImplicitDefinition(MoveAssignOperator);
  11104. }
  11105. }
  11106. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  11107. CXXRecordDecl *ClassDecl) {
  11108. // C++ [class.copy]p4:
  11109. // If the class definition does not explicitly declare a copy
  11110. // constructor, one is declared implicitly.
  11111. assert(ClassDecl->needsImplicitCopyConstructor());
  11112. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  11113. if (DSM.isAlreadyBeingDeclared())
  11114. return nullptr;
  11115. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11116. QualType ArgType = ClassType;
  11117. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  11118. if (Const)
  11119. ArgType = ArgType.withConst();
  11120. if (Context.getLangOpts().OpenCLCPlusPlus)
  11121. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  11122. ArgType = Context.getLValueReferenceType(ArgType);
  11123. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11124. CXXCopyConstructor,
  11125. Const);
  11126. DeclarationName Name
  11127. = Context.DeclarationNames.getCXXConstructorName(
  11128. Context.getCanonicalType(ClassType));
  11129. SourceLocation ClassLoc = ClassDecl->getLocation();
  11130. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11131. // An implicitly-declared copy constructor is an inline public
  11132. // member of its class.
  11133. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  11134. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11135. ExplicitSpecifier(),
  11136. /*isInline=*/true,
  11137. /*isImplicitlyDeclared=*/true,
  11138. Constexpr ? CSK_constexpr : CSK_unspecified);
  11139. CopyConstructor->setAccess(AS_public);
  11140. CopyConstructor->setDefaulted();
  11141. if (getLangOpts().CUDA) {
  11142. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  11143. CopyConstructor,
  11144. /* ConstRHS */ Const,
  11145. /* Diagnose */ false);
  11146. }
  11147. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  11148. // Add the parameter to the constructor.
  11149. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  11150. ClassLoc, ClassLoc,
  11151. /*IdentifierInfo=*/nullptr,
  11152. ArgType, /*TInfo=*/nullptr,
  11153. SC_None, nullptr);
  11154. CopyConstructor->setParams(FromParam);
  11155. CopyConstructor->setTrivial(
  11156. ClassDecl->needsOverloadResolutionForCopyConstructor()
  11157. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  11158. : ClassDecl->hasTrivialCopyConstructor());
  11159. CopyConstructor->setTrivialForCall(
  11160. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11161. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  11162. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  11163. TAH_ConsiderTrivialABI)
  11164. : ClassDecl->hasTrivialCopyConstructorForCall()));
  11165. // Note that we have declared this constructor.
  11166. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  11167. Scope *S = getScopeForContext(ClassDecl);
  11168. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  11169. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  11170. ClassDecl->setImplicitCopyConstructorIsDeleted();
  11171. SetDeclDeleted(CopyConstructor, ClassLoc);
  11172. }
  11173. if (S)
  11174. PushOnScopeChains(CopyConstructor, S, false);
  11175. ClassDecl->addDecl(CopyConstructor);
  11176. return CopyConstructor;
  11177. }
  11178. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  11179. CXXConstructorDecl *CopyConstructor) {
  11180. assert((CopyConstructor->isDefaulted() &&
  11181. CopyConstructor->isCopyConstructor() &&
  11182. !CopyConstructor->doesThisDeclarationHaveABody() &&
  11183. !CopyConstructor->isDeleted()) &&
  11184. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  11185. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  11186. return;
  11187. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  11188. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  11189. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  11190. // The exception specification is needed because we are defining the
  11191. // function.
  11192. ResolveExceptionSpec(CurrentLocation,
  11193. CopyConstructor->getType()->castAs<FunctionProtoType>());
  11194. MarkVTableUsed(CurrentLocation, ClassDecl);
  11195. // Add a context note for diagnostics produced after this point.
  11196. Scope.addContextNote(CurrentLocation);
  11197. // C++11 [class.copy]p7:
  11198. // The [definition of an implicitly declared copy constructor] is
  11199. // deprecated if the class has a user-declared copy assignment operator
  11200. // or a user-declared destructor.
  11201. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  11202. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  11203. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  11204. CopyConstructor->setInvalidDecl();
  11205. } else {
  11206. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  11207. ? CopyConstructor->getEndLoc()
  11208. : CopyConstructor->getLocation();
  11209. Sema::CompoundScopeRAII CompoundScope(*this);
  11210. CopyConstructor->setBody(
  11211. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  11212. CopyConstructor->markUsed(Context);
  11213. }
  11214. if (ASTMutationListener *L = getASTMutationListener()) {
  11215. L->CompletedImplicitDefinition(CopyConstructor);
  11216. }
  11217. }
  11218. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  11219. CXXRecordDecl *ClassDecl) {
  11220. assert(ClassDecl->needsImplicitMoveConstructor());
  11221. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  11222. if (DSM.isAlreadyBeingDeclared())
  11223. return nullptr;
  11224. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11225. QualType ArgType = ClassType;
  11226. if (Context.getLangOpts().OpenCLCPlusPlus)
  11227. ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
  11228. ArgType = Context.getRValueReferenceType(ArgType);
  11229. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11230. CXXMoveConstructor,
  11231. false);
  11232. DeclarationName Name
  11233. = Context.DeclarationNames.getCXXConstructorName(
  11234. Context.getCanonicalType(ClassType));
  11235. SourceLocation ClassLoc = ClassDecl->getLocation();
  11236. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11237. // C++11 [class.copy]p11:
  11238. // An implicitly-declared copy/move constructor is an inline public
  11239. // member of its class.
  11240. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  11241. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11242. ExplicitSpecifier(),
  11243. /*isInline=*/true,
  11244. /*isImplicitlyDeclared=*/true,
  11245. Constexpr ? CSK_constexpr : CSK_unspecified);
  11246. MoveConstructor->setAccess(AS_public);
  11247. MoveConstructor->setDefaulted();
  11248. if (getLangOpts().CUDA) {
  11249. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  11250. MoveConstructor,
  11251. /* ConstRHS */ false,
  11252. /* Diagnose */ false);
  11253. }
  11254. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  11255. // Add the parameter to the constructor.
  11256. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  11257. ClassLoc, ClassLoc,
  11258. /*IdentifierInfo=*/nullptr,
  11259. ArgType, /*TInfo=*/nullptr,
  11260. SC_None, nullptr);
  11261. MoveConstructor->setParams(FromParam);
  11262. MoveConstructor->setTrivial(
  11263. ClassDecl->needsOverloadResolutionForMoveConstructor()
  11264. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  11265. : ClassDecl->hasTrivialMoveConstructor());
  11266. MoveConstructor->setTrivialForCall(
  11267. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11268. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  11269. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  11270. TAH_ConsiderTrivialABI)
  11271. : ClassDecl->hasTrivialMoveConstructorForCall()));
  11272. // Note that we have declared this constructor.
  11273. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  11274. Scope *S = getScopeForContext(ClassDecl);
  11275. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  11276. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  11277. ClassDecl->setImplicitMoveConstructorIsDeleted();
  11278. SetDeclDeleted(MoveConstructor, ClassLoc);
  11279. }
  11280. if (S)
  11281. PushOnScopeChains(MoveConstructor, S, false);
  11282. ClassDecl->addDecl(MoveConstructor);
  11283. return MoveConstructor;
  11284. }
  11285. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  11286. CXXConstructorDecl *MoveConstructor) {
  11287. assert((MoveConstructor->isDefaulted() &&
  11288. MoveConstructor->isMoveConstructor() &&
  11289. !MoveConstructor->doesThisDeclarationHaveABody() &&
  11290. !MoveConstructor->isDeleted()) &&
  11291. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  11292. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  11293. return;
  11294. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  11295. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  11296. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  11297. // The exception specification is needed because we are defining the
  11298. // function.
  11299. ResolveExceptionSpec(CurrentLocation,
  11300. MoveConstructor->getType()->castAs<FunctionProtoType>());
  11301. MarkVTableUsed(CurrentLocation, ClassDecl);
  11302. // Add a context note for diagnostics produced after this point.
  11303. Scope.addContextNote(CurrentLocation);
  11304. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  11305. MoveConstructor->setInvalidDecl();
  11306. } else {
  11307. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  11308. ? MoveConstructor->getEndLoc()
  11309. : MoveConstructor->getLocation();
  11310. Sema::CompoundScopeRAII CompoundScope(*this);
  11311. MoveConstructor->setBody(ActOnCompoundStmt(
  11312. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  11313. MoveConstructor->markUsed(Context);
  11314. }
  11315. if (ASTMutationListener *L = getASTMutationListener()) {
  11316. L->CompletedImplicitDefinition(MoveConstructor);
  11317. }
  11318. }
  11319. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  11320. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  11321. }
  11322. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  11323. SourceLocation CurrentLocation,
  11324. CXXConversionDecl *Conv) {
  11325. SynthesizedFunctionScope Scope(*this, Conv);
  11326. assert(!Conv->getReturnType()->isUndeducedType());
  11327. CXXRecordDecl *Lambda = Conv->getParent();
  11328. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  11329. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  11330. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  11331. CallOp = InstantiateFunctionDeclaration(
  11332. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11333. if (!CallOp)
  11334. return;
  11335. Invoker = InstantiateFunctionDeclaration(
  11336. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11337. if (!Invoker)
  11338. return;
  11339. }
  11340. if (CallOp->isInvalidDecl())
  11341. return;
  11342. // Mark the call operator referenced (and add to pending instantiations
  11343. // if necessary).
  11344. // For both the conversion and static-invoker template specializations
  11345. // we construct their body's in this function, so no need to add them
  11346. // to the PendingInstantiations.
  11347. MarkFunctionReferenced(CurrentLocation, CallOp);
  11348. // Fill in the __invoke function with a dummy implementation. IR generation
  11349. // will fill in the actual details. Update its type in case it contained
  11350. // an 'auto'.
  11351. Invoker->markUsed(Context);
  11352. Invoker->setReferenced();
  11353. Invoker->setType(Conv->getReturnType()->getPointeeType());
  11354. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  11355. // Construct the body of the conversion function { return __invoke; }.
  11356. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  11357. VK_LValue, Conv->getLocation());
  11358. assert(FunctionRef && "Can't refer to __invoke function?");
  11359. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  11360. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  11361. Conv->getLocation()));
  11362. Conv->markUsed(Context);
  11363. Conv->setReferenced();
  11364. if (ASTMutationListener *L = getASTMutationListener()) {
  11365. L->CompletedImplicitDefinition(Conv);
  11366. L->CompletedImplicitDefinition(Invoker);
  11367. }
  11368. }
  11369. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  11370. SourceLocation CurrentLocation,
  11371. CXXConversionDecl *Conv)
  11372. {
  11373. assert(!Conv->getParent()->isGenericLambda());
  11374. SynthesizedFunctionScope Scope(*this, Conv);
  11375. // Copy-initialize the lambda object as needed to capture it.
  11376. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11377. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11378. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11379. Conv->getLocation(),
  11380. Conv, DerefThis);
  11381. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11382. // behavior. Note that only the general conversion function does this
  11383. // (since it's unusable otherwise); in the case where we inline the
  11384. // block literal, it has block literal lifetime semantics.
  11385. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11386. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11387. CK_CopyAndAutoreleaseBlockObject,
  11388. BuildBlock.get(), nullptr, VK_RValue);
  11389. if (BuildBlock.isInvalid()) {
  11390. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11391. Conv->setInvalidDecl();
  11392. return;
  11393. }
  11394. // Create the return statement that returns the block from the conversion
  11395. // function.
  11396. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11397. if (Return.isInvalid()) {
  11398. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11399. Conv->setInvalidDecl();
  11400. return;
  11401. }
  11402. // Set the body of the conversion function.
  11403. Stmt *ReturnS = Return.get();
  11404. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11405. Conv->getLocation()));
  11406. Conv->markUsed(Context);
  11407. // We're done; notify the mutation listener, if any.
  11408. if (ASTMutationListener *L = getASTMutationListener()) {
  11409. L->CompletedImplicitDefinition(Conv);
  11410. }
  11411. }
  11412. /// Determine whether the given list arguments contains exactly one
  11413. /// "real" (non-default) argument.
  11414. static bool hasOneRealArgument(MultiExprArg Args) {
  11415. switch (Args.size()) {
  11416. case 0:
  11417. return false;
  11418. default:
  11419. if (!Args[1]->isDefaultArgument())
  11420. return false;
  11421. LLVM_FALLTHROUGH;
  11422. case 1:
  11423. return !Args[0]->isDefaultArgument();
  11424. }
  11425. return false;
  11426. }
  11427. ExprResult
  11428. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11429. NamedDecl *FoundDecl,
  11430. CXXConstructorDecl *Constructor,
  11431. MultiExprArg ExprArgs,
  11432. bool HadMultipleCandidates,
  11433. bool IsListInitialization,
  11434. bool IsStdInitListInitialization,
  11435. bool RequiresZeroInit,
  11436. unsigned ConstructKind,
  11437. SourceRange ParenRange) {
  11438. bool Elidable = false;
  11439. // C++0x [class.copy]p34:
  11440. // When certain criteria are met, an implementation is allowed to
  11441. // omit the copy/move construction of a class object, even if the
  11442. // copy/move constructor and/or destructor for the object have
  11443. // side effects. [...]
  11444. // - when a temporary class object that has not been bound to a
  11445. // reference (12.2) would be copied/moved to a class object
  11446. // with the same cv-unqualified type, the copy/move operation
  11447. // can be omitted by constructing the temporary object
  11448. // directly into the target of the omitted copy/move
  11449. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11450. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11451. Expr *SubExpr = ExprArgs[0];
  11452. Elidable = SubExpr->isTemporaryObject(
  11453. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11454. }
  11455. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11456. FoundDecl, Constructor,
  11457. Elidable, ExprArgs, HadMultipleCandidates,
  11458. IsListInitialization,
  11459. IsStdInitListInitialization, RequiresZeroInit,
  11460. ConstructKind, ParenRange);
  11461. }
  11462. ExprResult
  11463. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11464. NamedDecl *FoundDecl,
  11465. CXXConstructorDecl *Constructor,
  11466. bool Elidable,
  11467. MultiExprArg ExprArgs,
  11468. bool HadMultipleCandidates,
  11469. bool IsListInitialization,
  11470. bool IsStdInitListInitialization,
  11471. bool RequiresZeroInit,
  11472. unsigned ConstructKind,
  11473. SourceRange ParenRange) {
  11474. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11475. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11476. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11477. return ExprError();
  11478. }
  11479. return BuildCXXConstructExpr(
  11480. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11481. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11482. RequiresZeroInit, ConstructKind, ParenRange);
  11483. }
  11484. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11485. /// including handling of its default argument expressions.
  11486. ExprResult
  11487. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11488. CXXConstructorDecl *Constructor,
  11489. bool Elidable,
  11490. MultiExprArg ExprArgs,
  11491. bool HadMultipleCandidates,
  11492. bool IsListInitialization,
  11493. bool IsStdInitListInitialization,
  11494. bool RequiresZeroInit,
  11495. unsigned ConstructKind,
  11496. SourceRange ParenRange) {
  11497. assert(declaresSameEntity(
  11498. Constructor->getParent(),
  11499. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11500. "given constructor for wrong type");
  11501. MarkFunctionReferenced(ConstructLoc, Constructor);
  11502. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11503. return ExprError();
  11504. return CXXConstructExpr::Create(
  11505. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11506. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11507. IsStdInitListInitialization, RequiresZeroInit,
  11508. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11509. ParenRange);
  11510. }
  11511. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11512. assert(Field->hasInClassInitializer());
  11513. // If we already have the in-class initializer nothing needs to be done.
  11514. if (Field->getInClassInitializer())
  11515. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11516. // If we might have already tried and failed to instantiate, don't try again.
  11517. if (Field->isInvalidDecl())
  11518. return ExprError();
  11519. // Maybe we haven't instantiated the in-class initializer. Go check the
  11520. // pattern FieldDecl to see if it has one.
  11521. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11522. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11523. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11524. DeclContext::lookup_result Lookup =
  11525. ClassPattern->lookup(Field->getDeclName());
  11526. // Lookup can return at most two results: the pattern for the field, or the
  11527. // injected class name of the parent record. No other member can have the
  11528. // same name as the field.
  11529. // In modules mode, lookup can return multiple results (coming from
  11530. // different modules).
  11531. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11532. "more than two lookup results for field name");
  11533. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11534. if (!Pattern) {
  11535. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11536. "cannot have other non-field member with same name");
  11537. for (auto L : Lookup)
  11538. if (isa<FieldDecl>(L)) {
  11539. Pattern = cast<FieldDecl>(L);
  11540. break;
  11541. }
  11542. assert(Pattern && "We must have set the Pattern!");
  11543. }
  11544. if (!Pattern->hasInClassInitializer() ||
  11545. InstantiateInClassInitializer(Loc, Field, Pattern,
  11546. getTemplateInstantiationArgs(Field))) {
  11547. // Don't diagnose this again.
  11548. Field->setInvalidDecl();
  11549. return ExprError();
  11550. }
  11551. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11552. }
  11553. // DR1351:
  11554. // If the brace-or-equal-initializer of a non-static data member
  11555. // invokes a defaulted default constructor of its class or of an
  11556. // enclosing class in a potentially evaluated subexpression, the
  11557. // program is ill-formed.
  11558. //
  11559. // This resolution is unworkable: the exception specification of the
  11560. // default constructor can be needed in an unevaluated context, in
  11561. // particular, in the operand of a noexcept-expression, and we can be
  11562. // unable to compute an exception specification for an enclosed class.
  11563. //
  11564. // Any attempt to resolve the exception specification of a defaulted default
  11565. // constructor before the initializer is lexically complete will ultimately
  11566. // come here at which point we can diagnose it.
  11567. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11568. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11569. << OutermostClass << Field;
  11570. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11571. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11572. if (!isSFINAEContext())
  11573. Field->setInvalidDecl();
  11574. return ExprError();
  11575. }
  11576. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11577. if (VD->isInvalidDecl()) return;
  11578. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11579. if (ClassDecl->isInvalidDecl()) return;
  11580. if (ClassDecl->hasIrrelevantDestructor()) return;
  11581. if (ClassDecl->isDependentContext()) return;
  11582. if (VD->isNoDestroy(getASTContext()))
  11583. return;
  11584. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11585. // If this is an array, we'll require the destructor during initialization, so
  11586. // we can skip over this. We still want to emit exit-time destructor warnings
  11587. // though.
  11588. if (!VD->getType()->isArrayType()) {
  11589. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11590. CheckDestructorAccess(VD->getLocation(), Destructor,
  11591. PDiag(diag::err_access_dtor_var)
  11592. << VD->getDeclName() << VD->getType());
  11593. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11594. }
  11595. if (Destructor->isTrivial()) return;
  11596. // If the destructor is constexpr, check whether the variable has constant
  11597. // destruction now.
  11598. if (Destructor->isConstexpr() && VD->getInit() &&
  11599. !VD->getInit()->isValueDependent() && VD->evaluateValue()) {
  11600. SmallVector<PartialDiagnosticAt, 8> Notes;
  11601. if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) {
  11602. Diag(VD->getLocation(),
  11603. diag::err_constexpr_var_requires_const_destruction) << VD;
  11604. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  11605. Diag(Notes[I].first, Notes[I].second);
  11606. }
  11607. }
  11608. if (!VD->hasGlobalStorage()) return;
  11609. // Emit warning for non-trivial dtor in global scope (a real global,
  11610. // class-static, function-static).
  11611. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11612. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11613. if (!VD->isStaticLocal())
  11614. Diag(VD->getLocation(), diag::warn_global_destructor);
  11615. }
  11616. /// Given a constructor and the set of arguments provided for the
  11617. /// constructor, convert the arguments and add any required default arguments
  11618. /// to form a proper call to this constructor.
  11619. ///
  11620. /// \returns true if an error occurred, false otherwise.
  11621. bool
  11622. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11623. MultiExprArg ArgsPtr,
  11624. SourceLocation Loc,
  11625. SmallVectorImpl<Expr*> &ConvertedArgs,
  11626. bool AllowExplicit,
  11627. bool IsListInitialization) {
  11628. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11629. unsigned NumArgs = ArgsPtr.size();
  11630. Expr **Args = ArgsPtr.data();
  11631. const FunctionProtoType *Proto
  11632. = Constructor->getType()->getAs<FunctionProtoType>();
  11633. assert(Proto && "Constructor without a prototype?");
  11634. unsigned NumParams = Proto->getNumParams();
  11635. // If too few arguments are available, we'll fill in the rest with defaults.
  11636. if (NumArgs < NumParams)
  11637. ConvertedArgs.reserve(NumParams);
  11638. else
  11639. ConvertedArgs.reserve(NumArgs);
  11640. VariadicCallType CallType =
  11641. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11642. SmallVector<Expr *, 8> AllArgs;
  11643. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11644. Proto, 0,
  11645. llvm::makeArrayRef(Args, NumArgs),
  11646. AllArgs,
  11647. CallType, AllowExplicit,
  11648. IsListInitialization);
  11649. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11650. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11651. CheckConstructorCall(Constructor,
  11652. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11653. Proto, Loc);
  11654. return Invalid;
  11655. }
  11656. static inline bool
  11657. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11658. const FunctionDecl *FnDecl) {
  11659. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11660. if (isa<NamespaceDecl>(DC)) {
  11661. return SemaRef.Diag(FnDecl->getLocation(),
  11662. diag::err_operator_new_delete_declared_in_namespace)
  11663. << FnDecl->getDeclName();
  11664. }
  11665. if (isa<TranslationUnitDecl>(DC) &&
  11666. FnDecl->getStorageClass() == SC_Static) {
  11667. return SemaRef.Diag(FnDecl->getLocation(),
  11668. diag::err_operator_new_delete_declared_static)
  11669. << FnDecl->getDeclName();
  11670. }
  11671. return false;
  11672. }
  11673. static QualType
  11674. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11675. QualType QTy = PtrTy->getPointeeType();
  11676. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11677. return SemaRef.Context.getPointerType(QTy);
  11678. }
  11679. static inline bool
  11680. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11681. CanQualType ExpectedResultType,
  11682. CanQualType ExpectedFirstParamType,
  11683. unsigned DependentParamTypeDiag,
  11684. unsigned InvalidParamTypeDiag) {
  11685. QualType ResultType =
  11686. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11687. // Check that the result type is not dependent.
  11688. if (ResultType->isDependentType())
  11689. return SemaRef.Diag(FnDecl->getLocation(),
  11690. diag::err_operator_new_delete_dependent_result_type)
  11691. << FnDecl->getDeclName() << ExpectedResultType;
  11692. // The operator is valid on any address space for OpenCL.
  11693. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11694. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11695. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11696. }
  11697. }
  11698. // Check that the result type is what we expect.
  11699. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11700. return SemaRef.Diag(FnDecl->getLocation(),
  11701. diag::err_operator_new_delete_invalid_result_type)
  11702. << FnDecl->getDeclName() << ExpectedResultType;
  11703. // A function template must have at least 2 parameters.
  11704. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11705. return SemaRef.Diag(FnDecl->getLocation(),
  11706. diag::err_operator_new_delete_template_too_few_parameters)
  11707. << FnDecl->getDeclName();
  11708. // The function decl must have at least 1 parameter.
  11709. if (FnDecl->getNumParams() == 0)
  11710. return SemaRef.Diag(FnDecl->getLocation(),
  11711. diag::err_operator_new_delete_too_few_parameters)
  11712. << FnDecl->getDeclName();
  11713. // Check the first parameter type is not dependent.
  11714. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11715. if (FirstParamType->isDependentType())
  11716. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11717. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11718. // Check that the first parameter type is what we expect.
  11719. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11720. // The operator is valid on any address space for OpenCL.
  11721. if (auto *PtrTy =
  11722. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11723. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11724. }
  11725. }
  11726. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11727. ExpectedFirstParamType)
  11728. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11729. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11730. return false;
  11731. }
  11732. static bool
  11733. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11734. // C++ [basic.stc.dynamic.allocation]p1:
  11735. // A program is ill-formed if an allocation function is declared in a
  11736. // namespace scope other than global scope or declared static in global
  11737. // scope.
  11738. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11739. return true;
  11740. CanQualType SizeTy =
  11741. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11742. // C++ [basic.stc.dynamic.allocation]p1:
  11743. // The return type shall be void*. The first parameter shall have type
  11744. // std::size_t.
  11745. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11746. SizeTy,
  11747. diag::err_operator_new_dependent_param_type,
  11748. diag::err_operator_new_param_type))
  11749. return true;
  11750. // C++ [basic.stc.dynamic.allocation]p1:
  11751. // The first parameter shall not have an associated default argument.
  11752. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11753. return SemaRef.Diag(FnDecl->getLocation(),
  11754. diag::err_operator_new_default_arg)
  11755. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11756. return false;
  11757. }
  11758. static bool
  11759. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11760. // C++ [basic.stc.dynamic.deallocation]p1:
  11761. // A program is ill-formed if deallocation functions are declared in a
  11762. // namespace scope other than global scope or declared static in global
  11763. // scope.
  11764. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11765. return true;
  11766. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11767. // C++ P0722:
  11768. // Within a class C, the first parameter of a destroying operator delete
  11769. // shall be of type C *. The first parameter of any other deallocation
  11770. // function shall be of type void *.
  11771. CanQualType ExpectedFirstParamType =
  11772. MD && MD->isDestroyingOperatorDelete()
  11773. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11774. SemaRef.Context.getRecordType(MD->getParent())))
  11775. : SemaRef.Context.VoidPtrTy;
  11776. // C++ [basic.stc.dynamic.deallocation]p2:
  11777. // Each deallocation function shall return void
  11778. if (CheckOperatorNewDeleteTypes(
  11779. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11780. diag::err_operator_delete_dependent_param_type,
  11781. diag::err_operator_delete_param_type))
  11782. return true;
  11783. // C++ P0722:
  11784. // A destroying operator delete shall be a usual deallocation function.
  11785. if (MD && !MD->getParent()->isDependentContext() &&
  11786. MD->isDestroyingOperatorDelete() &&
  11787. !SemaRef.isUsualDeallocationFunction(MD)) {
  11788. SemaRef.Diag(MD->getLocation(),
  11789. diag::err_destroying_operator_delete_not_usual);
  11790. return true;
  11791. }
  11792. return false;
  11793. }
  11794. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11795. /// of this overloaded operator is well-formed. If so, returns false;
  11796. /// otherwise, emits appropriate diagnostics and returns true.
  11797. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11798. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11799. "Expected an overloaded operator declaration");
  11800. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11801. // C++ [over.oper]p5:
  11802. // The allocation and deallocation functions, operator new,
  11803. // operator new[], operator delete and operator delete[], are
  11804. // described completely in 3.7.3. The attributes and restrictions
  11805. // found in the rest of this subclause do not apply to them unless
  11806. // explicitly stated in 3.7.3.
  11807. if (Op == OO_Delete || Op == OO_Array_Delete)
  11808. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11809. if (Op == OO_New || Op == OO_Array_New)
  11810. return CheckOperatorNewDeclaration(*this, FnDecl);
  11811. // C++ [over.oper]p6:
  11812. // An operator function shall either be a non-static member
  11813. // function or be a non-member function and have at least one
  11814. // parameter whose type is a class, a reference to a class, an
  11815. // enumeration, or a reference to an enumeration.
  11816. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11817. if (MethodDecl->isStatic())
  11818. return Diag(FnDecl->getLocation(),
  11819. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11820. } else {
  11821. bool ClassOrEnumParam = false;
  11822. for (auto Param : FnDecl->parameters()) {
  11823. QualType ParamType = Param->getType().getNonReferenceType();
  11824. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11825. ParamType->isEnumeralType()) {
  11826. ClassOrEnumParam = true;
  11827. break;
  11828. }
  11829. }
  11830. if (!ClassOrEnumParam)
  11831. return Diag(FnDecl->getLocation(),
  11832. diag::err_operator_overload_needs_class_or_enum)
  11833. << FnDecl->getDeclName();
  11834. }
  11835. // C++ [over.oper]p8:
  11836. // An operator function cannot have default arguments (8.3.6),
  11837. // except where explicitly stated below.
  11838. //
  11839. // Only the function-call operator allows default arguments
  11840. // (C++ [over.call]p1).
  11841. if (Op != OO_Call) {
  11842. for (auto Param : FnDecl->parameters()) {
  11843. if (Param->hasDefaultArg())
  11844. return Diag(Param->getLocation(),
  11845. diag::err_operator_overload_default_arg)
  11846. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11847. }
  11848. }
  11849. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11850. { false, false, false }
  11851. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11852. , { Unary, Binary, MemberOnly }
  11853. #include "clang/Basic/OperatorKinds.def"
  11854. };
  11855. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11856. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11857. bool MustBeMemberOperator = OperatorUses[Op][2];
  11858. // C++ [over.oper]p8:
  11859. // [...] Operator functions cannot have more or fewer parameters
  11860. // than the number required for the corresponding operator, as
  11861. // described in the rest of this subclause.
  11862. unsigned NumParams = FnDecl->getNumParams()
  11863. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11864. if (Op != OO_Call &&
  11865. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11866. (NumParams == 2 && !CanBeBinaryOperator) ||
  11867. (NumParams < 1) || (NumParams > 2))) {
  11868. // We have the wrong number of parameters.
  11869. unsigned ErrorKind;
  11870. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11871. ErrorKind = 2; // 2 -> unary or binary.
  11872. } else if (CanBeUnaryOperator) {
  11873. ErrorKind = 0; // 0 -> unary
  11874. } else {
  11875. assert(CanBeBinaryOperator &&
  11876. "All non-call overloaded operators are unary or binary!");
  11877. ErrorKind = 1; // 1 -> binary
  11878. }
  11879. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11880. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11881. }
  11882. // Overloaded operators other than operator() cannot be variadic.
  11883. if (Op != OO_Call &&
  11884. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11885. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11886. << FnDecl->getDeclName();
  11887. }
  11888. // Some operators must be non-static member functions.
  11889. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11890. return Diag(FnDecl->getLocation(),
  11891. diag::err_operator_overload_must_be_member)
  11892. << FnDecl->getDeclName();
  11893. }
  11894. // C++ [over.inc]p1:
  11895. // The user-defined function called operator++ implements the
  11896. // prefix and postfix ++ operator. If this function is a member
  11897. // function with no parameters, or a non-member function with one
  11898. // parameter of class or enumeration type, it defines the prefix
  11899. // increment operator ++ for objects of that type. If the function
  11900. // is a member function with one parameter (which shall be of type
  11901. // int) or a non-member function with two parameters (the second
  11902. // of which shall be of type int), it defines the postfix
  11903. // increment operator ++ for objects of that type.
  11904. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11905. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11906. QualType ParamType = LastParam->getType();
  11907. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11908. !ParamType->isDependentType())
  11909. return Diag(LastParam->getLocation(),
  11910. diag::err_operator_overload_post_incdec_must_be_int)
  11911. << LastParam->getType() << (Op == OO_MinusMinus);
  11912. }
  11913. return false;
  11914. }
  11915. static bool
  11916. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11917. FunctionTemplateDecl *TpDecl) {
  11918. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11919. // Must have one or two template parameters.
  11920. if (TemplateParams->size() == 1) {
  11921. NonTypeTemplateParmDecl *PmDecl =
  11922. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11923. // The template parameter must be a char parameter pack.
  11924. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11925. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11926. return false;
  11927. } else if (TemplateParams->size() == 2) {
  11928. TemplateTypeParmDecl *PmType =
  11929. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11930. NonTypeTemplateParmDecl *PmArgs =
  11931. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11932. // The second template parameter must be a parameter pack with the
  11933. // first template parameter as its type.
  11934. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11935. PmArgs->isTemplateParameterPack()) {
  11936. const TemplateTypeParmType *TArgs =
  11937. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11938. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11939. TArgs->getIndex() == PmType->getIndex()) {
  11940. if (!SemaRef.inTemplateInstantiation())
  11941. SemaRef.Diag(TpDecl->getLocation(),
  11942. diag::ext_string_literal_operator_template);
  11943. return false;
  11944. }
  11945. }
  11946. }
  11947. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11948. diag::err_literal_operator_template)
  11949. << TpDecl->getTemplateParameters()->getSourceRange();
  11950. return true;
  11951. }
  11952. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11953. /// of this literal operator function is well-formed. If so, returns
  11954. /// false; otherwise, emits appropriate diagnostics and returns true.
  11955. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11956. if (isa<CXXMethodDecl>(FnDecl)) {
  11957. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11958. << FnDecl->getDeclName();
  11959. return true;
  11960. }
  11961. if (FnDecl->isExternC()) {
  11962. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11963. if (const LinkageSpecDecl *LSD =
  11964. FnDecl->getDeclContext()->getExternCContext())
  11965. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11966. return true;
  11967. }
  11968. // This might be the definition of a literal operator template.
  11969. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11970. // This might be a specialization of a literal operator template.
  11971. if (!TpDecl)
  11972. TpDecl = FnDecl->getPrimaryTemplate();
  11973. // template <char...> type operator "" name() and
  11974. // template <class T, T...> type operator "" name() are the only valid
  11975. // template signatures, and the only valid signatures with no parameters.
  11976. if (TpDecl) {
  11977. if (FnDecl->param_size() != 0) {
  11978. Diag(FnDecl->getLocation(),
  11979. diag::err_literal_operator_template_with_params);
  11980. return true;
  11981. }
  11982. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11983. return true;
  11984. } else if (FnDecl->param_size() == 1) {
  11985. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11986. QualType ParamType = Param->getType().getUnqualifiedType();
  11987. // Only unsigned long long int, long double, any character type, and const
  11988. // char * are allowed as the only parameters.
  11989. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11990. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11991. Context.hasSameType(ParamType, Context.CharTy) ||
  11992. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11993. Context.hasSameType(ParamType, Context.Char8Ty) ||
  11994. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11995. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11996. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11997. QualType InnerType = Ptr->getPointeeType();
  11998. // Pointer parameter must be a const char *.
  11999. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  12000. Context.CharTy) &&
  12001. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  12002. Diag(Param->getSourceRange().getBegin(),
  12003. diag::err_literal_operator_param)
  12004. << ParamType << "'const char *'" << Param->getSourceRange();
  12005. return true;
  12006. }
  12007. } else if (ParamType->isRealFloatingType()) {
  12008. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  12009. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  12010. return true;
  12011. } else if (ParamType->isIntegerType()) {
  12012. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  12013. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  12014. return true;
  12015. } else {
  12016. Diag(Param->getSourceRange().getBegin(),
  12017. diag::err_literal_operator_invalid_param)
  12018. << ParamType << Param->getSourceRange();
  12019. return true;
  12020. }
  12021. } else if (FnDecl->param_size() == 2) {
  12022. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  12023. // First, verify that the first parameter is correct.
  12024. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  12025. // Two parameter function must have a pointer to const as a
  12026. // first parameter; let's strip those qualifiers.
  12027. const PointerType *PT = FirstParamType->getAs<PointerType>();
  12028. if (!PT) {
  12029. Diag((*Param)->getSourceRange().getBegin(),
  12030. diag::err_literal_operator_param)
  12031. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12032. return true;
  12033. }
  12034. QualType PointeeType = PT->getPointeeType();
  12035. // First parameter must be const
  12036. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  12037. Diag((*Param)->getSourceRange().getBegin(),
  12038. diag::err_literal_operator_param)
  12039. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12040. return true;
  12041. }
  12042. QualType InnerType = PointeeType.getUnqualifiedType();
  12043. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  12044. // const char32_t* are allowed as the first parameter to a two-parameter
  12045. // function
  12046. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  12047. Context.hasSameType(InnerType, Context.WideCharTy) ||
  12048. Context.hasSameType(InnerType, Context.Char8Ty) ||
  12049. Context.hasSameType(InnerType, Context.Char16Ty) ||
  12050. Context.hasSameType(InnerType, Context.Char32Ty))) {
  12051. Diag((*Param)->getSourceRange().getBegin(),
  12052. diag::err_literal_operator_param)
  12053. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  12054. return true;
  12055. }
  12056. // Move on to the second and final parameter.
  12057. ++Param;
  12058. // The second parameter must be a std::size_t.
  12059. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  12060. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  12061. Diag((*Param)->getSourceRange().getBegin(),
  12062. diag::err_literal_operator_param)
  12063. << SecondParamType << Context.getSizeType()
  12064. << (*Param)->getSourceRange();
  12065. return true;
  12066. }
  12067. } else {
  12068. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  12069. return true;
  12070. }
  12071. // Parameters are good.
  12072. // A parameter-declaration-clause containing a default argument is not
  12073. // equivalent to any of the permitted forms.
  12074. for (auto Param : FnDecl->parameters()) {
  12075. if (Param->hasDefaultArg()) {
  12076. Diag(Param->getDefaultArgRange().getBegin(),
  12077. diag::err_literal_operator_default_argument)
  12078. << Param->getDefaultArgRange();
  12079. break;
  12080. }
  12081. }
  12082. StringRef LiteralName
  12083. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  12084. if (LiteralName[0] != '_' &&
  12085. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  12086. // C++11 [usrlit.suffix]p1:
  12087. // Literal suffix identifiers that do not start with an underscore
  12088. // are reserved for future standardization.
  12089. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  12090. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  12091. }
  12092. return false;
  12093. }
  12094. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  12095. /// linkage specification, including the language and (if present)
  12096. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  12097. /// language string literal. LBraceLoc, if valid, provides the location of
  12098. /// the '{' brace. Otherwise, this linkage specification does not
  12099. /// have any braces.
  12100. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  12101. Expr *LangStr,
  12102. SourceLocation LBraceLoc) {
  12103. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  12104. if (!Lit->isAscii()) {
  12105. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  12106. << LangStr->getSourceRange();
  12107. return nullptr;
  12108. }
  12109. StringRef Lang = Lit->getString();
  12110. LinkageSpecDecl::LanguageIDs Language;
  12111. if (Lang == "C")
  12112. Language = LinkageSpecDecl::lang_c;
  12113. else if (Lang == "C++")
  12114. Language = LinkageSpecDecl::lang_cxx;
  12115. else if (Lang == "C++11")
  12116. Language = LinkageSpecDecl::lang_cxx_11;
  12117. else if (Lang == "C++14")
  12118. Language = LinkageSpecDecl::lang_cxx_14;
  12119. else {
  12120. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  12121. << LangStr->getSourceRange();
  12122. return nullptr;
  12123. }
  12124. // FIXME: Add all the various semantics of linkage specifications
  12125. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  12126. LangStr->getExprLoc(), Language,
  12127. LBraceLoc.isValid());
  12128. CurContext->addDecl(D);
  12129. PushDeclContext(S, D);
  12130. return D;
  12131. }
  12132. /// ActOnFinishLinkageSpecification - Complete the definition of
  12133. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  12134. /// valid, it's the position of the closing '}' brace in a linkage
  12135. /// specification that uses braces.
  12136. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  12137. Decl *LinkageSpec,
  12138. SourceLocation RBraceLoc) {
  12139. if (RBraceLoc.isValid()) {
  12140. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  12141. LSDecl->setRBraceLoc(RBraceLoc);
  12142. }
  12143. PopDeclContext();
  12144. return LinkageSpec;
  12145. }
  12146. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  12147. const ParsedAttributesView &AttrList,
  12148. SourceLocation SemiLoc) {
  12149. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  12150. // Attribute declarations appertain to empty declaration so we handle
  12151. // them here.
  12152. ProcessDeclAttributeList(S, ED, AttrList);
  12153. CurContext->addDecl(ED);
  12154. return ED;
  12155. }
  12156. /// Perform semantic analysis for the variable declaration that
  12157. /// occurs within a C++ catch clause, returning the newly-created
  12158. /// variable.
  12159. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  12160. TypeSourceInfo *TInfo,
  12161. SourceLocation StartLoc,
  12162. SourceLocation Loc,
  12163. IdentifierInfo *Name) {
  12164. bool Invalid = false;
  12165. QualType ExDeclType = TInfo->getType();
  12166. // Arrays and functions decay.
  12167. if (ExDeclType->isArrayType())
  12168. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  12169. else if (ExDeclType->isFunctionType())
  12170. ExDeclType = Context.getPointerType(ExDeclType);
  12171. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  12172. // The exception-declaration shall not denote a pointer or reference to an
  12173. // incomplete type, other than [cv] void*.
  12174. // N2844 forbids rvalue references.
  12175. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  12176. Diag(Loc, diag::err_catch_rvalue_ref);
  12177. Invalid = true;
  12178. }
  12179. if (ExDeclType->isVariablyModifiedType()) {
  12180. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  12181. Invalid = true;
  12182. }
  12183. QualType BaseType = ExDeclType;
  12184. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  12185. unsigned DK = diag::err_catch_incomplete;
  12186. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  12187. BaseType = Ptr->getPointeeType();
  12188. Mode = 1;
  12189. DK = diag::err_catch_incomplete_ptr;
  12190. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  12191. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  12192. BaseType = Ref->getPointeeType();
  12193. Mode = 2;
  12194. DK = diag::err_catch_incomplete_ref;
  12195. }
  12196. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  12197. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  12198. Invalid = true;
  12199. if (!Invalid && !ExDeclType->isDependentType() &&
  12200. RequireNonAbstractType(Loc, ExDeclType,
  12201. diag::err_abstract_type_in_decl,
  12202. AbstractVariableType))
  12203. Invalid = true;
  12204. // Only the non-fragile NeXT runtime currently supports C++ catches
  12205. // of ObjC types, and no runtime supports catching ObjC types by value.
  12206. if (!Invalid && getLangOpts().ObjC) {
  12207. QualType T = ExDeclType;
  12208. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  12209. T = RT->getPointeeType();
  12210. if (T->isObjCObjectType()) {
  12211. Diag(Loc, diag::err_objc_object_catch);
  12212. Invalid = true;
  12213. } else if (T->isObjCObjectPointerType()) {
  12214. // FIXME: should this be a test for macosx-fragile specifically?
  12215. if (getLangOpts().ObjCRuntime.isFragile())
  12216. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  12217. }
  12218. }
  12219. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  12220. ExDeclType, TInfo, SC_None);
  12221. ExDecl->setExceptionVariable(true);
  12222. // In ARC, infer 'retaining' for variables of retainable type.
  12223. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  12224. Invalid = true;
  12225. if (!Invalid && !ExDeclType->isDependentType()) {
  12226. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  12227. // Insulate this from anything else we might currently be parsing.
  12228. EnterExpressionEvaluationContext scope(
  12229. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12230. // C++ [except.handle]p16:
  12231. // The object declared in an exception-declaration or, if the
  12232. // exception-declaration does not specify a name, a temporary (12.2) is
  12233. // copy-initialized (8.5) from the exception object. [...]
  12234. // The object is destroyed when the handler exits, after the destruction
  12235. // of any automatic objects initialized within the handler.
  12236. //
  12237. // We just pretend to initialize the object with itself, then make sure
  12238. // it can be destroyed later.
  12239. QualType initType = Context.getExceptionObjectType(ExDeclType);
  12240. InitializedEntity entity =
  12241. InitializedEntity::InitializeVariable(ExDecl);
  12242. InitializationKind initKind =
  12243. InitializationKind::CreateCopy(Loc, SourceLocation());
  12244. Expr *opaqueValue =
  12245. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  12246. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  12247. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  12248. if (result.isInvalid())
  12249. Invalid = true;
  12250. else {
  12251. // If the constructor used was non-trivial, set this as the
  12252. // "initializer".
  12253. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  12254. if (!construct->getConstructor()->isTrivial()) {
  12255. Expr *init = MaybeCreateExprWithCleanups(construct);
  12256. ExDecl->setInit(init);
  12257. }
  12258. // And make sure it's destructable.
  12259. FinalizeVarWithDestructor(ExDecl, recordType);
  12260. }
  12261. }
  12262. }
  12263. if (Invalid)
  12264. ExDecl->setInvalidDecl();
  12265. return ExDecl;
  12266. }
  12267. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  12268. /// handler.
  12269. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  12270. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12271. bool Invalid = D.isInvalidType();
  12272. // Check for unexpanded parameter packs.
  12273. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12274. UPPC_ExceptionType)) {
  12275. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  12276. D.getIdentifierLoc());
  12277. Invalid = true;
  12278. }
  12279. IdentifierInfo *II = D.getIdentifier();
  12280. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  12281. LookupOrdinaryName,
  12282. ForVisibleRedeclaration)) {
  12283. // The scope should be freshly made just for us. There is just no way
  12284. // it contains any previous declaration, except for function parameters in
  12285. // a function-try-block's catch statement.
  12286. assert(!S->isDeclScope(PrevDecl));
  12287. if (isDeclInScope(PrevDecl, CurContext, S)) {
  12288. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  12289. << D.getIdentifier();
  12290. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12291. Invalid = true;
  12292. } else if (PrevDecl->isTemplateParameter())
  12293. // Maybe we will complain about the shadowed template parameter.
  12294. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12295. }
  12296. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  12297. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  12298. << D.getCXXScopeSpec().getRange();
  12299. Invalid = true;
  12300. }
  12301. VarDecl *ExDecl = BuildExceptionDeclaration(
  12302. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  12303. if (Invalid)
  12304. ExDecl->setInvalidDecl();
  12305. // Add the exception declaration into this scope.
  12306. if (II)
  12307. PushOnScopeChains(ExDecl, S);
  12308. else
  12309. CurContext->addDecl(ExDecl);
  12310. ProcessDeclAttributes(S, ExDecl, D);
  12311. return ExDecl;
  12312. }
  12313. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12314. Expr *AssertExpr,
  12315. Expr *AssertMessageExpr,
  12316. SourceLocation RParenLoc) {
  12317. StringLiteral *AssertMessage =
  12318. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  12319. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  12320. return nullptr;
  12321. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  12322. AssertMessage, RParenLoc, false);
  12323. }
  12324. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12325. Expr *AssertExpr,
  12326. StringLiteral *AssertMessage,
  12327. SourceLocation RParenLoc,
  12328. bool Failed) {
  12329. assert(AssertExpr != nullptr && "Expected non-null condition");
  12330. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  12331. !Failed) {
  12332. // In a static_assert-declaration, the constant-expression shall be a
  12333. // constant expression that can be contextually converted to bool.
  12334. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  12335. if (Converted.isInvalid())
  12336. Failed = true;
  12337. ExprResult FullAssertExpr =
  12338. ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
  12339. /*DiscardedValue*/ false,
  12340. /*IsConstexpr*/ true);
  12341. if (FullAssertExpr.isInvalid())
  12342. Failed = true;
  12343. else
  12344. AssertExpr = FullAssertExpr.get();
  12345. llvm::APSInt Cond;
  12346. if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
  12347. diag::err_static_assert_expression_is_not_constant,
  12348. /*AllowFold=*/false).isInvalid())
  12349. Failed = true;
  12350. if (!Failed && !Cond) {
  12351. SmallString<256> MsgBuffer;
  12352. llvm::raw_svector_ostream Msg(MsgBuffer);
  12353. if (AssertMessage)
  12354. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  12355. Expr *InnerCond = nullptr;
  12356. std::string InnerCondDescription;
  12357. std::tie(InnerCond, InnerCondDescription) =
  12358. findFailedBooleanCondition(Converted.get());
  12359. if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  12360. && !isa<IntegerLiteral>(InnerCond)) {
  12361. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  12362. << InnerCondDescription << !AssertMessage
  12363. << Msg.str() << InnerCond->getSourceRange();
  12364. } else {
  12365. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  12366. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  12367. }
  12368. Failed = true;
  12369. }
  12370. } else {
  12371. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  12372. /*DiscardedValue*/false,
  12373. /*IsConstexpr*/true);
  12374. if (FullAssertExpr.isInvalid())
  12375. Failed = true;
  12376. else
  12377. AssertExpr = FullAssertExpr.get();
  12378. }
  12379. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  12380. AssertExpr, AssertMessage, RParenLoc,
  12381. Failed);
  12382. CurContext->addDecl(Decl);
  12383. return Decl;
  12384. }
  12385. /// Perform semantic analysis of the given friend type declaration.
  12386. ///
  12387. /// \returns A friend declaration that.
  12388. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  12389. SourceLocation FriendLoc,
  12390. TypeSourceInfo *TSInfo) {
  12391. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  12392. QualType T = TSInfo->getType();
  12393. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  12394. // C++03 [class.friend]p2:
  12395. // An elaborated-type-specifier shall be used in a friend declaration
  12396. // for a class.*
  12397. //
  12398. // * The class-key of the elaborated-type-specifier is required.
  12399. if (!CodeSynthesisContexts.empty()) {
  12400. // Do not complain about the form of friend template types during any kind
  12401. // of code synthesis. For template instantiation, we will have complained
  12402. // when the template was defined.
  12403. } else {
  12404. if (!T->isElaboratedTypeSpecifier()) {
  12405. // If we evaluated the type to a record type, suggest putting
  12406. // a tag in front.
  12407. if (const RecordType *RT = T->getAs<RecordType>()) {
  12408. RecordDecl *RD = RT->getDecl();
  12409. SmallString<16> InsertionText(" ");
  12410. InsertionText += RD->getKindName();
  12411. Diag(TypeRange.getBegin(),
  12412. getLangOpts().CPlusPlus11 ?
  12413. diag::warn_cxx98_compat_unelaborated_friend_type :
  12414. diag::ext_unelaborated_friend_type)
  12415. << (unsigned) RD->getTagKind()
  12416. << T
  12417. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12418. InsertionText);
  12419. } else {
  12420. Diag(FriendLoc,
  12421. getLangOpts().CPlusPlus11 ?
  12422. diag::warn_cxx98_compat_nonclass_type_friend :
  12423. diag::ext_nonclass_type_friend)
  12424. << T
  12425. << TypeRange;
  12426. }
  12427. } else if (T->getAs<EnumType>()) {
  12428. Diag(FriendLoc,
  12429. getLangOpts().CPlusPlus11 ?
  12430. diag::warn_cxx98_compat_enum_friend :
  12431. diag::ext_enum_friend)
  12432. << T
  12433. << TypeRange;
  12434. }
  12435. // C++11 [class.friend]p3:
  12436. // A friend declaration that does not declare a function shall have one
  12437. // of the following forms:
  12438. // friend elaborated-type-specifier ;
  12439. // friend simple-type-specifier ;
  12440. // friend typename-specifier ;
  12441. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12442. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12443. }
  12444. // If the type specifier in a friend declaration designates a (possibly
  12445. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12446. // the friend declaration is ignored.
  12447. return FriendDecl::Create(Context, CurContext,
  12448. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12449. FriendLoc);
  12450. }
  12451. /// Handle a friend tag declaration where the scope specifier was
  12452. /// templated.
  12453. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12454. unsigned TagSpec, SourceLocation TagLoc,
  12455. CXXScopeSpec &SS, IdentifierInfo *Name,
  12456. SourceLocation NameLoc,
  12457. const ParsedAttributesView &Attr,
  12458. MultiTemplateParamsArg TempParamLists) {
  12459. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12460. bool IsMemberSpecialization = false;
  12461. bool Invalid = false;
  12462. if (TemplateParameterList *TemplateParams =
  12463. MatchTemplateParametersToScopeSpecifier(
  12464. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12465. IsMemberSpecialization, Invalid)) {
  12466. if (TemplateParams->size() > 0) {
  12467. // This is a declaration of a class template.
  12468. if (Invalid)
  12469. return nullptr;
  12470. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12471. NameLoc, Attr, TemplateParams, AS_public,
  12472. /*ModulePrivateLoc=*/SourceLocation(),
  12473. FriendLoc, TempParamLists.size() - 1,
  12474. TempParamLists.data()).get();
  12475. } else {
  12476. // The "template<>" header is extraneous.
  12477. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12478. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12479. IsMemberSpecialization = true;
  12480. }
  12481. }
  12482. if (Invalid) return nullptr;
  12483. bool isAllExplicitSpecializations = true;
  12484. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12485. if (TempParamLists[I]->size()) {
  12486. isAllExplicitSpecializations = false;
  12487. break;
  12488. }
  12489. }
  12490. // FIXME: don't ignore attributes.
  12491. // If it's explicit specializations all the way down, just forget
  12492. // about the template header and build an appropriate non-templated
  12493. // friend. TODO: for source fidelity, remember the headers.
  12494. if (isAllExplicitSpecializations) {
  12495. if (SS.isEmpty()) {
  12496. bool Owned = false;
  12497. bool IsDependent = false;
  12498. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12499. Attr, AS_public,
  12500. /*ModulePrivateLoc=*/SourceLocation(),
  12501. MultiTemplateParamsArg(), Owned, IsDependent,
  12502. /*ScopedEnumKWLoc=*/SourceLocation(),
  12503. /*ScopedEnumUsesClassTag=*/false,
  12504. /*UnderlyingType=*/TypeResult(),
  12505. /*IsTypeSpecifier=*/false,
  12506. /*IsTemplateParamOrArg=*/false);
  12507. }
  12508. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12509. ElaboratedTypeKeyword Keyword
  12510. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12511. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12512. *Name, NameLoc);
  12513. if (T.isNull())
  12514. return nullptr;
  12515. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12516. if (isa<DependentNameType>(T)) {
  12517. DependentNameTypeLoc TL =
  12518. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12519. TL.setElaboratedKeywordLoc(TagLoc);
  12520. TL.setQualifierLoc(QualifierLoc);
  12521. TL.setNameLoc(NameLoc);
  12522. } else {
  12523. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12524. TL.setElaboratedKeywordLoc(TagLoc);
  12525. TL.setQualifierLoc(QualifierLoc);
  12526. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12527. }
  12528. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12529. TSI, FriendLoc, TempParamLists);
  12530. Friend->setAccess(AS_public);
  12531. CurContext->addDecl(Friend);
  12532. return Friend;
  12533. }
  12534. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12535. // Handle the case of a templated-scope friend class. e.g.
  12536. // template <class T> class A<T>::B;
  12537. // FIXME: we don't support these right now.
  12538. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12539. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12540. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12541. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12542. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12543. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12544. TL.setElaboratedKeywordLoc(TagLoc);
  12545. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12546. TL.setNameLoc(NameLoc);
  12547. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12548. TSI, FriendLoc, TempParamLists);
  12549. Friend->setAccess(AS_public);
  12550. Friend->setUnsupportedFriend(true);
  12551. CurContext->addDecl(Friend);
  12552. return Friend;
  12553. }
  12554. /// Handle a friend type declaration. This works in tandem with
  12555. /// ActOnTag.
  12556. ///
  12557. /// Notes on friend class templates:
  12558. ///
  12559. /// We generally treat friend class declarations as if they were
  12560. /// declaring a class. So, for example, the elaborated type specifier
  12561. /// in a friend declaration is required to obey the restrictions of a
  12562. /// class-head (i.e. no typedefs in the scope chain), template
  12563. /// parameters are required to match up with simple template-ids, &c.
  12564. /// However, unlike when declaring a template specialization, it's
  12565. /// okay to refer to a template specialization without an empty
  12566. /// template parameter declaration, e.g.
  12567. /// friend class A<T>::B<unsigned>;
  12568. /// We permit this as a special case; if there are any template
  12569. /// parameters present at all, require proper matching, i.e.
  12570. /// template <> template \<class T> friend class A<int>::B;
  12571. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12572. MultiTemplateParamsArg TempParams) {
  12573. SourceLocation Loc = DS.getBeginLoc();
  12574. assert(DS.isFriendSpecified());
  12575. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12576. // C++ [class.friend]p3:
  12577. // A friend declaration that does not declare a function shall have one of
  12578. // the following forms:
  12579. // friend elaborated-type-specifier ;
  12580. // friend simple-type-specifier ;
  12581. // friend typename-specifier ;
  12582. //
  12583. // Any declaration with a type qualifier does not have that form. (It's
  12584. // legal to specify a qualified type as a friend, you just can't write the
  12585. // keywords.)
  12586. if (DS.getTypeQualifiers()) {
  12587. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12588. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12589. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12590. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12591. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12592. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12593. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12594. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12595. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12596. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12597. }
  12598. // Try to convert the decl specifier to a type. This works for
  12599. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12600. // for a TUK_Friend.
  12601. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12602. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12603. QualType T = TSI->getType();
  12604. if (TheDeclarator.isInvalidType())
  12605. return nullptr;
  12606. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12607. return nullptr;
  12608. // This is definitely an error in C++98. It's probably meant to
  12609. // be forbidden in C++0x, too, but the specification is just
  12610. // poorly written.
  12611. //
  12612. // The problem is with declarations like the following:
  12613. // template <T> friend A<T>::foo;
  12614. // where deciding whether a class C is a friend or not now hinges
  12615. // on whether there exists an instantiation of A that causes
  12616. // 'foo' to equal C. There are restrictions on class-heads
  12617. // (which we declare (by fiat) elaborated friend declarations to
  12618. // be) that makes this tractable.
  12619. //
  12620. // FIXME: handle "template <> friend class A<T>;", which
  12621. // is possibly well-formed? Who even knows?
  12622. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12623. Diag(Loc, diag::err_tagless_friend_type_template)
  12624. << DS.getSourceRange();
  12625. return nullptr;
  12626. }
  12627. // C++98 [class.friend]p1: A friend of a class is a function
  12628. // or class that is not a member of the class . . .
  12629. // This is fixed in DR77, which just barely didn't make the C++03
  12630. // deadline. It's also a very silly restriction that seriously
  12631. // affects inner classes and which nobody else seems to implement;
  12632. // thus we never diagnose it, not even in -pedantic.
  12633. //
  12634. // But note that we could warn about it: it's always useless to
  12635. // friend one of your own members (it's not, however, worthless to
  12636. // friend a member of an arbitrary specialization of your template).
  12637. Decl *D;
  12638. if (!TempParams.empty())
  12639. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12640. TempParams,
  12641. TSI,
  12642. DS.getFriendSpecLoc());
  12643. else
  12644. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12645. if (!D)
  12646. return nullptr;
  12647. D->setAccess(AS_public);
  12648. CurContext->addDecl(D);
  12649. return D;
  12650. }
  12651. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12652. MultiTemplateParamsArg TemplateParams) {
  12653. const DeclSpec &DS = D.getDeclSpec();
  12654. assert(DS.isFriendSpecified());
  12655. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12656. SourceLocation Loc = D.getIdentifierLoc();
  12657. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12658. // C++ [class.friend]p1
  12659. // A friend of a class is a function or class....
  12660. // Note that this sees through typedefs, which is intended.
  12661. // It *doesn't* see through dependent types, which is correct
  12662. // according to [temp.arg.type]p3:
  12663. // If a declaration acquires a function type through a
  12664. // type dependent on a template-parameter and this causes
  12665. // a declaration that does not use the syntactic form of a
  12666. // function declarator to have a function type, the program
  12667. // is ill-formed.
  12668. if (!TInfo->getType()->isFunctionType()) {
  12669. Diag(Loc, diag::err_unexpected_friend);
  12670. // It might be worthwhile to try to recover by creating an
  12671. // appropriate declaration.
  12672. return nullptr;
  12673. }
  12674. // C++ [namespace.memdef]p3
  12675. // - If a friend declaration in a non-local class first declares a
  12676. // class or function, the friend class or function is a member
  12677. // of the innermost enclosing namespace.
  12678. // - The name of the friend is not found by simple name lookup
  12679. // until a matching declaration is provided in that namespace
  12680. // scope (either before or after the class declaration granting
  12681. // friendship).
  12682. // - If a friend function is called, its name may be found by the
  12683. // name lookup that considers functions from namespaces and
  12684. // classes associated with the types of the function arguments.
  12685. // - When looking for a prior declaration of a class or a function
  12686. // declared as a friend, scopes outside the innermost enclosing
  12687. // namespace scope are not considered.
  12688. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12689. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12690. assert(NameInfo.getName());
  12691. // Check for unexpanded parameter packs.
  12692. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12693. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12694. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12695. return nullptr;
  12696. // The context we found the declaration in, or in which we should
  12697. // create the declaration.
  12698. DeclContext *DC;
  12699. Scope *DCScope = S;
  12700. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12701. ForExternalRedeclaration);
  12702. // There are five cases here.
  12703. // - There's no scope specifier and we're in a local class. Only look
  12704. // for functions declared in the immediately-enclosing block scope.
  12705. // We recover from invalid scope qualifiers as if they just weren't there.
  12706. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12707. if ((SS.isInvalid() || !SS.isSet()) &&
  12708. (FunctionContainingLocalClass =
  12709. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12710. // C++11 [class.friend]p11:
  12711. // If a friend declaration appears in a local class and the name
  12712. // specified is an unqualified name, a prior declaration is
  12713. // looked up without considering scopes that are outside the
  12714. // innermost enclosing non-class scope. For a friend function
  12715. // declaration, if there is no prior declaration, the program is
  12716. // ill-formed.
  12717. // Find the innermost enclosing non-class scope. This is the block
  12718. // scope containing the local class definition (or for a nested class,
  12719. // the outer local class).
  12720. DCScope = S->getFnParent();
  12721. // Look up the function name in the scope.
  12722. Previous.clear(LookupLocalFriendName);
  12723. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12724. if (!Previous.empty()) {
  12725. // All possible previous declarations must have the same context:
  12726. // either they were declared at block scope or they are members of
  12727. // one of the enclosing local classes.
  12728. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12729. } else {
  12730. // This is ill-formed, but provide the context that we would have
  12731. // declared the function in, if we were permitted to, for error recovery.
  12732. DC = FunctionContainingLocalClass;
  12733. }
  12734. adjustContextForLocalExternDecl(DC);
  12735. // C++ [class.friend]p6:
  12736. // A function can be defined in a friend declaration of a class if and
  12737. // only if the class is a non-local class (9.8), the function name is
  12738. // unqualified, and the function has namespace scope.
  12739. if (D.isFunctionDefinition()) {
  12740. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12741. }
  12742. // - There's no scope specifier, in which case we just go to the
  12743. // appropriate scope and look for a function or function template
  12744. // there as appropriate.
  12745. } else if (SS.isInvalid() || !SS.isSet()) {
  12746. // C++11 [namespace.memdef]p3:
  12747. // If the name in a friend declaration is neither qualified nor
  12748. // a template-id and the declaration is a function or an
  12749. // elaborated-type-specifier, the lookup to determine whether
  12750. // the entity has been previously declared shall not consider
  12751. // any scopes outside the innermost enclosing namespace.
  12752. bool isTemplateId =
  12753. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12754. // Find the appropriate context according to the above.
  12755. DC = CurContext;
  12756. // Skip class contexts. If someone can cite chapter and verse
  12757. // for this behavior, that would be nice --- it's what GCC and
  12758. // EDG do, and it seems like a reasonable intent, but the spec
  12759. // really only says that checks for unqualified existing
  12760. // declarations should stop at the nearest enclosing namespace,
  12761. // not that they should only consider the nearest enclosing
  12762. // namespace.
  12763. while (DC->isRecord())
  12764. DC = DC->getParent();
  12765. DeclContext *LookupDC = DC;
  12766. while (LookupDC->isTransparentContext())
  12767. LookupDC = LookupDC->getParent();
  12768. while (true) {
  12769. LookupQualifiedName(Previous, LookupDC);
  12770. if (!Previous.empty()) {
  12771. DC = LookupDC;
  12772. break;
  12773. }
  12774. if (isTemplateId) {
  12775. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12776. } else {
  12777. if (LookupDC->isFileContext()) break;
  12778. }
  12779. LookupDC = LookupDC->getParent();
  12780. }
  12781. DCScope = getScopeForDeclContext(S, DC);
  12782. // - There's a non-dependent scope specifier, in which case we
  12783. // compute it and do a previous lookup there for a function
  12784. // or function template.
  12785. } else if (!SS.getScopeRep()->isDependent()) {
  12786. DC = computeDeclContext(SS);
  12787. if (!DC) return nullptr;
  12788. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12789. LookupQualifiedName(Previous, DC);
  12790. // C++ [class.friend]p1: A friend of a class is a function or
  12791. // class that is not a member of the class . . .
  12792. if (DC->Equals(CurContext))
  12793. Diag(DS.getFriendSpecLoc(),
  12794. getLangOpts().CPlusPlus11 ?
  12795. diag::warn_cxx98_compat_friend_is_member :
  12796. diag::err_friend_is_member);
  12797. if (D.isFunctionDefinition()) {
  12798. // C++ [class.friend]p6:
  12799. // A function can be defined in a friend declaration of a class if and
  12800. // only if the class is a non-local class (9.8), the function name is
  12801. // unqualified, and the function has namespace scope.
  12802. //
  12803. // FIXME: We should only do this if the scope specifier names the
  12804. // innermost enclosing namespace; otherwise the fixit changes the
  12805. // meaning of the code.
  12806. SemaDiagnosticBuilder DB
  12807. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12808. DB << SS.getScopeRep();
  12809. if (DC->isFileContext())
  12810. DB << FixItHint::CreateRemoval(SS.getRange());
  12811. SS.clear();
  12812. }
  12813. // - There's a scope specifier that does not match any template
  12814. // parameter lists, in which case we use some arbitrary context,
  12815. // create a method or method template, and wait for instantiation.
  12816. // - There's a scope specifier that does match some template
  12817. // parameter lists, which we don't handle right now.
  12818. } else {
  12819. if (D.isFunctionDefinition()) {
  12820. // C++ [class.friend]p6:
  12821. // A function can be defined in a friend declaration of a class if and
  12822. // only if the class is a non-local class (9.8), the function name is
  12823. // unqualified, and the function has namespace scope.
  12824. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12825. << SS.getScopeRep();
  12826. }
  12827. DC = CurContext;
  12828. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12829. }
  12830. if (!DC->isRecord()) {
  12831. int DiagArg = -1;
  12832. switch (D.getName().getKind()) {
  12833. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12834. case UnqualifiedIdKind::IK_ConstructorName:
  12835. DiagArg = 0;
  12836. break;
  12837. case UnqualifiedIdKind::IK_DestructorName:
  12838. DiagArg = 1;
  12839. break;
  12840. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12841. DiagArg = 2;
  12842. break;
  12843. case UnqualifiedIdKind::IK_DeductionGuideName:
  12844. DiagArg = 3;
  12845. break;
  12846. case UnqualifiedIdKind::IK_Identifier:
  12847. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12848. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12849. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12850. case UnqualifiedIdKind::IK_TemplateId:
  12851. break;
  12852. }
  12853. // This implies that it has to be an operator or function.
  12854. if (DiagArg >= 0) {
  12855. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12856. return nullptr;
  12857. }
  12858. }
  12859. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12860. // does not contain the declaration context, i.e., in an out-of-line
  12861. // definition of a class.
  12862. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12863. if (!DCScope) {
  12864. FakeDCScope.setEntity(DC);
  12865. DCScope = &FakeDCScope;
  12866. }
  12867. bool AddToScope = true;
  12868. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12869. TemplateParams, AddToScope);
  12870. if (!ND) return nullptr;
  12871. assert(ND->getLexicalDeclContext() == CurContext);
  12872. // If we performed typo correction, we might have added a scope specifier
  12873. // and changed the decl context.
  12874. DC = ND->getDeclContext();
  12875. // Add the function declaration to the appropriate lookup tables,
  12876. // adjusting the redeclarations list as necessary. We don't
  12877. // want to do this yet if the friending class is dependent.
  12878. //
  12879. // Also update the scope-based lookup if the target context's
  12880. // lookup context is in lexical scope.
  12881. if (!CurContext->isDependentContext()) {
  12882. DC = DC->getRedeclContext();
  12883. DC->makeDeclVisibleInContext(ND);
  12884. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12885. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12886. }
  12887. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12888. D.getIdentifierLoc(), ND,
  12889. DS.getFriendSpecLoc());
  12890. FrD->setAccess(AS_public);
  12891. CurContext->addDecl(FrD);
  12892. if (ND->isInvalidDecl()) {
  12893. FrD->setInvalidDecl();
  12894. } else {
  12895. if (DC->isRecord()) CheckFriendAccess(ND);
  12896. FunctionDecl *FD;
  12897. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12898. FD = FTD->getTemplatedDecl();
  12899. else
  12900. FD = cast<FunctionDecl>(ND);
  12901. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12902. // default argument expression, that declaration shall be a definition
  12903. // and shall be the only declaration of the function or function
  12904. // template in the translation unit.
  12905. if (functionDeclHasDefaultArgument(FD)) {
  12906. // We can't look at FD->getPreviousDecl() because it may not have been set
  12907. // if we're in a dependent context. If the function is known to be a
  12908. // redeclaration, we will have narrowed Previous down to the right decl.
  12909. if (D.isRedeclaration()) {
  12910. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12911. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12912. diag::note_previous_declaration);
  12913. } else if (!D.isFunctionDefinition())
  12914. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12915. }
  12916. // Mark templated-scope function declarations as unsupported.
  12917. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12918. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12919. << SS.getScopeRep() << SS.getRange()
  12920. << cast<CXXRecordDecl>(CurContext);
  12921. FrD->setUnsupportedFriend(true);
  12922. }
  12923. }
  12924. return ND;
  12925. }
  12926. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12927. AdjustDeclIfTemplate(Dcl);
  12928. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12929. if (!Fn) {
  12930. Diag(DelLoc, diag::err_deleted_non_function);
  12931. return;
  12932. }
  12933. // Deleted function does not have a body.
  12934. Fn->setWillHaveBody(false);
  12935. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12936. // Don't consider the implicit declaration we generate for explicit
  12937. // specializations. FIXME: Do not generate these implicit declarations.
  12938. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12939. Prev->getPreviousDecl()) &&
  12940. !Prev->isDefined()) {
  12941. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12942. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12943. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12944. : diag::note_previous_declaration);
  12945. }
  12946. // If the declaration wasn't the first, we delete the function anyway for
  12947. // recovery.
  12948. Fn = Fn->getCanonicalDecl();
  12949. }
  12950. // dllimport/dllexport cannot be deleted.
  12951. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12952. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12953. Fn->setInvalidDecl();
  12954. }
  12955. if (Fn->isDeleted())
  12956. return;
  12957. // See if we're deleting a function which is already known to override a
  12958. // non-deleted virtual function.
  12959. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12960. bool IssuedDiagnostic = false;
  12961. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12962. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12963. if (!IssuedDiagnostic) {
  12964. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12965. IssuedDiagnostic = true;
  12966. }
  12967. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12968. }
  12969. }
  12970. // If this function was implicitly deleted because it was defaulted,
  12971. // explain why it was deleted.
  12972. if (IssuedDiagnostic && MD->isDefaulted())
  12973. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12974. /*Diagnose*/true);
  12975. }
  12976. // C++11 [basic.start.main]p3:
  12977. // A program that defines main as deleted [...] is ill-formed.
  12978. if (Fn->isMain())
  12979. Diag(DelLoc, diag::err_deleted_main);
  12980. // C++11 [dcl.fct.def.delete]p4:
  12981. // A deleted function is implicitly inline.
  12982. Fn->setImplicitlyInline();
  12983. Fn->setDeletedAsWritten();
  12984. }
  12985. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12986. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12987. if (MD) {
  12988. if (MD->getParent()->isDependentType()) {
  12989. MD->setDefaulted();
  12990. MD->setExplicitlyDefaulted();
  12991. return;
  12992. }
  12993. CXXSpecialMember Member = getSpecialMember(MD);
  12994. if (Member == CXXInvalid) {
  12995. if (!MD->isInvalidDecl())
  12996. Diag(DefaultLoc, diag::err_default_special_members);
  12997. return;
  12998. }
  12999. MD->setDefaulted();
  13000. MD->setExplicitlyDefaulted();
  13001. // Unset that we will have a body for this function. We might not,
  13002. // if it turns out to be trivial, and we don't need this marking now
  13003. // that we've marked it as defaulted.
  13004. MD->setWillHaveBody(false);
  13005. // If this definition appears within the record, do the checking when
  13006. // the record is complete.
  13007. const FunctionDecl *Primary = MD;
  13008. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  13009. // Ask the template instantiation pattern that actually had the
  13010. // '= default' on it.
  13011. Primary = Pattern;
  13012. // If the method was defaulted on its first declaration, we will have
  13013. // already performed the checking in CheckCompletedCXXClass. Such a
  13014. // declaration doesn't trigger an implicit definition.
  13015. if (Primary->getCanonicalDecl()->isDefaulted())
  13016. return;
  13017. CheckExplicitlyDefaultedSpecialMember(MD);
  13018. if (!MD->isInvalidDecl())
  13019. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  13020. } else {
  13021. Diag(DefaultLoc, diag::err_default_special_members);
  13022. }
  13023. }
  13024. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  13025. for (Stmt *SubStmt : S->children()) {
  13026. if (!SubStmt)
  13027. continue;
  13028. if (isa<ReturnStmt>(SubStmt))
  13029. Self.Diag(SubStmt->getBeginLoc(),
  13030. diag::err_return_in_constructor_handler);
  13031. if (!isa<Expr>(SubStmt))
  13032. SearchForReturnInStmt(Self, SubStmt);
  13033. }
  13034. }
  13035. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  13036. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  13037. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  13038. SearchForReturnInStmt(*this, Handler);
  13039. }
  13040. }
  13041. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  13042. const CXXMethodDecl *Old) {
  13043. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  13044. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  13045. if (OldFT->hasExtParameterInfos()) {
  13046. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  13047. // A parameter of the overriding method should be annotated with noescape
  13048. // if the corresponding parameter of the overridden method is annotated.
  13049. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  13050. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  13051. Diag(New->getParamDecl(I)->getLocation(),
  13052. diag::warn_overriding_method_missing_noescape);
  13053. Diag(Old->getParamDecl(I)->getLocation(),
  13054. diag::note_overridden_marked_noescape);
  13055. }
  13056. }
  13057. // Virtual overrides must have the same code_seg.
  13058. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  13059. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  13060. if ((NewCSA || OldCSA) &&
  13061. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  13062. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  13063. Diag(Old->getLocation(), diag::note_previous_declaration);
  13064. return true;
  13065. }
  13066. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  13067. // If the calling conventions match, everything is fine
  13068. if (NewCC == OldCC)
  13069. return false;
  13070. // If the calling conventions mismatch because the new function is static,
  13071. // suppress the calling convention mismatch error; the error about static
  13072. // function override (err_static_overrides_virtual from
  13073. // Sema::CheckFunctionDeclaration) is more clear.
  13074. if (New->getStorageClass() == SC_Static)
  13075. return false;
  13076. Diag(New->getLocation(),
  13077. diag::err_conflicting_overriding_cc_attributes)
  13078. << New->getDeclName() << New->getType() << Old->getType();
  13079. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  13080. return true;
  13081. }
  13082. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  13083. const CXXMethodDecl *Old) {
  13084. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  13085. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  13086. if (Context.hasSameType(NewTy, OldTy) ||
  13087. NewTy->isDependentType() || OldTy->isDependentType())
  13088. return false;
  13089. // Check if the return types are covariant
  13090. QualType NewClassTy, OldClassTy;
  13091. /// Both types must be pointers or references to classes.
  13092. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  13093. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  13094. NewClassTy = NewPT->getPointeeType();
  13095. OldClassTy = OldPT->getPointeeType();
  13096. }
  13097. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  13098. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  13099. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  13100. NewClassTy = NewRT->getPointeeType();
  13101. OldClassTy = OldRT->getPointeeType();
  13102. }
  13103. }
  13104. }
  13105. // The return types aren't either both pointers or references to a class type.
  13106. if (NewClassTy.isNull()) {
  13107. Diag(New->getLocation(),
  13108. diag::err_different_return_type_for_overriding_virtual_function)
  13109. << New->getDeclName() << NewTy << OldTy
  13110. << New->getReturnTypeSourceRange();
  13111. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13112. << Old->getReturnTypeSourceRange();
  13113. return true;
  13114. }
  13115. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  13116. // C++14 [class.virtual]p8:
  13117. // If the class type in the covariant return type of D::f differs from
  13118. // that of B::f, the class type in the return type of D::f shall be
  13119. // complete at the point of declaration of D::f or shall be the class
  13120. // type D.
  13121. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  13122. if (!RT->isBeingDefined() &&
  13123. RequireCompleteType(New->getLocation(), NewClassTy,
  13124. diag::err_covariant_return_incomplete,
  13125. New->getDeclName()))
  13126. return true;
  13127. }
  13128. // Check if the new class derives from the old class.
  13129. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  13130. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  13131. << New->getDeclName() << NewTy << OldTy
  13132. << New->getReturnTypeSourceRange();
  13133. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13134. << Old->getReturnTypeSourceRange();
  13135. return true;
  13136. }
  13137. // Check if we the conversion from derived to base is valid.
  13138. if (CheckDerivedToBaseConversion(
  13139. NewClassTy, OldClassTy,
  13140. diag::err_covariant_return_inaccessible_base,
  13141. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  13142. New->getLocation(), New->getReturnTypeSourceRange(),
  13143. New->getDeclName(), nullptr)) {
  13144. // FIXME: this note won't trigger for delayed access control
  13145. // diagnostics, and it's impossible to get an undelayed error
  13146. // here from access control during the original parse because
  13147. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  13148. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13149. << Old->getReturnTypeSourceRange();
  13150. return true;
  13151. }
  13152. }
  13153. // The qualifiers of the return types must be the same.
  13154. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  13155. Diag(New->getLocation(),
  13156. diag::err_covariant_return_type_different_qualifications)
  13157. << New->getDeclName() << NewTy << OldTy
  13158. << New->getReturnTypeSourceRange();
  13159. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13160. << Old->getReturnTypeSourceRange();
  13161. return true;
  13162. }
  13163. // The new class type must have the same or less qualifiers as the old type.
  13164. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  13165. Diag(New->getLocation(),
  13166. diag::err_covariant_return_type_class_type_more_qualified)
  13167. << New->getDeclName() << NewTy << OldTy
  13168. << New->getReturnTypeSourceRange();
  13169. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13170. << Old->getReturnTypeSourceRange();
  13171. return true;
  13172. }
  13173. return false;
  13174. }
  13175. /// Mark the given method pure.
  13176. ///
  13177. /// \param Method the method to be marked pure.
  13178. ///
  13179. /// \param InitRange the source range that covers the "0" initializer.
  13180. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  13181. SourceLocation EndLoc = InitRange.getEnd();
  13182. if (EndLoc.isValid())
  13183. Method->setRangeEnd(EndLoc);
  13184. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  13185. Method->setPure();
  13186. return false;
  13187. }
  13188. if (!Method->isInvalidDecl())
  13189. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  13190. << Method->getDeclName() << InitRange;
  13191. return true;
  13192. }
  13193. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  13194. if (D->getFriendObjectKind())
  13195. Diag(D->getLocation(), diag::err_pure_friend);
  13196. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  13197. CheckPureMethod(M, ZeroLoc);
  13198. else
  13199. Diag(D->getLocation(), diag::err_illegal_initializer);
  13200. }
  13201. /// Determine whether the given declaration is a global variable or
  13202. /// static data member.
  13203. static bool isNonlocalVariable(const Decl *D) {
  13204. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  13205. return Var->hasGlobalStorage();
  13206. return false;
  13207. }
  13208. /// Invoked when we are about to parse an initializer for the declaration
  13209. /// 'Dcl'.
  13210. ///
  13211. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  13212. /// static data member of class X, names should be looked up in the scope of
  13213. /// class X. If the declaration had a scope specifier, a scope will have
  13214. /// been created and passed in for this purpose. Otherwise, S will be null.
  13215. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  13216. // If there is no declaration, there was an error parsing it.
  13217. if (!D || D->isInvalidDecl())
  13218. return;
  13219. // We will always have a nested name specifier here, but this declaration
  13220. // might not be out of line if the specifier names the current namespace:
  13221. // extern int n;
  13222. // int ::n = 0;
  13223. if (S && D->isOutOfLine())
  13224. EnterDeclaratorContext(S, D->getDeclContext());
  13225. // If we are parsing the initializer for a static data member, push a
  13226. // new expression evaluation context that is associated with this static
  13227. // data member.
  13228. if (isNonlocalVariable(D))
  13229. PushExpressionEvaluationContext(
  13230. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  13231. }
  13232. /// Invoked after we are finished parsing an initializer for the declaration D.
  13233. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  13234. // If there is no declaration, there was an error parsing it.
  13235. if (!D || D->isInvalidDecl())
  13236. return;
  13237. if (isNonlocalVariable(D))
  13238. PopExpressionEvaluationContext();
  13239. if (S && D->isOutOfLine())
  13240. ExitDeclaratorContext(S);
  13241. }
  13242. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  13243. /// C++ if/switch/while/for statement.
  13244. /// e.g: "if (int x = f()) {...}"
  13245. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  13246. // C++ 6.4p2:
  13247. // The declarator shall not specify a function or an array.
  13248. // The type-specifier-seq shall not contain typedef and shall not declare a
  13249. // new class or enumeration.
  13250. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  13251. "Parser allowed 'typedef' as storage class of condition decl.");
  13252. Decl *Dcl = ActOnDeclarator(S, D);
  13253. if (!Dcl)
  13254. return true;
  13255. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  13256. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  13257. << D.getSourceRange();
  13258. return true;
  13259. }
  13260. return Dcl;
  13261. }
  13262. void Sema::LoadExternalVTableUses() {
  13263. if (!ExternalSource)
  13264. return;
  13265. SmallVector<ExternalVTableUse, 4> VTables;
  13266. ExternalSource->ReadUsedVTables(VTables);
  13267. SmallVector<VTableUse, 4> NewUses;
  13268. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  13269. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  13270. = VTablesUsed.find(VTables[I].Record);
  13271. // Even if a definition wasn't required before, it may be required now.
  13272. if (Pos != VTablesUsed.end()) {
  13273. if (!Pos->second && VTables[I].DefinitionRequired)
  13274. Pos->second = true;
  13275. continue;
  13276. }
  13277. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  13278. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  13279. }
  13280. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  13281. }
  13282. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  13283. bool DefinitionRequired) {
  13284. // Ignore any vtable uses in unevaluated operands or for classes that do
  13285. // not have a vtable.
  13286. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  13287. CurContext->isDependentContext() || isUnevaluatedContext())
  13288. return;
  13289. // Do not mark as used if compiling for the device outside of the target
  13290. // region.
  13291. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  13292. !isInOpenMPDeclareTargetContext() &&
  13293. !isInOpenMPTargetExecutionDirective()) {
  13294. if (!DefinitionRequired)
  13295. MarkVirtualMembersReferenced(Loc, Class);
  13296. return;
  13297. }
  13298. // Try to insert this class into the map.
  13299. LoadExternalVTableUses();
  13300. Class = Class->getCanonicalDecl();
  13301. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  13302. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  13303. if (!Pos.second) {
  13304. // If we already had an entry, check to see if we are promoting this vtable
  13305. // to require a definition. If so, we need to reappend to the VTableUses
  13306. // list, since we may have already processed the first entry.
  13307. if (DefinitionRequired && !Pos.first->second) {
  13308. Pos.first->second = true;
  13309. } else {
  13310. // Otherwise, we can early exit.
  13311. return;
  13312. }
  13313. } else {
  13314. // The Microsoft ABI requires that we perform the destructor body
  13315. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  13316. // the deleting destructor is emitted with the vtable, not with the
  13317. // destructor definition as in the Itanium ABI.
  13318. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  13319. CXXDestructorDecl *DD = Class->getDestructor();
  13320. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  13321. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  13322. // If this is an out-of-line declaration, marking it referenced will
  13323. // not do anything. Manually call CheckDestructor to look up operator
  13324. // delete().
  13325. ContextRAII SavedContext(*this, DD);
  13326. CheckDestructor(DD);
  13327. } else {
  13328. MarkFunctionReferenced(Loc, Class->getDestructor());
  13329. }
  13330. }
  13331. }
  13332. }
  13333. // Local classes need to have their virtual members marked
  13334. // immediately. For all other classes, we mark their virtual members
  13335. // at the end of the translation unit.
  13336. if (Class->isLocalClass())
  13337. MarkVirtualMembersReferenced(Loc, Class);
  13338. else
  13339. VTableUses.push_back(std::make_pair(Class, Loc));
  13340. }
  13341. bool Sema::DefineUsedVTables() {
  13342. LoadExternalVTableUses();
  13343. if (VTableUses.empty())
  13344. return false;
  13345. // Note: The VTableUses vector could grow as a result of marking
  13346. // the members of a class as "used", so we check the size each
  13347. // time through the loop and prefer indices (which are stable) to
  13348. // iterators (which are not).
  13349. bool DefinedAnything = false;
  13350. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  13351. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  13352. if (!Class)
  13353. continue;
  13354. TemplateSpecializationKind ClassTSK =
  13355. Class->getTemplateSpecializationKind();
  13356. SourceLocation Loc = VTableUses[I].second;
  13357. bool DefineVTable = true;
  13358. // If this class has a key function, but that key function is
  13359. // defined in another translation unit, we don't need to emit the
  13360. // vtable even though we're using it.
  13361. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  13362. if (KeyFunction && !KeyFunction->hasBody()) {
  13363. // The key function is in another translation unit.
  13364. DefineVTable = false;
  13365. TemplateSpecializationKind TSK =
  13366. KeyFunction->getTemplateSpecializationKind();
  13367. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  13368. TSK != TSK_ImplicitInstantiation &&
  13369. "Instantiations don't have key functions");
  13370. (void)TSK;
  13371. } else if (!KeyFunction) {
  13372. // If we have a class with no key function that is the subject
  13373. // of an explicit instantiation declaration, suppress the
  13374. // vtable; it will live with the explicit instantiation
  13375. // definition.
  13376. bool IsExplicitInstantiationDeclaration =
  13377. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  13378. for (auto R : Class->redecls()) {
  13379. TemplateSpecializationKind TSK
  13380. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  13381. if (TSK == TSK_ExplicitInstantiationDeclaration)
  13382. IsExplicitInstantiationDeclaration = true;
  13383. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  13384. IsExplicitInstantiationDeclaration = false;
  13385. break;
  13386. }
  13387. }
  13388. if (IsExplicitInstantiationDeclaration)
  13389. DefineVTable = false;
  13390. }
  13391. // The exception specifications for all virtual members may be needed even
  13392. // if we are not providing an authoritative form of the vtable in this TU.
  13393. // We may choose to emit it available_externally anyway.
  13394. if (!DefineVTable) {
  13395. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13396. continue;
  13397. }
  13398. // Mark all of the virtual members of this class as referenced, so
  13399. // that we can build a vtable. Then, tell the AST consumer that a
  13400. // vtable for this class is required.
  13401. DefinedAnything = true;
  13402. MarkVirtualMembersReferenced(Loc, Class);
  13403. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13404. if (VTablesUsed[Canonical])
  13405. Consumer.HandleVTable(Class);
  13406. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13407. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13408. // that lack key functions, since the user won't be able to make one.
  13409. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13410. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13411. const FunctionDecl *KeyFunctionDef = nullptr;
  13412. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13413. KeyFunctionDef->isInlined())) {
  13414. Diag(Class->getLocation(),
  13415. ClassTSK == TSK_ExplicitInstantiationDefinition
  13416. ? diag::warn_weak_template_vtable
  13417. : diag::warn_weak_vtable)
  13418. << Class;
  13419. }
  13420. }
  13421. }
  13422. VTableUses.clear();
  13423. return DefinedAnything;
  13424. }
  13425. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13426. const CXXRecordDecl *RD) {
  13427. for (const auto *I : RD->methods())
  13428. if (I->isVirtual() && !I->isPure())
  13429. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13430. }
  13431. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13432. const CXXRecordDecl *RD,
  13433. bool ConstexprOnly) {
  13434. // Mark all functions which will appear in RD's vtable as used.
  13435. CXXFinalOverriderMap FinalOverriders;
  13436. RD->getFinalOverriders(FinalOverriders);
  13437. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13438. E = FinalOverriders.end();
  13439. I != E; ++I) {
  13440. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13441. OE = I->second.end();
  13442. OI != OE; ++OI) {
  13443. assert(OI->second.size() > 0 && "no final overrider");
  13444. CXXMethodDecl *Overrider = OI->second.front().Method;
  13445. // C++ [basic.def.odr]p2:
  13446. // [...] A virtual member function is used if it is not pure. [...]
  13447. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  13448. MarkFunctionReferenced(Loc, Overrider);
  13449. }
  13450. }
  13451. // Only classes that have virtual bases need a VTT.
  13452. if (RD->getNumVBases() == 0)
  13453. return;
  13454. for (const auto &I : RD->bases()) {
  13455. const auto *Base =
  13456. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  13457. if (Base->getNumVBases() == 0)
  13458. continue;
  13459. MarkVirtualMembersReferenced(Loc, Base);
  13460. }
  13461. }
  13462. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13463. /// Objective-C implementation whose ivars need be initialized.
  13464. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13465. if (!getLangOpts().CPlusPlus)
  13466. return;
  13467. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13468. SmallVector<ObjCIvarDecl*, 8> ivars;
  13469. CollectIvarsToConstructOrDestruct(OID, ivars);
  13470. if (ivars.empty())
  13471. return;
  13472. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13473. for (unsigned i = 0; i < ivars.size(); i++) {
  13474. FieldDecl *Field = ivars[i];
  13475. if (Field->isInvalidDecl())
  13476. continue;
  13477. CXXCtorInitializer *Member;
  13478. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13479. InitializationKind InitKind =
  13480. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13481. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13482. ExprResult MemberInit =
  13483. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13484. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13485. // Note, MemberInit could actually come back empty if no initialization
  13486. // is required (e.g., because it would call a trivial default constructor)
  13487. if (!MemberInit.get() || MemberInit.isInvalid())
  13488. continue;
  13489. Member =
  13490. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13491. SourceLocation(),
  13492. MemberInit.getAs<Expr>(),
  13493. SourceLocation());
  13494. AllToInit.push_back(Member);
  13495. // Be sure that the destructor is accessible and is marked as referenced.
  13496. if (const RecordType *RecordTy =
  13497. Context.getBaseElementType(Field->getType())
  13498. ->getAs<RecordType>()) {
  13499. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13500. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13501. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13502. CheckDestructorAccess(Field->getLocation(), Destructor,
  13503. PDiag(diag::err_access_dtor_ivar)
  13504. << Context.getBaseElementType(Field->getType()));
  13505. }
  13506. }
  13507. }
  13508. ObjCImplementation->setIvarInitializers(Context,
  13509. AllToInit.data(), AllToInit.size());
  13510. }
  13511. }
  13512. static
  13513. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13514. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13515. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13516. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13517. Sema &S) {
  13518. if (Ctor->isInvalidDecl())
  13519. return;
  13520. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13521. // Target may not be determinable yet, for instance if this is a dependent
  13522. // call in an uninstantiated template.
  13523. if (Target) {
  13524. const FunctionDecl *FNTarget = nullptr;
  13525. (void)Target->hasBody(FNTarget);
  13526. Target = const_cast<CXXConstructorDecl*>(
  13527. cast_or_null<CXXConstructorDecl>(FNTarget));
  13528. }
  13529. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13530. // Avoid dereferencing a null pointer here.
  13531. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13532. if (!Current.insert(Canonical).second)
  13533. return;
  13534. // We know that beyond here, we aren't chaining into a cycle.
  13535. if (!Target || !Target->isDelegatingConstructor() ||
  13536. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13537. Valid.insert(Current.begin(), Current.end());
  13538. Current.clear();
  13539. // We've hit a cycle.
  13540. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13541. Current.count(TCanonical)) {
  13542. // If we haven't diagnosed this cycle yet, do so now.
  13543. if (!Invalid.count(TCanonical)) {
  13544. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13545. diag::warn_delegating_ctor_cycle)
  13546. << Ctor;
  13547. // Don't add a note for a function delegating directly to itself.
  13548. if (TCanonical != Canonical)
  13549. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13550. CXXConstructorDecl *C = Target;
  13551. while (C->getCanonicalDecl() != Canonical) {
  13552. const FunctionDecl *FNTarget = nullptr;
  13553. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13554. assert(FNTarget && "Ctor cycle through bodiless function");
  13555. C = const_cast<CXXConstructorDecl*>(
  13556. cast<CXXConstructorDecl>(FNTarget));
  13557. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13558. }
  13559. }
  13560. Invalid.insert(Current.begin(), Current.end());
  13561. Current.clear();
  13562. } else {
  13563. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13564. }
  13565. }
  13566. void Sema::CheckDelegatingCtorCycles() {
  13567. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13568. for (DelegatingCtorDeclsType::iterator
  13569. I = DelegatingCtorDecls.begin(ExternalSource),
  13570. E = DelegatingCtorDecls.end();
  13571. I != E; ++I)
  13572. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13573. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13574. (*CI)->setInvalidDecl();
  13575. }
  13576. namespace {
  13577. /// AST visitor that finds references to the 'this' expression.
  13578. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13579. Sema &S;
  13580. public:
  13581. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13582. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13583. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13584. << E->isImplicit();
  13585. return false;
  13586. }
  13587. };
  13588. }
  13589. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13590. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13591. if (!TSInfo)
  13592. return false;
  13593. TypeLoc TL = TSInfo->getTypeLoc();
  13594. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13595. if (!ProtoTL)
  13596. return false;
  13597. // C++11 [expr.prim.general]p3:
  13598. // [The expression this] shall not appear before the optional
  13599. // cv-qualifier-seq and it shall not appear within the declaration of a
  13600. // static member function (although its type and value category are defined
  13601. // within a static member function as they are within a non-static member
  13602. // function). [ Note: this is because declaration matching does not occur
  13603. // until the complete declarator is known. - end note ]
  13604. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13605. FindCXXThisExpr Finder(*this);
  13606. // If the return type came after the cv-qualifier-seq, check it now.
  13607. if (Proto->hasTrailingReturn() &&
  13608. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13609. return true;
  13610. // Check the exception specification.
  13611. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13612. return true;
  13613. return checkThisInStaticMemberFunctionAttributes(Method);
  13614. }
  13615. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13616. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13617. if (!TSInfo)
  13618. return false;
  13619. TypeLoc TL = TSInfo->getTypeLoc();
  13620. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13621. if (!ProtoTL)
  13622. return false;
  13623. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13624. FindCXXThisExpr Finder(*this);
  13625. switch (Proto->getExceptionSpecType()) {
  13626. case EST_Unparsed:
  13627. case EST_Uninstantiated:
  13628. case EST_Unevaluated:
  13629. case EST_BasicNoexcept:
  13630. case EST_NoThrow:
  13631. case EST_DynamicNone:
  13632. case EST_MSAny:
  13633. case EST_None:
  13634. break;
  13635. case EST_DependentNoexcept:
  13636. case EST_NoexceptFalse:
  13637. case EST_NoexceptTrue:
  13638. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13639. return true;
  13640. LLVM_FALLTHROUGH;
  13641. case EST_Dynamic:
  13642. for (const auto &E : Proto->exceptions()) {
  13643. if (!Finder.TraverseType(E))
  13644. return true;
  13645. }
  13646. break;
  13647. }
  13648. return false;
  13649. }
  13650. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13651. FindCXXThisExpr Finder(*this);
  13652. // Check attributes.
  13653. for (const auto *A : Method->attrs()) {
  13654. // FIXME: This should be emitted by tblgen.
  13655. Expr *Arg = nullptr;
  13656. ArrayRef<Expr *> Args;
  13657. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13658. Arg = G->getArg();
  13659. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13660. Arg = G->getArg();
  13661. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13662. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13663. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13664. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13665. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13666. Arg = ETLF->getSuccessValue();
  13667. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13668. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13669. Arg = STLF->getSuccessValue();
  13670. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13671. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13672. Arg = LR->getArg();
  13673. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13674. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13675. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13676. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13677. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13678. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13679. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13680. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13681. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13682. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13683. if (Arg && !Finder.TraverseStmt(Arg))
  13684. return true;
  13685. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13686. if (!Finder.TraverseStmt(Args[I]))
  13687. return true;
  13688. }
  13689. }
  13690. return false;
  13691. }
  13692. void Sema::checkExceptionSpecification(
  13693. bool IsTopLevel, ExceptionSpecificationType EST,
  13694. ArrayRef<ParsedType> DynamicExceptions,
  13695. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13696. SmallVectorImpl<QualType> &Exceptions,
  13697. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13698. Exceptions.clear();
  13699. ESI.Type = EST;
  13700. if (EST == EST_Dynamic) {
  13701. Exceptions.reserve(DynamicExceptions.size());
  13702. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13703. // FIXME: Preserve type source info.
  13704. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13705. if (IsTopLevel) {
  13706. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13707. collectUnexpandedParameterPacks(ET, Unexpanded);
  13708. if (!Unexpanded.empty()) {
  13709. DiagnoseUnexpandedParameterPacks(
  13710. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13711. Unexpanded);
  13712. continue;
  13713. }
  13714. }
  13715. // Check that the type is valid for an exception spec, and
  13716. // drop it if not.
  13717. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13718. Exceptions.push_back(ET);
  13719. }
  13720. ESI.Exceptions = Exceptions;
  13721. return;
  13722. }
  13723. if (isComputedNoexcept(EST)) {
  13724. assert((NoexceptExpr->isTypeDependent() ||
  13725. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13726. Context.BoolTy) &&
  13727. "Parser should have made sure that the expression is boolean");
  13728. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13729. ESI.Type = EST_BasicNoexcept;
  13730. return;
  13731. }
  13732. ESI.NoexceptExpr = NoexceptExpr;
  13733. return;
  13734. }
  13735. }
  13736. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13737. ExceptionSpecificationType EST,
  13738. SourceRange SpecificationRange,
  13739. ArrayRef<ParsedType> DynamicExceptions,
  13740. ArrayRef<SourceRange> DynamicExceptionRanges,
  13741. Expr *NoexceptExpr) {
  13742. if (!MethodD)
  13743. return;
  13744. // Dig out the method we're referring to.
  13745. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13746. MethodD = FunTmpl->getTemplatedDecl();
  13747. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13748. if (!Method)
  13749. return;
  13750. // Check the exception specification.
  13751. llvm::SmallVector<QualType, 4> Exceptions;
  13752. FunctionProtoType::ExceptionSpecInfo ESI;
  13753. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13754. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13755. ESI);
  13756. // Update the exception specification on the function type.
  13757. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13758. if (Method->isStatic())
  13759. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13760. if (Method->isVirtual()) {
  13761. // Check overrides, which we previously had to delay.
  13762. for (const CXXMethodDecl *O : Method->overridden_methods())
  13763. CheckOverridingFunctionExceptionSpec(Method, O);
  13764. }
  13765. }
  13766. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13767. ///
  13768. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13769. SourceLocation DeclStart, Declarator &D,
  13770. Expr *BitWidth,
  13771. InClassInitStyle InitStyle,
  13772. AccessSpecifier AS,
  13773. const ParsedAttr &MSPropertyAttr) {
  13774. IdentifierInfo *II = D.getIdentifier();
  13775. if (!II) {
  13776. Diag(DeclStart, diag::err_anonymous_property);
  13777. return nullptr;
  13778. }
  13779. SourceLocation Loc = D.getIdentifierLoc();
  13780. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13781. QualType T = TInfo->getType();
  13782. if (getLangOpts().CPlusPlus) {
  13783. CheckExtraCXXDefaultArguments(D);
  13784. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13785. UPPC_DataMemberType)) {
  13786. D.setInvalidType();
  13787. T = Context.IntTy;
  13788. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13789. }
  13790. }
  13791. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13792. if (D.getDeclSpec().isInlineSpecified())
  13793. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13794. << getLangOpts().CPlusPlus17;
  13795. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13796. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13797. diag::err_invalid_thread)
  13798. << DeclSpec::getSpecifierName(TSCS);
  13799. // Check to see if this name was declared as a member previously
  13800. NamedDecl *PrevDecl = nullptr;
  13801. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13802. ForVisibleRedeclaration);
  13803. LookupName(Previous, S);
  13804. switch (Previous.getResultKind()) {
  13805. case LookupResult::Found:
  13806. case LookupResult::FoundUnresolvedValue:
  13807. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13808. break;
  13809. case LookupResult::FoundOverloaded:
  13810. PrevDecl = Previous.getRepresentativeDecl();
  13811. break;
  13812. case LookupResult::NotFound:
  13813. case LookupResult::NotFoundInCurrentInstantiation:
  13814. case LookupResult::Ambiguous:
  13815. break;
  13816. }
  13817. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13818. // Maybe we will complain about the shadowed template parameter.
  13819. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13820. // Just pretend that we didn't see the previous declaration.
  13821. PrevDecl = nullptr;
  13822. }
  13823. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13824. PrevDecl = nullptr;
  13825. SourceLocation TSSL = D.getBeginLoc();
  13826. MSPropertyDecl *NewPD =
  13827. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13828. MSPropertyAttr.getPropertyDataGetter(),
  13829. MSPropertyAttr.getPropertyDataSetter());
  13830. ProcessDeclAttributes(TUScope, NewPD, D);
  13831. NewPD->setAccess(AS);
  13832. if (NewPD->isInvalidDecl())
  13833. Record->setInvalidDecl();
  13834. if (D.getDeclSpec().isModulePrivateSpecified())
  13835. NewPD->setModulePrivate();
  13836. if (NewPD->isInvalidDecl() && PrevDecl) {
  13837. // Don't introduce NewFD into scope; there's already something
  13838. // with the same name in the same scope.
  13839. } else if (II) {
  13840. PushOnScopeChains(NewPD, S);
  13841. } else
  13842. Record->addDecl(NewPD);
  13843. return NewPD;
  13844. }