SemaDeclCXX.cpp 602 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890
  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. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1417. // are all literal types. If so, return true. If not, produce a suitable
  1418. // diagnostic and return false.
  1419. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1420. const FunctionDecl *FD,
  1421. Sema::CheckConstexprKind Kind) {
  1422. unsigned ArgIndex = 0;
  1423. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1424. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1425. e = FT->param_type_end();
  1426. i != e; ++i, ++ArgIndex) {
  1427. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1428. SourceLocation ParamLoc = PD->getLocation();
  1429. if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
  1430. diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1431. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1432. FD->isConsteval()))
  1433. return false;
  1434. }
  1435. return true;
  1436. }
  1437. /// Get diagnostic %select index for tag kind for
  1438. /// record diagnostic message.
  1439. /// WARNING: Indexes apply to particular diagnostics only!
  1440. ///
  1441. /// \returns diagnostic %select index.
  1442. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1443. switch (Tag) {
  1444. case TTK_Struct: return 0;
  1445. case TTK_Interface: return 1;
  1446. case TTK_Class: return 2;
  1447. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1448. }
  1449. }
  1450. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1451. Stmt *Body,
  1452. Sema::CheckConstexprKind Kind);
  1453. // Check whether a function declaration satisfies the requirements of a
  1454. // constexpr function definition or a constexpr constructor definition. If so,
  1455. // return true. If not, produce appropriate diagnostics (unless asked not to by
  1456. // Kind) and return false.
  1457. //
  1458. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1459. bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
  1460. CheckConstexprKind Kind) {
  1461. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1462. if (MD && MD->isInstance()) {
  1463. // C++11 [dcl.constexpr]p4:
  1464. // The definition of a constexpr constructor shall satisfy the following
  1465. // constraints:
  1466. // - the class shall not have any virtual base classes;
  1467. //
  1468. // FIXME: This only applies to constructors, not arbitrary member
  1469. // functions.
  1470. const CXXRecordDecl *RD = MD->getParent();
  1471. if (RD->getNumVBases()) {
  1472. if (Kind == CheckConstexprKind::CheckValid)
  1473. return false;
  1474. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1475. << isa<CXXConstructorDecl>(NewFD)
  1476. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1477. for (const auto &I : RD->vbases())
  1478. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1479. << I.getSourceRange();
  1480. return false;
  1481. }
  1482. }
  1483. if (!isa<CXXConstructorDecl>(NewFD)) {
  1484. // C++11 [dcl.constexpr]p3:
  1485. // The definition of a constexpr function shall satisfy the following
  1486. // constraints:
  1487. // - it shall not be virtual; (removed in C++20)
  1488. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1489. if (Method && Method->isVirtual()) {
  1490. if (getLangOpts().CPlusPlus2a) {
  1491. if (Kind == CheckConstexprKind::Diagnose)
  1492. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1493. } else {
  1494. if (Kind == CheckConstexprKind::CheckValid)
  1495. return false;
  1496. Method = Method->getCanonicalDecl();
  1497. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1498. // If it's not obvious why this function is virtual, find an overridden
  1499. // function which uses the 'virtual' keyword.
  1500. const CXXMethodDecl *WrittenVirtual = Method;
  1501. while (!WrittenVirtual->isVirtualAsWritten())
  1502. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1503. if (WrittenVirtual != Method)
  1504. Diag(WrittenVirtual->getLocation(),
  1505. diag::note_overridden_virtual_function);
  1506. return false;
  1507. }
  1508. }
  1509. // - its return type shall be a literal type;
  1510. QualType RT = NewFD->getReturnType();
  1511. if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
  1512. diag::err_constexpr_non_literal_return,
  1513. NewFD->isConsteval()))
  1514. return false;
  1515. }
  1516. // - each of its parameter types shall be a literal type;
  1517. if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
  1518. return false;
  1519. Stmt *Body = NewFD->getBody();
  1520. assert(Body &&
  1521. "CheckConstexprFunctionDefinition called on function with no body");
  1522. return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
  1523. }
  1524. /// Check the given declaration statement is legal within a constexpr function
  1525. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1526. ///
  1527. /// \return true if the body is OK (maybe only as an extension), false if we
  1528. /// have diagnosed a problem.
  1529. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1530. DeclStmt *DS, SourceLocation &Cxx1yLoc,
  1531. Sema::CheckConstexprKind Kind) {
  1532. // C++11 [dcl.constexpr]p3 and p4:
  1533. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1534. // contain only
  1535. for (const auto *DclIt : DS->decls()) {
  1536. switch (DclIt->getKind()) {
  1537. case Decl::StaticAssert:
  1538. case Decl::Using:
  1539. case Decl::UsingShadow:
  1540. case Decl::UsingDirective:
  1541. case Decl::UnresolvedUsingTypename:
  1542. case Decl::UnresolvedUsingValue:
  1543. // - static_assert-declarations
  1544. // - using-declarations,
  1545. // - using-directives,
  1546. continue;
  1547. case Decl::Typedef:
  1548. case Decl::TypeAlias: {
  1549. // - typedef declarations and alias-declarations that do not define
  1550. // classes or enumerations,
  1551. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1552. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1553. // Don't allow variably-modified types in constexpr functions.
  1554. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1555. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1556. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1557. << TL.getSourceRange() << TL.getType()
  1558. << isa<CXXConstructorDecl>(Dcl);
  1559. }
  1560. return false;
  1561. }
  1562. continue;
  1563. }
  1564. case Decl::Enum:
  1565. case Decl::CXXRecord:
  1566. // C++1y allows types to be defined, not just declared.
  1567. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
  1568. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1569. SemaRef.Diag(DS->getBeginLoc(),
  1570. SemaRef.getLangOpts().CPlusPlus14
  1571. ? diag::warn_cxx11_compat_constexpr_type_definition
  1572. : diag::ext_constexpr_type_definition)
  1573. << isa<CXXConstructorDecl>(Dcl);
  1574. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1575. return false;
  1576. }
  1577. }
  1578. continue;
  1579. case Decl::EnumConstant:
  1580. case Decl::IndirectField:
  1581. case Decl::ParmVar:
  1582. // These can only appear with other declarations which are banned in
  1583. // C++11 and permitted in C++1y, so ignore them.
  1584. continue;
  1585. case Decl::Var:
  1586. case Decl::Decomposition: {
  1587. // C++1y [dcl.constexpr]p3 allows anything except:
  1588. // a definition of a variable of non-literal type or of static or
  1589. // thread storage duration or for which no initialization is performed.
  1590. const auto *VD = cast<VarDecl>(DclIt);
  1591. if (VD->isThisDeclarationADefinition()) {
  1592. if (VD->isStaticLocal()) {
  1593. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1594. SemaRef.Diag(VD->getLocation(),
  1595. diag::err_constexpr_local_var_static)
  1596. << isa<CXXConstructorDecl>(Dcl)
  1597. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1598. }
  1599. return false;
  1600. }
  1601. if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
  1602. diag::err_constexpr_local_var_non_literal_type,
  1603. isa<CXXConstructorDecl>(Dcl)))
  1604. return false;
  1605. if (!VD->getType()->isDependentType() &&
  1606. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1607. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1608. SemaRef.Diag(VD->getLocation(),
  1609. diag::err_constexpr_local_var_no_init)
  1610. << isa<CXXConstructorDecl>(Dcl);
  1611. }
  1612. return false;
  1613. }
  1614. }
  1615. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1616. SemaRef.Diag(VD->getLocation(),
  1617. SemaRef.getLangOpts().CPlusPlus14
  1618. ? diag::warn_cxx11_compat_constexpr_local_var
  1619. : diag::ext_constexpr_local_var)
  1620. << isa<CXXConstructorDecl>(Dcl);
  1621. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1622. return false;
  1623. }
  1624. continue;
  1625. }
  1626. case Decl::NamespaceAlias:
  1627. case Decl::Function:
  1628. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1629. // everywhere as an extension.
  1630. if (!Cxx1yLoc.isValid())
  1631. Cxx1yLoc = DS->getBeginLoc();
  1632. continue;
  1633. default:
  1634. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1635. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1636. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1637. }
  1638. return false;
  1639. }
  1640. }
  1641. return true;
  1642. }
  1643. /// Check that the given field is initialized within a constexpr constructor.
  1644. ///
  1645. /// \param Dcl The constexpr constructor being checked.
  1646. /// \param Field The field being checked. This may be a member of an anonymous
  1647. /// struct or union nested within the class being checked.
  1648. /// \param Inits All declarations, including anonymous struct/union members and
  1649. /// indirect members, for which any initialization was provided.
  1650. /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
  1651. /// multiple notes for different members to the same error.
  1652. /// \param Kind Whether we're diagnosing a constructor as written or determining
  1653. /// whether the formal requirements are satisfied.
  1654. /// \return \c false if we're checking for validity and the constructor does
  1655. /// not satisfy the requirements on a constexpr constructor.
  1656. static bool CheckConstexprCtorInitializer(Sema &SemaRef,
  1657. const FunctionDecl *Dcl,
  1658. FieldDecl *Field,
  1659. llvm::SmallSet<Decl*, 16> &Inits,
  1660. bool &Diagnosed,
  1661. Sema::CheckConstexprKind Kind) {
  1662. if (Field->isInvalidDecl())
  1663. return true;
  1664. if (Field->isUnnamedBitfield())
  1665. return true;
  1666. // Anonymous unions with no variant members and empty anonymous structs do not
  1667. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1668. // indirect fields don't need initializing.
  1669. if (Field->isAnonymousStructOrUnion() &&
  1670. (Field->getType()->isUnionType()
  1671. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1672. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1673. return true;
  1674. if (!Inits.count(Field)) {
  1675. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1676. if (!Diagnosed) {
  1677. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  1678. Diagnosed = true;
  1679. }
  1680. SemaRef.Diag(Field->getLocation(),
  1681. diag::note_constexpr_ctor_missing_init);
  1682. } else {
  1683. return false;
  1684. }
  1685. } else if (Field->isAnonymousStructOrUnion()) {
  1686. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1687. for (auto *I : RD->fields())
  1688. // If an anonymous union contains an anonymous struct of which any member
  1689. // is initialized, all members must be initialized.
  1690. if (!RD->isUnion() || Inits.count(I))
  1691. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1692. Kind))
  1693. return false;
  1694. }
  1695. return true;
  1696. }
  1697. /// Check the provided statement is allowed in a constexpr function
  1698. /// definition.
  1699. static bool
  1700. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1701. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1702. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
  1703. Sema::CheckConstexprKind Kind) {
  1704. // - its function-body shall be [...] a compound-statement that contains only
  1705. switch (S->getStmtClass()) {
  1706. case Stmt::NullStmtClass:
  1707. // - null statements,
  1708. return true;
  1709. case Stmt::DeclStmtClass:
  1710. // - static_assert-declarations
  1711. // - using-declarations,
  1712. // - using-directives,
  1713. // - typedef declarations and alias-declarations that do not define
  1714. // classes or enumerations,
  1715. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
  1716. return false;
  1717. return true;
  1718. case Stmt::ReturnStmtClass:
  1719. // - and exactly one return statement;
  1720. if (isa<CXXConstructorDecl>(Dcl)) {
  1721. // C++1y allows return statements in constexpr constructors.
  1722. if (!Cxx1yLoc.isValid())
  1723. Cxx1yLoc = S->getBeginLoc();
  1724. return true;
  1725. }
  1726. ReturnStmts.push_back(S->getBeginLoc());
  1727. return true;
  1728. case Stmt::CompoundStmtClass: {
  1729. // C++1y allows compound-statements.
  1730. if (!Cxx1yLoc.isValid())
  1731. Cxx1yLoc = S->getBeginLoc();
  1732. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1733. for (auto *BodyIt : CompStmt->body()) {
  1734. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1735. Cxx1yLoc, Cxx2aLoc, Kind))
  1736. return false;
  1737. }
  1738. return true;
  1739. }
  1740. case Stmt::AttributedStmtClass:
  1741. if (!Cxx1yLoc.isValid())
  1742. Cxx1yLoc = S->getBeginLoc();
  1743. return true;
  1744. case Stmt::IfStmtClass: {
  1745. // C++1y allows if-statements.
  1746. if (!Cxx1yLoc.isValid())
  1747. Cxx1yLoc = S->getBeginLoc();
  1748. IfStmt *If = cast<IfStmt>(S);
  1749. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1750. Cxx1yLoc, Cxx2aLoc, Kind))
  1751. return false;
  1752. if (If->getElse() &&
  1753. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1754. Cxx1yLoc, Cxx2aLoc, Kind))
  1755. return false;
  1756. return true;
  1757. }
  1758. case Stmt::WhileStmtClass:
  1759. case Stmt::DoStmtClass:
  1760. case Stmt::ForStmtClass:
  1761. case Stmt::CXXForRangeStmtClass:
  1762. case Stmt::ContinueStmtClass:
  1763. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1764. // because they don't make sense without variable mutation.
  1765. if (!SemaRef.getLangOpts().CPlusPlus14)
  1766. break;
  1767. if (!Cxx1yLoc.isValid())
  1768. Cxx1yLoc = S->getBeginLoc();
  1769. for (Stmt *SubStmt : S->children())
  1770. if (SubStmt &&
  1771. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1772. Cxx1yLoc, Cxx2aLoc, Kind))
  1773. return false;
  1774. return true;
  1775. case Stmt::SwitchStmtClass:
  1776. case Stmt::CaseStmtClass:
  1777. case Stmt::DefaultStmtClass:
  1778. case Stmt::BreakStmtClass:
  1779. // C++1y allows switch-statements, and since they don't need variable
  1780. // mutation, we can reasonably allow them in C++11 as an extension.
  1781. if (!Cxx1yLoc.isValid())
  1782. Cxx1yLoc = S->getBeginLoc();
  1783. for (Stmt *SubStmt : S->children())
  1784. if (SubStmt &&
  1785. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1786. Cxx1yLoc, Cxx2aLoc, Kind))
  1787. return false;
  1788. return true;
  1789. case Stmt::GCCAsmStmtClass:
  1790. case Stmt::MSAsmStmtClass:
  1791. // C++2a allows inline assembly statements.
  1792. case Stmt::CXXTryStmtClass:
  1793. if (Cxx2aLoc.isInvalid())
  1794. Cxx2aLoc = S->getBeginLoc();
  1795. for (Stmt *SubStmt : S->children()) {
  1796. if (SubStmt &&
  1797. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1798. Cxx1yLoc, Cxx2aLoc, Kind))
  1799. return false;
  1800. }
  1801. return true;
  1802. case Stmt::CXXCatchStmtClass:
  1803. // Do not bother checking the language mode (already covered by the
  1804. // try block check).
  1805. if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
  1806. cast<CXXCatchStmt>(S)->getHandlerBlock(),
  1807. ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
  1808. return false;
  1809. return true;
  1810. default:
  1811. if (!isa<Expr>(S))
  1812. break;
  1813. // C++1y allows expression-statements.
  1814. if (!Cxx1yLoc.isValid())
  1815. Cxx1yLoc = S->getBeginLoc();
  1816. return true;
  1817. }
  1818. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1819. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1820. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1821. }
  1822. return false;
  1823. }
  1824. /// Check the body for the given constexpr function declaration only contains
  1825. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1826. ///
  1827. /// \return true if the body is OK, false if we have found or diagnosed a
  1828. /// problem.
  1829. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1830. Stmt *Body,
  1831. Sema::CheckConstexprKind Kind) {
  1832. SmallVector<SourceLocation, 4> ReturnStmts;
  1833. if (isa<CXXTryStmt>(Body)) {
  1834. // C++11 [dcl.constexpr]p3:
  1835. // The definition of a constexpr function shall satisfy the following
  1836. // constraints: [...]
  1837. // - its function-body shall be = delete, = default, or a
  1838. // compound-statement
  1839. //
  1840. // C++11 [dcl.constexpr]p4:
  1841. // In the definition of a constexpr constructor, [...]
  1842. // - its function-body shall not be a function-try-block;
  1843. //
  1844. // This restriction is lifted in C++2a, as long as inner statements also
  1845. // apply the general constexpr rules.
  1846. switch (Kind) {
  1847. case Sema::CheckConstexprKind::CheckValid:
  1848. if (!SemaRef.getLangOpts().CPlusPlus2a)
  1849. return false;
  1850. break;
  1851. case Sema::CheckConstexprKind::Diagnose:
  1852. SemaRef.Diag(Body->getBeginLoc(),
  1853. !SemaRef.getLangOpts().CPlusPlus2a
  1854. ? diag::ext_constexpr_function_try_block_cxx2a
  1855. : diag::warn_cxx17_compat_constexpr_function_try_block)
  1856. << isa<CXXConstructorDecl>(Dcl);
  1857. break;
  1858. }
  1859. }
  1860. // - its function-body shall be [...] a compound-statement that contains only
  1861. // [... list of cases ...]
  1862. //
  1863. // Note that walking the children here is enough to properly check for
  1864. // CompoundStmt and CXXTryStmt body.
  1865. SourceLocation Cxx1yLoc, Cxx2aLoc;
  1866. for (Stmt *SubStmt : Body->children()) {
  1867. if (SubStmt &&
  1868. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1869. Cxx1yLoc, Cxx2aLoc, Kind))
  1870. return false;
  1871. }
  1872. if (Kind == Sema::CheckConstexprKind::CheckValid) {
  1873. // If this is only valid as an extension, report that we don't satisfy the
  1874. // constraints of the current language.
  1875. if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
  1876. (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
  1877. return false;
  1878. } else if (Cxx2aLoc.isValid()) {
  1879. SemaRef.Diag(Cxx2aLoc,
  1880. SemaRef.getLangOpts().CPlusPlus2a
  1881. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  1882. : diag::ext_constexpr_body_invalid_stmt_cxx2a)
  1883. << isa<CXXConstructorDecl>(Dcl);
  1884. } else if (Cxx1yLoc.isValid()) {
  1885. SemaRef.Diag(Cxx1yLoc,
  1886. SemaRef.getLangOpts().CPlusPlus14
  1887. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1888. : diag::ext_constexpr_body_invalid_stmt)
  1889. << isa<CXXConstructorDecl>(Dcl);
  1890. }
  1891. if (const CXXConstructorDecl *Constructor
  1892. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1893. const CXXRecordDecl *RD = Constructor->getParent();
  1894. // DR1359:
  1895. // - every non-variant non-static data member and base class sub-object
  1896. // shall be initialized;
  1897. // DR1460:
  1898. // - if the class is a union having variant members, exactly one of them
  1899. // shall be initialized;
  1900. if (RD->isUnion()) {
  1901. if (Constructor->getNumCtorInitializers() == 0 &&
  1902. RD->hasVariantMembers()) {
  1903. if (Kind == Sema::CheckConstexprKind::Diagnose)
  1904. SemaRef.Diag(Dcl->getLocation(),
  1905. diag::err_constexpr_union_ctor_no_init);
  1906. return false;
  1907. }
  1908. } else if (!Constructor->isDependentContext() &&
  1909. !Constructor->isDelegatingConstructor()) {
  1910. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1911. // Skip detailed checking if we have enough initializers, and we would
  1912. // allow at most one initializer per member.
  1913. bool AnyAnonStructUnionMembers = false;
  1914. unsigned Fields = 0;
  1915. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1916. E = RD->field_end(); I != E; ++I, ++Fields) {
  1917. if (I->isAnonymousStructOrUnion()) {
  1918. AnyAnonStructUnionMembers = true;
  1919. break;
  1920. }
  1921. }
  1922. // DR1460:
  1923. // - if the class is a union-like class, but is not a union, for each of
  1924. // its anonymous union members having variant members, exactly one of
  1925. // them shall be initialized;
  1926. if (AnyAnonStructUnionMembers ||
  1927. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1928. // Check initialization of non-static data members. Base classes are
  1929. // always initialized so do not need to be checked. Dependent bases
  1930. // might not have initializers in the member initializer list.
  1931. llvm::SmallSet<Decl*, 16> Inits;
  1932. for (const auto *I: Constructor->inits()) {
  1933. if (FieldDecl *FD = I->getMember())
  1934. Inits.insert(FD);
  1935. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1936. Inits.insert(ID->chain_begin(), ID->chain_end());
  1937. }
  1938. bool Diagnosed = false;
  1939. for (auto *I : RD->fields())
  1940. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1941. Kind))
  1942. return false;
  1943. }
  1944. }
  1945. } else {
  1946. if (ReturnStmts.empty()) {
  1947. // C++1y doesn't require constexpr functions to contain a 'return'
  1948. // statement. We still do, unless the return type might be void, because
  1949. // otherwise if there's no return statement, the function cannot
  1950. // be used in a core constant expression.
  1951. bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
  1952. (Dcl->getReturnType()->isVoidType() ||
  1953. Dcl->getReturnType()->isDependentType());
  1954. switch (Kind) {
  1955. case Sema::CheckConstexprKind::Diagnose:
  1956. SemaRef.Diag(Dcl->getLocation(),
  1957. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1958. : diag::err_constexpr_body_no_return)
  1959. << Dcl->isConsteval();
  1960. if (!OK)
  1961. return false;
  1962. break;
  1963. case Sema::CheckConstexprKind::CheckValid:
  1964. // The formal requirements don't include this rule in C++14, even
  1965. // though the "must be able to produce a constant expression" rules
  1966. // still imply it in some cases.
  1967. if (!SemaRef.getLangOpts().CPlusPlus14)
  1968. return false;
  1969. break;
  1970. }
  1971. } else if (ReturnStmts.size() > 1) {
  1972. switch (Kind) {
  1973. case Sema::CheckConstexprKind::Diagnose:
  1974. SemaRef.Diag(
  1975. ReturnStmts.back(),
  1976. SemaRef.getLangOpts().CPlusPlus14
  1977. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1978. : diag::ext_constexpr_body_multiple_return);
  1979. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1980. SemaRef.Diag(ReturnStmts[I],
  1981. diag::note_constexpr_body_previous_return);
  1982. break;
  1983. case Sema::CheckConstexprKind::CheckValid:
  1984. if (!SemaRef.getLangOpts().CPlusPlus14)
  1985. return false;
  1986. break;
  1987. }
  1988. }
  1989. }
  1990. // C++11 [dcl.constexpr]p5:
  1991. // if no function argument values exist such that the function invocation
  1992. // substitution would produce a constant expression, the program is
  1993. // ill-formed; no diagnostic required.
  1994. // C++11 [dcl.constexpr]p3:
  1995. // - every constructor call and implicit conversion used in initializing the
  1996. // return value shall be one of those allowed in a constant expression.
  1997. // C++11 [dcl.constexpr]p4:
  1998. // - every constructor involved in initializing non-static data members and
  1999. // base class sub-objects shall be a constexpr constructor.
  2000. //
  2001. // Note that this rule is distinct from the "requirements for a constexpr
  2002. // function", so is not checked in CheckValid mode.
  2003. SmallVector<PartialDiagnosticAt, 8> Diags;
  2004. if (Kind == Sema::CheckConstexprKind::Diagnose &&
  2005. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  2006. SemaRef.Diag(Dcl->getLocation(),
  2007. diag::ext_constexpr_function_never_constant_expr)
  2008. << isa<CXXConstructorDecl>(Dcl);
  2009. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  2010. SemaRef.Diag(Diags[I].first, Diags[I].second);
  2011. // Don't return false here: we allow this for compatibility in
  2012. // system headers.
  2013. }
  2014. return true;
  2015. }
  2016. /// Get the class that is directly named by the current context. This is the
  2017. /// class for which an unqualified-id in this scope could name a constructor
  2018. /// or destructor.
  2019. ///
  2020. /// If the scope specifier denotes a class, this will be that class.
  2021. /// If the scope specifier is empty, this will be the class whose
  2022. /// member-specification we are currently within. Otherwise, there
  2023. /// is no such class.
  2024. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  2025. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2026. if (SS && SS->isInvalid())
  2027. return nullptr;
  2028. if (SS && SS->isNotEmpty()) {
  2029. DeclContext *DC = computeDeclContext(*SS, true);
  2030. return dyn_cast_or_null<CXXRecordDecl>(DC);
  2031. }
  2032. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2033. }
  2034. /// isCurrentClassName - Determine whether the identifier II is the
  2035. /// name of the class type currently being defined. In the case of
  2036. /// nested classes, this will only return true if II is the name of
  2037. /// the innermost class.
  2038. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  2039. const CXXScopeSpec *SS) {
  2040. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  2041. return CurDecl && &II == CurDecl->getIdentifier();
  2042. }
  2043. /// Determine whether the identifier II is a typo for the name of
  2044. /// the class type currently being defined. If so, update it to the identifier
  2045. /// that should have been used.
  2046. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  2047. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2048. if (!getLangOpts().SpellChecking)
  2049. return false;
  2050. CXXRecordDecl *CurDecl;
  2051. if (SS && SS->isSet() && !SS->isInvalid()) {
  2052. DeclContext *DC = computeDeclContext(*SS, true);
  2053. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  2054. } else
  2055. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2056. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  2057. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  2058. < II->getLength()) {
  2059. II = CurDecl->getIdentifier();
  2060. return true;
  2061. }
  2062. return false;
  2063. }
  2064. /// Determine whether the given class is a base class of the given
  2065. /// class, including looking at dependent bases.
  2066. static bool findCircularInheritance(const CXXRecordDecl *Class,
  2067. const CXXRecordDecl *Current) {
  2068. SmallVector<const CXXRecordDecl*, 8> Queue;
  2069. Class = Class->getCanonicalDecl();
  2070. while (true) {
  2071. for (const auto &I : Current->bases()) {
  2072. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  2073. if (!Base)
  2074. continue;
  2075. Base = Base->getDefinition();
  2076. if (!Base)
  2077. continue;
  2078. if (Base->getCanonicalDecl() == Class)
  2079. return true;
  2080. Queue.push_back(Base);
  2081. }
  2082. if (Queue.empty())
  2083. return false;
  2084. Current = Queue.pop_back_val();
  2085. }
  2086. return false;
  2087. }
  2088. /// Check the validity of a C++ base class specifier.
  2089. ///
  2090. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  2091. /// and returns NULL otherwise.
  2092. CXXBaseSpecifier *
  2093. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  2094. SourceRange SpecifierRange,
  2095. bool Virtual, AccessSpecifier Access,
  2096. TypeSourceInfo *TInfo,
  2097. SourceLocation EllipsisLoc) {
  2098. QualType BaseType = TInfo->getType();
  2099. // C++ [class.union]p1:
  2100. // A union shall not have base classes.
  2101. if (Class->isUnion()) {
  2102. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  2103. << SpecifierRange;
  2104. return nullptr;
  2105. }
  2106. if (EllipsisLoc.isValid() &&
  2107. !TInfo->getType()->containsUnexpandedParameterPack()) {
  2108. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2109. << TInfo->getTypeLoc().getSourceRange();
  2110. EllipsisLoc = SourceLocation();
  2111. }
  2112. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2113. if (BaseType->isDependentType()) {
  2114. // Make sure that we don't have circular inheritance among our dependent
  2115. // bases. For non-dependent bases, the check for completeness below handles
  2116. // this.
  2117. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2118. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2119. ((BaseDecl = BaseDecl->getDefinition()) &&
  2120. findCircularInheritance(Class, BaseDecl))) {
  2121. Diag(BaseLoc, diag::err_circular_inheritance)
  2122. << BaseType << Context.getTypeDeclType(Class);
  2123. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2124. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2125. << BaseType;
  2126. return nullptr;
  2127. }
  2128. }
  2129. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2130. Class->getTagKind() == TTK_Class,
  2131. Access, TInfo, EllipsisLoc);
  2132. }
  2133. // Base specifiers must be record types.
  2134. if (!BaseType->isRecordType()) {
  2135. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2136. return nullptr;
  2137. }
  2138. // C++ [class.union]p1:
  2139. // A union shall not be used as a base class.
  2140. if (BaseType->isUnionType()) {
  2141. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2142. return nullptr;
  2143. }
  2144. // For the MS ABI, propagate DLL attributes to base class templates.
  2145. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2146. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2147. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2148. BaseType->getAsCXXRecordDecl())) {
  2149. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2150. BaseLoc);
  2151. }
  2152. }
  2153. }
  2154. // C++ [class.derived]p2:
  2155. // The class-name in a base-specifier shall not be an incompletely
  2156. // defined class.
  2157. if (RequireCompleteType(BaseLoc, BaseType,
  2158. diag::err_incomplete_base_class, SpecifierRange)) {
  2159. Class->setInvalidDecl();
  2160. return nullptr;
  2161. }
  2162. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2163. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  2164. assert(BaseDecl && "Record type has no declaration");
  2165. BaseDecl = BaseDecl->getDefinition();
  2166. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2167. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2168. assert(CXXBaseDecl && "Base type is not a C++ type");
  2169. // Microsoft docs say:
  2170. // "If a base-class has a code_seg attribute, derived classes must have the
  2171. // same attribute."
  2172. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2173. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2174. if ((DerivedCSA || BaseCSA) &&
  2175. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2176. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2177. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2178. << CXXBaseDecl;
  2179. return nullptr;
  2180. }
  2181. // A class which contains a flexible array member is not suitable for use as a
  2182. // base class:
  2183. // - If the layout determines that a base comes before another base,
  2184. // the flexible array member would index into the subsequent base.
  2185. // - If the layout determines that base comes before the derived class,
  2186. // the flexible array member would index into the derived class.
  2187. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2188. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2189. << CXXBaseDecl->getDeclName();
  2190. return nullptr;
  2191. }
  2192. // C++ [class]p3:
  2193. // If a class is marked final and it appears as a base-type-specifier in
  2194. // base-clause, the program is ill-formed.
  2195. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2196. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2197. << CXXBaseDecl->getDeclName()
  2198. << FA->isSpelledAsSealed();
  2199. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2200. << CXXBaseDecl->getDeclName() << FA->getRange();
  2201. return nullptr;
  2202. }
  2203. if (BaseDecl->isInvalidDecl())
  2204. Class->setInvalidDecl();
  2205. // Create the base specifier.
  2206. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2207. Class->getTagKind() == TTK_Class,
  2208. Access, TInfo, EllipsisLoc);
  2209. }
  2210. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2211. /// one entry in the base class list of a class specifier, for
  2212. /// example:
  2213. /// class foo : public bar, virtual private baz {
  2214. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2215. BaseResult
  2216. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2217. ParsedAttributes &Attributes,
  2218. bool Virtual, AccessSpecifier Access,
  2219. ParsedType basetype, SourceLocation BaseLoc,
  2220. SourceLocation EllipsisLoc) {
  2221. if (!classdecl)
  2222. return true;
  2223. AdjustDeclIfTemplate(classdecl);
  2224. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2225. if (!Class)
  2226. return true;
  2227. // We haven't yet attached the base specifiers.
  2228. Class->setIsParsingBaseSpecifiers();
  2229. // We do not support any C++11 attributes on base-specifiers yet.
  2230. // Diagnose any attributes we see.
  2231. for (const ParsedAttr &AL : Attributes) {
  2232. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2233. continue;
  2234. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2235. ? (unsigned)diag::warn_unknown_attribute_ignored
  2236. : (unsigned)diag::err_base_specifier_attribute)
  2237. << AL;
  2238. }
  2239. TypeSourceInfo *TInfo = nullptr;
  2240. GetTypeFromParser(basetype, &TInfo);
  2241. if (EllipsisLoc.isInvalid() &&
  2242. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2243. UPPC_BaseType))
  2244. return true;
  2245. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2246. Virtual, Access, TInfo,
  2247. EllipsisLoc))
  2248. return BaseSpec;
  2249. else
  2250. Class->setInvalidDecl();
  2251. return true;
  2252. }
  2253. /// Use small set to collect indirect bases. As this is only used
  2254. /// locally, there's no need to abstract the small size parameter.
  2255. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2256. /// Recursively add the bases of Type. Don't add Type itself.
  2257. static void
  2258. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2259. const QualType &Type)
  2260. {
  2261. // Even though the incoming type is a base, it might not be
  2262. // a class -- it could be a template parm, for instance.
  2263. if (auto Rec = Type->getAs<RecordType>()) {
  2264. auto Decl = Rec->getAsCXXRecordDecl();
  2265. // Iterate over its bases.
  2266. for (const auto &BaseSpec : Decl->bases()) {
  2267. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2268. .getUnqualifiedType();
  2269. if (Set.insert(Base).second)
  2270. // If we've not already seen it, recurse.
  2271. NoteIndirectBases(Context, Set, Base);
  2272. }
  2273. }
  2274. }
  2275. /// Performs the actual work of attaching the given base class
  2276. /// specifiers to a C++ class.
  2277. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2278. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2279. if (Bases.empty())
  2280. return false;
  2281. // Used to keep track of which base types we have already seen, so
  2282. // that we can properly diagnose redundant direct base types. Note
  2283. // that the key is always the unqualified canonical type of the base
  2284. // class.
  2285. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2286. // Used to track indirect bases so we can see if a direct base is
  2287. // ambiguous.
  2288. IndirectBaseSet IndirectBaseTypes;
  2289. // Copy non-redundant base specifiers into permanent storage.
  2290. unsigned NumGoodBases = 0;
  2291. bool Invalid = false;
  2292. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2293. QualType NewBaseType
  2294. = Context.getCanonicalType(Bases[idx]->getType());
  2295. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2296. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2297. if (KnownBase) {
  2298. // C++ [class.mi]p3:
  2299. // A class shall not be specified as a direct base class of a
  2300. // derived class more than once.
  2301. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2302. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2303. // Delete the duplicate base class specifier; we're going to
  2304. // overwrite its pointer later.
  2305. Context.Deallocate(Bases[idx]);
  2306. Invalid = true;
  2307. } else {
  2308. // Okay, add this new base class.
  2309. KnownBase = Bases[idx];
  2310. Bases[NumGoodBases++] = Bases[idx];
  2311. // Note this base's direct & indirect bases, if there could be ambiguity.
  2312. if (Bases.size() > 1)
  2313. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2314. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2315. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2316. if (Class->isInterface() &&
  2317. (!RD->isInterfaceLike() ||
  2318. KnownBase->getAccessSpecifier() != AS_public)) {
  2319. // The Microsoft extension __interface does not permit bases that
  2320. // are not themselves public interfaces.
  2321. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2322. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2323. << RD->getSourceRange();
  2324. Invalid = true;
  2325. }
  2326. if (RD->hasAttr<WeakAttr>())
  2327. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2328. }
  2329. }
  2330. }
  2331. // Attach the remaining base class specifiers to the derived class.
  2332. Class->setBases(Bases.data(), NumGoodBases);
  2333. // Check that the only base classes that are duplicate are virtual.
  2334. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2335. // Check whether this direct base is inaccessible due to ambiguity.
  2336. QualType BaseType = Bases[idx]->getType();
  2337. // Skip all dependent types in templates being used as base specifiers.
  2338. // Checks below assume that the base specifier is a CXXRecord.
  2339. if (BaseType->isDependentType())
  2340. continue;
  2341. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2342. .getUnqualifiedType();
  2343. if (IndirectBaseTypes.count(CanonicalBase)) {
  2344. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2345. /*DetectVirtual=*/true);
  2346. bool found
  2347. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2348. assert(found);
  2349. (void)found;
  2350. if (Paths.isAmbiguous(CanonicalBase))
  2351. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2352. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2353. << Bases[idx]->getSourceRange();
  2354. else
  2355. assert(Bases[idx]->isVirtual());
  2356. }
  2357. // Delete the base class specifier, since its data has been copied
  2358. // into the CXXRecordDecl.
  2359. Context.Deallocate(Bases[idx]);
  2360. }
  2361. return Invalid;
  2362. }
  2363. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2364. /// class, after checking whether there are any duplicate base
  2365. /// classes.
  2366. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2367. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2368. if (!ClassDecl || Bases.empty())
  2369. return;
  2370. AdjustDeclIfTemplate(ClassDecl);
  2371. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2372. }
  2373. /// Determine whether the type \p Derived is a C++ class that is
  2374. /// derived from the type \p Base.
  2375. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2376. if (!getLangOpts().CPlusPlus)
  2377. return false;
  2378. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2379. if (!DerivedRD)
  2380. return false;
  2381. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2382. if (!BaseRD)
  2383. return false;
  2384. // If either the base or the derived type is invalid, don't try to
  2385. // check whether one is derived from the other.
  2386. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2387. return false;
  2388. // FIXME: In a modules build, do we need the entire path to be visible for us
  2389. // to be able to use the inheritance relationship?
  2390. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2391. return false;
  2392. return DerivedRD->isDerivedFrom(BaseRD);
  2393. }
  2394. /// Determine whether the type \p Derived is a C++ class that is
  2395. /// derived from the type \p Base.
  2396. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2397. CXXBasePaths &Paths) {
  2398. if (!getLangOpts().CPlusPlus)
  2399. return false;
  2400. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2401. if (!DerivedRD)
  2402. return false;
  2403. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2404. if (!BaseRD)
  2405. return false;
  2406. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2407. return false;
  2408. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2409. }
  2410. static void BuildBasePathArray(const CXXBasePath &Path,
  2411. CXXCastPath &BasePathArray) {
  2412. // We first go backward and check if we have a virtual base.
  2413. // FIXME: It would be better if CXXBasePath had the base specifier for
  2414. // the nearest virtual base.
  2415. unsigned Start = 0;
  2416. for (unsigned I = Path.size(); I != 0; --I) {
  2417. if (Path[I - 1].Base->isVirtual()) {
  2418. Start = I - 1;
  2419. break;
  2420. }
  2421. }
  2422. // Now add all bases.
  2423. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2424. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2425. }
  2426. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2427. CXXCastPath &BasePathArray) {
  2428. assert(BasePathArray.empty() && "Base path array must be empty!");
  2429. assert(Paths.isRecordingPaths() && "Must record paths!");
  2430. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2431. }
  2432. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2433. /// conversion (where Derived and Base are class types) is
  2434. /// well-formed, meaning that the conversion is unambiguous (and
  2435. /// that all of the base classes are accessible). Returns true
  2436. /// and emits a diagnostic if the code is ill-formed, returns false
  2437. /// otherwise. Loc is the location where this routine should point to
  2438. /// if there is an error, and Range is the source range to highlight
  2439. /// if there is an error.
  2440. ///
  2441. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2442. /// diagnostic for the respective type of error will be suppressed, but the
  2443. /// check for ill-formed code will still be performed.
  2444. bool
  2445. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2446. unsigned InaccessibleBaseID,
  2447. unsigned AmbigiousBaseConvID,
  2448. SourceLocation Loc, SourceRange Range,
  2449. DeclarationName Name,
  2450. CXXCastPath *BasePath,
  2451. bool IgnoreAccess) {
  2452. // First, determine whether the path from Derived to Base is
  2453. // ambiguous. This is slightly more expensive than checking whether
  2454. // the Derived to Base conversion exists, because here we need to
  2455. // explore multiple paths to determine if there is an ambiguity.
  2456. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2457. /*DetectVirtual=*/false);
  2458. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2459. if (!DerivationOkay)
  2460. return true;
  2461. const CXXBasePath *Path = nullptr;
  2462. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2463. Path = &Paths.front();
  2464. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2465. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2466. // user to access such bases.
  2467. if (!Path && getLangOpts().MSVCCompat) {
  2468. for (const CXXBasePath &PossiblePath : Paths) {
  2469. if (PossiblePath.size() == 1) {
  2470. Path = &PossiblePath;
  2471. if (AmbigiousBaseConvID)
  2472. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2473. << Base << Derived << Range;
  2474. break;
  2475. }
  2476. }
  2477. }
  2478. if (Path) {
  2479. if (!IgnoreAccess) {
  2480. // Check that the base class can be accessed.
  2481. switch (
  2482. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2483. case AR_inaccessible:
  2484. return true;
  2485. case AR_accessible:
  2486. case AR_dependent:
  2487. case AR_delayed:
  2488. break;
  2489. }
  2490. }
  2491. // Build a base path if necessary.
  2492. if (BasePath)
  2493. ::BuildBasePathArray(*Path, *BasePath);
  2494. return false;
  2495. }
  2496. if (AmbigiousBaseConvID) {
  2497. // We know that the derived-to-base conversion is ambiguous, and
  2498. // we're going to produce a diagnostic. Perform the derived-to-base
  2499. // search just one more time to compute all of the possible paths so
  2500. // that we can print them out. This is more expensive than any of
  2501. // the previous derived-to-base checks we've done, but at this point
  2502. // performance isn't as much of an issue.
  2503. Paths.clear();
  2504. Paths.setRecordingPaths(true);
  2505. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2506. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2507. (void)StillOkay;
  2508. // Build up a textual representation of the ambiguous paths, e.g.,
  2509. // D -> B -> A, that will be used to illustrate the ambiguous
  2510. // conversions in the diagnostic. We only print one of the paths
  2511. // to each base class subobject.
  2512. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2513. Diag(Loc, AmbigiousBaseConvID)
  2514. << Derived << Base << PathDisplayStr << Range << Name;
  2515. }
  2516. return true;
  2517. }
  2518. bool
  2519. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2520. SourceLocation Loc, SourceRange Range,
  2521. CXXCastPath *BasePath,
  2522. bool IgnoreAccess) {
  2523. return CheckDerivedToBaseConversion(
  2524. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2525. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2526. BasePath, IgnoreAccess);
  2527. }
  2528. /// Builds a string representing ambiguous paths from a
  2529. /// specific derived class to different subobjects of the same base
  2530. /// class.
  2531. ///
  2532. /// This function builds a string that can be used in error messages
  2533. /// to show the different paths that one can take through the
  2534. /// inheritance hierarchy to go from the derived class to different
  2535. /// subobjects of a base class. The result looks something like this:
  2536. /// @code
  2537. /// struct D -> struct B -> struct A
  2538. /// struct D -> struct C -> struct A
  2539. /// @endcode
  2540. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2541. std::string PathDisplayStr;
  2542. std::set<unsigned> DisplayedPaths;
  2543. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2544. Path != Paths.end(); ++Path) {
  2545. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2546. // We haven't displayed a path to this particular base
  2547. // class subobject yet.
  2548. PathDisplayStr += "\n ";
  2549. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2550. for (CXXBasePath::const_iterator Element = Path->begin();
  2551. Element != Path->end(); ++Element)
  2552. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2553. }
  2554. }
  2555. return PathDisplayStr;
  2556. }
  2557. //===----------------------------------------------------------------------===//
  2558. // C++ class member Handling
  2559. //===----------------------------------------------------------------------===//
  2560. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2561. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2562. SourceLocation ColonLoc,
  2563. const ParsedAttributesView &Attrs) {
  2564. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2565. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2566. ASLoc, ColonLoc);
  2567. CurContext->addHiddenDecl(ASDecl);
  2568. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2569. }
  2570. /// CheckOverrideControl - Check C++11 override control semantics.
  2571. void Sema::CheckOverrideControl(NamedDecl *D) {
  2572. if (D->isInvalidDecl())
  2573. return;
  2574. // We only care about "override" and "final" declarations.
  2575. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2576. return;
  2577. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2578. // We can't check dependent instance methods.
  2579. if (MD && MD->isInstance() &&
  2580. (MD->getParent()->hasAnyDependentBases() ||
  2581. MD->getType()->isDependentType()))
  2582. return;
  2583. if (MD && !MD->isVirtual()) {
  2584. // If we have a non-virtual method, check if if hides a virtual method.
  2585. // (In that case, it's most likely the method has the wrong type.)
  2586. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2587. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2588. if (!OverloadedMethods.empty()) {
  2589. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2590. Diag(OA->getLocation(),
  2591. diag::override_keyword_hides_virtual_member_function)
  2592. << "override" << (OverloadedMethods.size() > 1);
  2593. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2594. Diag(FA->getLocation(),
  2595. diag::override_keyword_hides_virtual_member_function)
  2596. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2597. << (OverloadedMethods.size() > 1);
  2598. }
  2599. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2600. MD->setInvalidDecl();
  2601. return;
  2602. }
  2603. // Fall through into the general case diagnostic.
  2604. // FIXME: We might want to attempt typo correction here.
  2605. }
  2606. if (!MD || !MD->isVirtual()) {
  2607. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2608. Diag(OA->getLocation(),
  2609. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2610. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2611. D->dropAttr<OverrideAttr>();
  2612. }
  2613. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2614. Diag(FA->getLocation(),
  2615. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2616. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2617. << FixItHint::CreateRemoval(FA->getLocation());
  2618. D->dropAttr<FinalAttr>();
  2619. }
  2620. return;
  2621. }
  2622. // C++11 [class.virtual]p5:
  2623. // If a function is marked with the virt-specifier override and
  2624. // does not override a member function of a base class, the program is
  2625. // ill-formed.
  2626. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2627. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2628. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2629. << MD->getDeclName();
  2630. }
  2631. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2632. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2633. return;
  2634. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2635. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2636. return;
  2637. SourceLocation Loc = MD->getLocation();
  2638. SourceLocation SpellingLoc = Loc;
  2639. if (getSourceManager().isMacroArgExpansion(Loc))
  2640. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2641. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2642. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2643. return;
  2644. if (MD->size_overridden_methods() > 0) {
  2645. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2646. ? diag::warn_destructor_marked_not_override_overriding
  2647. : diag::warn_function_marked_not_override_overriding;
  2648. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2649. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2650. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2651. }
  2652. }
  2653. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2654. /// function overrides a virtual member function marked 'final', according to
  2655. /// C++11 [class.virtual]p4.
  2656. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2657. const CXXMethodDecl *Old) {
  2658. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2659. if (!FA)
  2660. return false;
  2661. Diag(New->getLocation(), diag::err_final_function_overridden)
  2662. << New->getDeclName()
  2663. << FA->isSpelledAsSealed();
  2664. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2665. return true;
  2666. }
  2667. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2668. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2669. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2670. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2671. return !RD->isCompleteDefinition() ||
  2672. !RD->hasTrivialDefaultConstructor() ||
  2673. !RD->hasTrivialDestructor();
  2674. return false;
  2675. }
  2676. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2677. ParsedAttributesView::const_iterator Itr =
  2678. llvm::find_if(list, [](const ParsedAttr &AL) {
  2679. return AL.isDeclspecPropertyAttribute();
  2680. });
  2681. if (Itr != list.end())
  2682. return &*Itr;
  2683. return nullptr;
  2684. }
  2685. // Check if there is a field shadowing.
  2686. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2687. DeclarationName FieldName,
  2688. const CXXRecordDecl *RD,
  2689. bool DeclIsField) {
  2690. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2691. return;
  2692. // To record a shadowed field in a base
  2693. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2694. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2695. CXXBasePath &Path) {
  2696. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2697. // Record an ambiguous path directly
  2698. if (Bases.find(Base) != Bases.end())
  2699. return true;
  2700. for (const auto Field : Base->lookup(FieldName)) {
  2701. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2702. Field->getAccess() != AS_private) {
  2703. assert(Field->getAccess() != AS_none);
  2704. assert(Bases.find(Base) == Bases.end());
  2705. Bases[Base] = Field;
  2706. return true;
  2707. }
  2708. }
  2709. return false;
  2710. };
  2711. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2712. /*DetectVirtual=*/true);
  2713. if (!RD->lookupInBases(FieldShadowed, Paths))
  2714. return;
  2715. for (const auto &P : Paths) {
  2716. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2717. auto It = Bases.find(Base);
  2718. // Skip duplicated bases
  2719. if (It == Bases.end())
  2720. continue;
  2721. auto BaseField = It->second;
  2722. assert(BaseField->getAccess() != AS_private);
  2723. if (AS_none !=
  2724. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2725. Diag(Loc, diag::warn_shadow_field)
  2726. << FieldName << RD << Base << DeclIsField;
  2727. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2728. Bases.erase(It);
  2729. }
  2730. }
  2731. }
  2732. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2733. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2734. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2735. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2736. /// present (but parsing it has been deferred).
  2737. NamedDecl *
  2738. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2739. MultiTemplateParamsArg TemplateParameterLists,
  2740. Expr *BW, const VirtSpecifiers &VS,
  2741. InClassInitStyle InitStyle) {
  2742. const DeclSpec &DS = D.getDeclSpec();
  2743. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2744. DeclarationName Name = NameInfo.getName();
  2745. SourceLocation Loc = NameInfo.getLoc();
  2746. // For anonymous bitfields, the location should point to the type.
  2747. if (Loc.isInvalid())
  2748. Loc = D.getBeginLoc();
  2749. Expr *BitWidth = static_cast<Expr*>(BW);
  2750. assert(isa<CXXRecordDecl>(CurContext));
  2751. assert(!DS.isFriendSpecified());
  2752. bool isFunc = D.isDeclarationOfFunction();
  2753. const ParsedAttr *MSPropertyAttr =
  2754. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2755. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2756. // The Microsoft extension __interface only permits public member functions
  2757. // and prohibits constructors, destructors, operators, non-public member
  2758. // functions, static methods and data members.
  2759. unsigned InvalidDecl;
  2760. bool ShowDeclName = true;
  2761. if (!isFunc &&
  2762. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2763. InvalidDecl = 0;
  2764. else if (!isFunc)
  2765. InvalidDecl = 1;
  2766. else if (AS != AS_public)
  2767. InvalidDecl = 2;
  2768. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2769. InvalidDecl = 3;
  2770. else switch (Name.getNameKind()) {
  2771. case DeclarationName::CXXConstructorName:
  2772. InvalidDecl = 4;
  2773. ShowDeclName = false;
  2774. break;
  2775. case DeclarationName::CXXDestructorName:
  2776. InvalidDecl = 5;
  2777. ShowDeclName = false;
  2778. break;
  2779. case DeclarationName::CXXOperatorName:
  2780. case DeclarationName::CXXConversionFunctionName:
  2781. InvalidDecl = 6;
  2782. break;
  2783. default:
  2784. InvalidDecl = 0;
  2785. break;
  2786. }
  2787. if (InvalidDecl) {
  2788. if (ShowDeclName)
  2789. Diag(Loc, diag::err_invalid_member_in_interface)
  2790. << (InvalidDecl-1) << Name;
  2791. else
  2792. Diag(Loc, diag::err_invalid_member_in_interface)
  2793. << (InvalidDecl-1) << "";
  2794. return nullptr;
  2795. }
  2796. }
  2797. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2798. // duration (auto, register) or with the extern storage-class-specifier.
  2799. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2800. // data members and cannot be applied to names declared const or static,
  2801. // and cannot be applied to reference members.
  2802. switch (DS.getStorageClassSpec()) {
  2803. case DeclSpec::SCS_unspecified:
  2804. case DeclSpec::SCS_typedef:
  2805. case DeclSpec::SCS_static:
  2806. break;
  2807. case DeclSpec::SCS_mutable:
  2808. if (isFunc) {
  2809. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2810. // FIXME: It would be nicer if the keyword was ignored only for this
  2811. // declarator. Otherwise we could get follow-up errors.
  2812. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2813. }
  2814. break;
  2815. default:
  2816. Diag(DS.getStorageClassSpecLoc(),
  2817. diag::err_storageclass_invalid_for_member);
  2818. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2819. break;
  2820. }
  2821. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2822. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2823. !isFunc);
  2824. if (DS.hasConstexprSpecifier() && isInstField) {
  2825. SemaDiagnosticBuilder B =
  2826. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2827. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2828. if (InitStyle == ICIS_NoInit) {
  2829. B << 0 << 0;
  2830. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2831. B << FixItHint::CreateRemoval(ConstexprLoc);
  2832. else {
  2833. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2834. D.getMutableDeclSpec().ClearConstexprSpec();
  2835. const char *PrevSpec;
  2836. unsigned DiagID;
  2837. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2838. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2839. (void)Failed;
  2840. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2841. }
  2842. } else {
  2843. B << 1;
  2844. const char *PrevSpec;
  2845. unsigned DiagID;
  2846. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2847. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2848. Context.getPrintingPolicy())) {
  2849. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2850. "This is the only DeclSpec that should fail to be applied");
  2851. B << 1;
  2852. } else {
  2853. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2854. isInstField = false;
  2855. }
  2856. }
  2857. }
  2858. NamedDecl *Member;
  2859. if (isInstField) {
  2860. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2861. // Data members must have identifiers for names.
  2862. if (!Name.isIdentifier()) {
  2863. Diag(Loc, diag::err_bad_variable_name)
  2864. << Name;
  2865. return nullptr;
  2866. }
  2867. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2868. // Member field could not be with "template" keyword.
  2869. // So TemplateParameterLists should be empty in this case.
  2870. if (TemplateParameterLists.size()) {
  2871. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2872. if (TemplateParams->size()) {
  2873. // There is no such thing as a member field template.
  2874. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2875. << II
  2876. << SourceRange(TemplateParams->getTemplateLoc(),
  2877. TemplateParams->getRAngleLoc());
  2878. } else {
  2879. // There is an extraneous 'template<>' for this member.
  2880. Diag(TemplateParams->getTemplateLoc(),
  2881. diag::err_template_member_noparams)
  2882. << II
  2883. << SourceRange(TemplateParams->getTemplateLoc(),
  2884. TemplateParams->getRAngleLoc());
  2885. }
  2886. return nullptr;
  2887. }
  2888. if (SS.isSet() && !SS.isInvalid()) {
  2889. // The user provided a superfluous scope specifier inside a class
  2890. // definition:
  2891. //
  2892. // class X {
  2893. // int X::member;
  2894. // };
  2895. if (DeclContext *DC = computeDeclContext(SS, false))
  2896. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2897. D.getName().getKind() ==
  2898. UnqualifiedIdKind::IK_TemplateId);
  2899. else
  2900. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2901. << Name << SS.getRange();
  2902. SS.clear();
  2903. }
  2904. if (MSPropertyAttr) {
  2905. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2906. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2907. if (!Member)
  2908. return nullptr;
  2909. isInstField = false;
  2910. } else {
  2911. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2912. BitWidth, InitStyle, AS);
  2913. if (!Member)
  2914. return nullptr;
  2915. }
  2916. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2917. } else {
  2918. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2919. if (!Member)
  2920. return nullptr;
  2921. // Non-instance-fields can't have a bitfield.
  2922. if (BitWidth) {
  2923. if (Member->isInvalidDecl()) {
  2924. // don't emit another diagnostic.
  2925. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2926. // C++ 9.6p3: A bit-field shall not be a static member.
  2927. // "static member 'A' cannot be a bit-field"
  2928. Diag(Loc, diag::err_static_not_bitfield)
  2929. << Name << BitWidth->getSourceRange();
  2930. } else if (isa<TypedefDecl>(Member)) {
  2931. // "typedef member 'x' cannot be a bit-field"
  2932. Diag(Loc, diag::err_typedef_not_bitfield)
  2933. << Name << BitWidth->getSourceRange();
  2934. } else {
  2935. // A function typedef ("typedef int f(); f a;").
  2936. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2937. Diag(Loc, diag::err_not_integral_type_bitfield)
  2938. << Name << cast<ValueDecl>(Member)->getType()
  2939. << BitWidth->getSourceRange();
  2940. }
  2941. BitWidth = nullptr;
  2942. Member->setInvalidDecl();
  2943. }
  2944. NamedDecl *NonTemplateMember = Member;
  2945. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2946. NonTemplateMember = FunTmpl->getTemplatedDecl();
  2947. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2948. NonTemplateMember = VarTmpl->getTemplatedDecl();
  2949. Member->setAccess(AS);
  2950. // If we have declared a member function template or static data member
  2951. // template, set the access of the templated declaration as well.
  2952. if (NonTemplateMember != Member)
  2953. NonTemplateMember->setAccess(AS);
  2954. // C++ [temp.deduct.guide]p3:
  2955. // A deduction guide [...] for a member class template [shall be
  2956. // declared] with the same access [as the template].
  2957. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  2958. auto *TD = DG->getDeducedTemplate();
  2959. // Access specifiers are only meaningful if both the template and the
  2960. // deduction guide are from the same scope.
  2961. if (AS != TD->getAccess() &&
  2962. TD->getDeclContext()->getRedeclContext()->Equals(
  2963. DG->getDeclContext()->getRedeclContext())) {
  2964. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  2965. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  2966. << TD->getAccess();
  2967. const AccessSpecDecl *LastAccessSpec = nullptr;
  2968. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  2969. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  2970. LastAccessSpec = AccessSpec;
  2971. }
  2972. assert(LastAccessSpec && "differing access with no access specifier");
  2973. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  2974. << AS;
  2975. }
  2976. }
  2977. }
  2978. if (VS.isOverrideSpecified())
  2979. Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
  2980. AttributeCommonInfo::AS_Keyword));
  2981. if (VS.isFinalSpecified())
  2982. Member->addAttr(FinalAttr::Create(
  2983. Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
  2984. static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
  2985. if (VS.getLastLocation().isValid()) {
  2986. // Update the end location of a method that has a virt-specifiers.
  2987. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2988. MD->setRangeEnd(VS.getLastLocation());
  2989. }
  2990. CheckOverrideControl(Member);
  2991. assert((Name || isInstField) && "No identifier for non-field ?");
  2992. if (isInstField) {
  2993. FieldDecl *FD = cast<FieldDecl>(Member);
  2994. FieldCollector->Add(FD);
  2995. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2996. // Remember all explicit private FieldDecls that have a name, no side
  2997. // effects and are not part of a dependent type declaration.
  2998. if (!FD->isImplicit() && FD->getDeclName() &&
  2999. FD->getAccess() == AS_private &&
  3000. !FD->hasAttr<UnusedAttr>() &&
  3001. !FD->getParent()->isDependentContext() &&
  3002. !InitializationHasSideEffects(*FD))
  3003. UnusedPrivateFields.insert(FD);
  3004. }
  3005. }
  3006. return Member;
  3007. }
  3008. namespace {
  3009. class UninitializedFieldVisitor
  3010. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  3011. Sema &S;
  3012. // List of Decls to generate a warning on. Also remove Decls that become
  3013. // initialized.
  3014. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  3015. // List of base classes of the record. Classes are removed after their
  3016. // initializers.
  3017. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  3018. // Vector of decls to be removed from the Decl set prior to visiting the
  3019. // nodes. These Decls may have been initialized in the prior initializer.
  3020. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  3021. // If non-null, add a note to the warning pointing back to the constructor.
  3022. const CXXConstructorDecl *Constructor;
  3023. // Variables to hold state when processing an initializer list. When
  3024. // InitList is true, special case initialization of FieldDecls matching
  3025. // InitListFieldDecl.
  3026. bool InitList;
  3027. FieldDecl *InitListFieldDecl;
  3028. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  3029. public:
  3030. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  3031. UninitializedFieldVisitor(Sema &S,
  3032. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  3033. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  3034. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  3035. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  3036. // Returns true if the use of ME is not an uninitialized use.
  3037. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  3038. bool CheckReferenceOnly) {
  3039. llvm::SmallVector<FieldDecl*, 4> Fields;
  3040. bool ReferenceField = false;
  3041. while (ME) {
  3042. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  3043. if (!FD)
  3044. return false;
  3045. Fields.push_back(FD);
  3046. if (FD->getType()->isReferenceType())
  3047. ReferenceField = true;
  3048. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  3049. }
  3050. // Binding a reference to an uninitialized field is not an
  3051. // uninitialized use.
  3052. if (CheckReferenceOnly && !ReferenceField)
  3053. return true;
  3054. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  3055. // Discard the first field since it is the field decl that is being
  3056. // initialized.
  3057. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  3058. UsedFieldIndex.push_back((*I)->getFieldIndex());
  3059. }
  3060. for (auto UsedIter = UsedFieldIndex.begin(),
  3061. UsedEnd = UsedFieldIndex.end(),
  3062. OrigIter = InitFieldIndex.begin(),
  3063. OrigEnd = InitFieldIndex.end();
  3064. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  3065. if (*UsedIter < *OrigIter)
  3066. return true;
  3067. if (*UsedIter > *OrigIter)
  3068. break;
  3069. }
  3070. return false;
  3071. }
  3072. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  3073. bool AddressOf) {
  3074. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  3075. return;
  3076. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  3077. // or union.
  3078. MemberExpr *FieldME = ME;
  3079. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  3080. Expr *Base = ME;
  3081. while (MemberExpr *SubME =
  3082. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  3083. if (isa<VarDecl>(SubME->getMemberDecl()))
  3084. return;
  3085. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  3086. if (!FD->isAnonymousStructOrUnion())
  3087. FieldME = SubME;
  3088. if (!FieldME->getType().isPODType(S.Context))
  3089. AllPODFields = false;
  3090. Base = SubME->getBase();
  3091. }
  3092. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  3093. return;
  3094. if (AddressOf && AllPODFields)
  3095. return;
  3096. ValueDecl* FoundVD = FieldME->getMemberDecl();
  3097. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  3098. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  3099. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  3100. }
  3101. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  3102. QualType T = BaseCast->getType();
  3103. if (T->isPointerType() &&
  3104. BaseClasses.count(T->getPointeeType())) {
  3105. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  3106. << T->getPointeeType() << FoundVD;
  3107. }
  3108. }
  3109. }
  3110. if (!Decls.count(FoundVD))
  3111. return;
  3112. const bool IsReference = FoundVD->getType()->isReferenceType();
  3113. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3114. // Special checking for initializer lists.
  3115. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3116. return;
  3117. }
  3118. } else {
  3119. // Prevent double warnings on use of unbounded references.
  3120. if (CheckReferenceOnly && !IsReference)
  3121. return;
  3122. }
  3123. unsigned diag = IsReference
  3124. ? diag::warn_reference_field_is_uninit
  3125. : diag::warn_field_is_uninit;
  3126. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3127. if (Constructor)
  3128. S.Diag(Constructor->getLocation(),
  3129. diag::note_uninit_in_this_constructor)
  3130. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3131. }
  3132. void HandleValue(Expr *E, bool AddressOf) {
  3133. E = E->IgnoreParens();
  3134. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3135. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3136. AddressOf /*AddressOf*/);
  3137. return;
  3138. }
  3139. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3140. Visit(CO->getCond());
  3141. HandleValue(CO->getTrueExpr(), AddressOf);
  3142. HandleValue(CO->getFalseExpr(), AddressOf);
  3143. return;
  3144. }
  3145. if (BinaryConditionalOperator *BCO =
  3146. dyn_cast<BinaryConditionalOperator>(E)) {
  3147. Visit(BCO->getCond());
  3148. HandleValue(BCO->getFalseExpr(), AddressOf);
  3149. return;
  3150. }
  3151. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3152. HandleValue(OVE->getSourceExpr(), AddressOf);
  3153. return;
  3154. }
  3155. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3156. switch (BO->getOpcode()) {
  3157. default:
  3158. break;
  3159. case(BO_PtrMemD):
  3160. case(BO_PtrMemI):
  3161. HandleValue(BO->getLHS(), AddressOf);
  3162. Visit(BO->getRHS());
  3163. return;
  3164. case(BO_Comma):
  3165. Visit(BO->getLHS());
  3166. HandleValue(BO->getRHS(), AddressOf);
  3167. return;
  3168. }
  3169. }
  3170. Visit(E);
  3171. }
  3172. void CheckInitListExpr(InitListExpr *ILE) {
  3173. InitFieldIndex.push_back(0);
  3174. for (auto Child : ILE->children()) {
  3175. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3176. CheckInitListExpr(SubList);
  3177. } else {
  3178. Visit(Child);
  3179. }
  3180. ++InitFieldIndex.back();
  3181. }
  3182. InitFieldIndex.pop_back();
  3183. }
  3184. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3185. FieldDecl *Field, const Type *BaseClass) {
  3186. // Remove Decls that may have been initialized in the previous
  3187. // initializer.
  3188. for (ValueDecl* VD : DeclsToRemove)
  3189. Decls.erase(VD);
  3190. DeclsToRemove.clear();
  3191. Constructor = FieldConstructor;
  3192. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3193. if (ILE && Field) {
  3194. InitList = true;
  3195. InitListFieldDecl = Field;
  3196. InitFieldIndex.clear();
  3197. CheckInitListExpr(ILE);
  3198. } else {
  3199. InitList = false;
  3200. Visit(E);
  3201. }
  3202. if (Field)
  3203. Decls.erase(Field);
  3204. if (BaseClass)
  3205. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3206. }
  3207. void VisitMemberExpr(MemberExpr *ME) {
  3208. // All uses of unbounded reference fields will warn.
  3209. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3210. }
  3211. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3212. if (E->getCastKind() == CK_LValueToRValue) {
  3213. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3214. return;
  3215. }
  3216. Inherited::VisitImplicitCastExpr(E);
  3217. }
  3218. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3219. if (E->getConstructor()->isCopyConstructor()) {
  3220. Expr *ArgExpr = E->getArg(0);
  3221. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3222. if (ILE->getNumInits() == 1)
  3223. ArgExpr = ILE->getInit(0);
  3224. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3225. if (ICE->getCastKind() == CK_NoOp)
  3226. ArgExpr = ICE->getSubExpr();
  3227. HandleValue(ArgExpr, false /*AddressOf*/);
  3228. return;
  3229. }
  3230. Inherited::VisitCXXConstructExpr(E);
  3231. }
  3232. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3233. Expr *Callee = E->getCallee();
  3234. if (isa<MemberExpr>(Callee)) {
  3235. HandleValue(Callee, false /*AddressOf*/);
  3236. for (auto Arg : E->arguments())
  3237. Visit(Arg);
  3238. return;
  3239. }
  3240. Inherited::VisitCXXMemberCallExpr(E);
  3241. }
  3242. void VisitCallExpr(CallExpr *E) {
  3243. // Treat std::move as a use.
  3244. if (E->isCallToStdMove()) {
  3245. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3246. return;
  3247. }
  3248. Inherited::VisitCallExpr(E);
  3249. }
  3250. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3251. Expr *Callee = E->getCallee();
  3252. if (isa<UnresolvedLookupExpr>(Callee))
  3253. return Inherited::VisitCXXOperatorCallExpr(E);
  3254. Visit(Callee);
  3255. for (auto Arg : E->arguments())
  3256. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3257. }
  3258. void VisitBinaryOperator(BinaryOperator *E) {
  3259. // If a field assignment is detected, remove the field from the
  3260. // uninitiailized field set.
  3261. if (E->getOpcode() == BO_Assign)
  3262. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3263. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3264. if (!FD->getType()->isReferenceType())
  3265. DeclsToRemove.push_back(FD);
  3266. if (E->isCompoundAssignmentOp()) {
  3267. HandleValue(E->getLHS(), false /*AddressOf*/);
  3268. Visit(E->getRHS());
  3269. return;
  3270. }
  3271. Inherited::VisitBinaryOperator(E);
  3272. }
  3273. void VisitUnaryOperator(UnaryOperator *E) {
  3274. if (E->isIncrementDecrementOp()) {
  3275. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3276. return;
  3277. }
  3278. if (E->getOpcode() == UO_AddrOf) {
  3279. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3280. HandleValue(ME->getBase(), true /*AddressOf*/);
  3281. return;
  3282. }
  3283. }
  3284. Inherited::VisitUnaryOperator(E);
  3285. }
  3286. };
  3287. // Diagnose value-uses of fields to initialize themselves, e.g.
  3288. // foo(foo)
  3289. // where foo is not also a parameter to the constructor.
  3290. // Also diagnose across field uninitialized use such as
  3291. // x(y), y(x)
  3292. // TODO: implement -Wuninitialized and fold this into that framework.
  3293. static void DiagnoseUninitializedFields(
  3294. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3295. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3296. Constructor->getLocation())) {
  3297. return;
  3298. }
  3299. if (Constructor->isInvalidDecl())
  3300. return;
  3301. const CXXRecordDecl *RD = Constructor->getParent();
  3302. if (RD->getDescribedClassTemplate())
  3303. return;
  3304. // Holds fields that are uninitialized.
  3305. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3306. // At the beginning, all fields are uninitialized.
  3307. for (auto *I : RD->decls()) {
  3308. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3309. UninitializedFields.insert(FD);
  3310. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3311. UninitializedFields.insert(IFD->getAnonField());
  3312. }
  3313. }
  3314. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3315. for (auto I : RD->bases())
  3316. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3317. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3318. return;
  3319. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3320. UninitializedFields,
  3321. UninitializedBaseClasses);
  3322. for (const auto *FieldInit : Constructor->inits()) {
  3323. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3324. break;
  3325. Expr *InitExpr = FieldInit->getInit();
  3326. if (!InitExpr)
  3327. continue;
  3328. if (CXXDefaultInitExpr *Default =
  3329. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3330. InitExpr = Default->getExpr();
  3331. if (!InitExpr)
  3332. continue;
  3333. // In class initializers will point to the constructor.
  3334. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3335. FieldInit->getAnyMember(),
  3336. FieldInit->getBaseClass());
  3337. } else {
  3338. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3339. FieldInit->getAnyMember(),
  3340. FieldInit->getBaseClass());
  3341. }
  3342. }
  3343. }
  3344. } // namespace
  3345. /// Enter a new C++ default initializer scope. After calling this, the
  3346. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3347. /// parsing or instantiating the initializer failed.
  3348. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3349. // Create a synthetic function scope to represent the call to the constructor
  3350. // that notionally surrounds a use of this initializer.
  3351. PushFunctionScope();
  3352. }
  3353. /// This is invoked after parsing an in-class initializer for a
  3354. /// non-static C++ class member, and after instantiating an in-class initializer
  3355. /// in a class template. Such actions are deferred until the class is complete.
  3356. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3357. SourceLocation InitLoc,
  3358. Expr *InitExpr) {
  3359. // Pop the notional constructor scope we created earlier.
  3360. PopFunctionScopeInfo(nullptr, D);
  3361. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3362. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3363. "must set init style when field is created");
  3364. if (!InitExpr) {
  3365. D->setInvalidDecl();
  3366. if (FD)
  3367. FD->removeInClassInitializer();
  3368. return;
  3369. }
  3370. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3371. FD->setInvalidDecl();
  3372. FD->removeInClassInitializer();
  3373. return;
  3374. }
  3375. ExprResult Init = InitExpr;
  3376. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3377. InitializedEntity Entity =
  3378. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3379. InitializationKind Kind =
  3380. FD->getInClassInitStyle() == ICIS_ListInit
  3381. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3382. InitExpr->getBeginLoc(),
  3383. InitExpr->getEndLoc())
  3384. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3385. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3386. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3387. if (Init.isInvalid()) {
  3388. FD->setInvalidDecl();
  3389. return;
  3390. }
  3391. }
  3392. // C++11 [class.base.init]p7:
  3393. // The initialization of each base and member constitutes a
  3394. // full-expression.
  3395. Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
  3396. if (Init.isInvalid()) {
  3397. FD->setInvalidDecl();
  3398. return;
  3399. }
  3400. InitExpr = Init.get();
  3401. FD->setInClassInitializer(InitExpr);
  3402. }
  3403. /// Find the direct and/or virtual base specifiers that
  3404. /// correspond to the given base type, for use in base initialization
  3405. /// within a constructor.
  3406. static bool FindBaseInitializer(Sema &SemaRef,
  3407. CXXRecordDecl *ClassDecl,
  3408. QualType BaseType,
  3409. const CXXBaseSpecifier *&DirectBaseSpec,
  3410. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3411. // First, check for a direct base class.
  3412. DirectBaseSpec = nullptr;
  3413. for (const auto &Base : ClassDecl->bases()) {
  3414. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3415. // We found a direct base of this type. That's what we're
  3416. // initializing.
  3417. DirectBaseSpec = &Base;
  3418. break;
  3419. }
  3420. }
  3421. // Check for a virtual base class.
  3422. // FIXME: We might be able to short-circuit this if we know in advance that
  3423. // there are no virtual bases.
  3424. VirtualBaseSpec = nullptr;
  3425. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3426. // We haven't found a base yet; search the class hierarchy for a
  3427. // virtual base class.
  3428. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3429. /*DetectVirtual=*/false);
  3430. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3431. SemaRef.Context.getTypeDeclType(ClassDecl),
  3432. BaseType, Paths)) {
  3433. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3434. Path != Paths.end(); ++Path) {
  3435. if (Path->back().Base->isVirtual()) {
  3436. VirtualBaseSpec = Path->back().Base;
  3437. break;
  3438. }
  3439. }
  3440. }
  3441. }
  3442. return DirectBaseSpec || VirtualBaseSpec;
  3443. }
  3444. /// Handle a C++ member initializer using braced-init-list syntax.
  3445. MemInitResult
  3446. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3447. Scope *S,
  3448. CXXScopeSpec &SS,
  3449. IdentifierInfo *MemberOrBase,
  3450. ParsedType TemplateTypeTy,
  3451. const DeclSpec &DS,
  3452. SourceLocation IdLoc,
  3453. Expr *InitList,
  3454. SourceLocation EllipsisLoc) {
  3455. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3456. DS, IdLoc, InitList,
  3457. EllipsisLoc);
  3458. }
  3459. /// Handle a C++ member initializer using parentheses syntax.
  3460. MemInitResult
  3461. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3462. Scope *S,
  3463. CXXScopeSpec &SS,
  3464. IdentifierInfo *MemberOrBase,
  3465. ParsedType TemplateTypeTy,
  3466. const DeclSpec &DS,
  3467. SourceLocation IdLoc,
  3468. SourceLocation LParenLoc,
  3469. ArrayRef<Expr *> Args,
  3470. SourceLocation RParenLoc,
  3471. SourceLocation EllipsisLoc) {
  3472. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3473. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3474. DS, IdLoc, List, EllipsisLoc);
  3475. }
  3476. namespace {
  3477. // Callback to only accept typo corrections that can be a valid C++ member
  3478. // intializer: either a non-static field member or a base class.
  3479. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3480. public:
  3481. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3482. : ClassDecl(ClassDecl) {}
  3483. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3484. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3485. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3486. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3487. return isa<TypeDecl>(ND);
  3488. }
  3489. return false;
  3490. }
  3491. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3492. return std::make_unique<MemInitializerValidatorCCC>(*this);
  3493. }
  3494. private:
  3495. CXXRecordDecl *ClassDecl;
  3496. };
  3497. }
  3498. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3499. CXXScopeSpec &SS,
  3500. ParsedType TemplateTypeTy,
  3501. IdentifierInfo *MemberOrBase) {
  3502. if (SS.getScopeRep() || TemplateTypeTy)
  3503. return nullptr;
  3504. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3505. if (Result.empty())
  3506. return nullptr;
  3507. ValueDecl *Member;
  3508. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3509. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3510. return Member;
  3511. return nullptr;
  3512. }
  3513. /// Handle a C++ member initializer.
  3514. MemInitResult
  3515. Sema::BuildMemInitializer(Decl *ConstructorD,
  3516. Scope *S,
  3517. CXXScopeSpec &SS,
  3518. IdentifierInfo *MemberOrBase,
  3519. ParsedType TemplateTypeTy,
  3520. const DeclSpec &DS,
  3521. SourceLocation IdLoc,
  3522. Expr *Init,
  3523. SourceLocation EllipsisLoc) {
  3524. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3525. if (!Res.isUsable())
  3526. return true;
  3527. Init = Res.get();
  3528. if (!ConstructorD)
  3529. return true;
  3530. AdjustDeclIfTemplate(ConstructorD);
  3531. CXXConstructorDecl *Constructor
  3532. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3533. if (!Constructor) {
  3534. // The user wrote a constructor initializer on a function that is
  3535. // not a C++ constructor. Ignore the error for now, because we may
  3536. // have more member initializers coming; we'll diagnose it just
  3537. // once in ActOnMemInitializers.
  3538. return true;
  3539. }
  3540. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3541. // C++ [class.base.init]p2:
  3542. // Names in a mem-initializer-id are looked up in the scope of the
  3543. // constructor's class and, if not found in that scope, are looked
  3544. // up in the scope containing the constructor's definition.
  3545. // [Note: if the constructor's class contains a member with the
  3546. // same name as a direct or virtual base class of the class, a
  3547. // mem-initializer-id naming the member or base class and composed
  3548. // of a single identifier refers to the class member. A
  3549. // mem-initializer-id for the hidden base class may be specified
  3550. // using a qualified name. ]
  3551. // Look for a member, first.
  3552. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3553. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3554. if (EllipsisLoc.isValid())
  3555. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3556. << MemberOrBase
  3557. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3558. return BuildMemberInitializer(Member, Init, IdLoc);
  3559. }
  3560. // It didn't name a member, so see if it names a class.
  3561. QualType BaseType;
  3562. TypeSourceInfo *TInfo = nullptr;
  3563. if (TemplateTypeTy) {
  3564. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3565. if (BaseType.isNull())
  3566. return true;
  3567. } else if (DS.getTypeSpecType() == TST_decltype) {
  3568. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3569. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3570. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3571. return true;
  3572. } else {
  3573. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3574. LookupParsedName(R, S, &SS);
  3575. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3576. if (!TyD) {
  3577. if (R.isAmbiguous()) return true;
  3578. // We don't want access-control diagnostics here.
  3579. R.suppressDiagnostics();
  3580. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3581. bool NotUnknownSpecialization = false;
  3582. DeclContext *DC = computeDeclContext(SS, false);
  3583. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3584. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3585. if (!NotUnknownSpecialization) {
  3586. // When the scope specifier can refer to a member of an unknown
  3587. // specialization, we take it as a type name.
  3588. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3589. SS.getWithLocInContext(Context),
  3590. *MemberOrBase, IdLoc);
  3591. if (BaseType.isNull())
  3592. return true;
  3593. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3594. DependentNameTypeLoc TL =
  3595. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3596. if (!TL.isNull()) {
  3597. TL.setNameLoc(IdLoc);
  3598. TL.setElaboratedKeywordLoc(SourceLocation());
  3599. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3600. }
  3601. R.clear();
  3602. R.setLookupName(MemberOrBase);
  3603. }
  3604. }
  3605. // If no results were found, try to correct typos.
  3606. TypoCorrection Corr;
  3607. MemInitializerValidatorCCC CCC(ClassDecl);
  3608. if (R.empty() && BaseType.isNull() &&
  3609. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3610. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3611. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3612. // We have found a non-static data member with a similar
  3613. // name to what was typed; complain and initialize that
  3614. // member.
  3615. diagnoseTypo(Corr,
  3616. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3617. << MemberOrBase << true);
  3618. return BuildMemberInitializer(Member, Init, IdLoc);
  3619. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3620. const CXXBaseSpecifier *DirectBaseSpec;
  3621. const CXXBaseSpecifier *VirtualBaseSpec;
  3622. if (FindBaseInitializer(*this, ClassDecl,
  3623. Context.getTypeDeclType(Type),
  3624. DirectBaseSpec, VirtualBaseSpec)) {
  3625. // We have found a direct or virtual base class with a
  3626. // similar name to what was typed; complain and initialize
  3627. // that base class.
  3628. diagnoseTypo(Corr,
  3629. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3630. << MemberOrBase << false,
  3631. PDiag() /*Suppress note, we provide our own.*/);
  3632. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3633. : VirtualBaseSpec;
  3634. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3635. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3636. TyD = Type;
  3637. }
  3638. }
  3639. }
  3640. if (!TyD && BaseType.isNull()) {
  3641. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3642. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3643. return true;
  3644. }
  3645. }
  3646. if (BaseType.isNull()) {
  3647. BaseType = Context.getTypeDeclType(TyD);
  3648. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3649. if (SS.isSet()) {
  3650. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3651. BaseType);
  3652. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3653. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3654. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3655. TL.setElaboratedKeywordLoc(SourceLocation());
  3656. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3657. }
  3658. }
  3659. }
  3660. if (!TInfo)
  3661. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3662. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3663. }
  3664. MemInitResult
  3665. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3666. SourceLocation IdLoc) {
  3667. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3668. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3669. assert((DirectMember || IndirectMember) &&
  3670. "Member must be a FieldDecl or IndirectFieldDecl");
  3671. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3672. return true;
  3673. if (Member->isInvalidDecl())
  3674. return true;
  3675. MultiExprArg Args;
  3676. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3677. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3678. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3679. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3680. } else {
  3681. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3682. Args = Init;
  3683. }
  3684. SourceRange InitRange = Init->getSourceRange();
  3685. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3686. // Can't check initialization for a member of dependent type or when
  3687. // any of the arguments are type-dependent expressions.
  3688. DiscardCleanupsInEvaluationContext();
  3689. } else {
  3690. bool InitList = false;
  3691. if (isa<InitListExpr>(Init)) {
  3692. InitList = true;
  3693. Args = Init;
  3694. }
  3695. // Initialize the member.
  3696. InitializedEntity MemberEntity =
  3697. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3698. : InitializedEntity::InitializeMember(IndirectMember,
  3699. nullptr);
  3700. InitializationKind Kind =
  3701. InitList ? InitializationKind::CreateDirectList(
  3702. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3703. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3704. InitRange.getEnd());
  3705. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3706. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3707. nullptr);
  3708. if (MemberInit.isInvalid())
  3709. return true;
  3710. // C++11 [class.base.init]p7:
  3711. // The initialization of each base and member constitutes a
  3712. // full-expression.
  3713. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3714. /*DiscardedValue*/ false);
  3715. if (MemberInit.isInvalid())
  3716. return true;
  3717. Init = MemberInit.get();
  3718. }
  3719. if (DirectMember) {
  3720. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3721. InitRange.getBegin(), Init,
  3722. InitRange.getEnd());
  3723. } else {
  3724. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3725. InitRange.getBegin(), Init,
  3726. InitRange.getEnd());
  3727. }
  3728. }
  3729. MemInitResult
  3730. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3731. CXXRecordDecl *ClassDecl) {
  3732. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3733. if (!LangOpts.CPlusPlus11)
  3734. return Diag(NameLoc, diag::err_delegating_ctor)
  3735. << TInfo->getTypeLoc().getLocalSourceRange();
  3736. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3737. bool InitList = true;
  3738. MultiExprArg Args = Init;
  3739. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3740. InitList = false;
  3741. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3742. }
  3743. SourceRange InitRange = Init->getSourceRange();
  3744. // Initialize the object.
  3745. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3746. QualType(ClassDecl->getTypeForDecl(), 0));
  3747. InitializationKind Kind =
  3748. InitList ? InitializationKind::CreateDirectList(
  3749. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3750. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3751. InitRange.getEnd());
  3752. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3753. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3754. Args, nullptr);
  3755. if (DelegationInit.isInvalid())
  3756. return true;
  3757. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3758. "Delegating constructor with no target?");
  3759. // C++11 [class.base.init]p7:
  3760. // The initialization of each base and member constitutes a
  3761. // full-expression.
  3762. DelegationInit = ActOnFinishFullExpr(
  3763. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  3764. if (DelegationInit.isInvalid())
  3765. return true;
  3766. // If we are in a dependent context, template instantiation will
  3767. // perform this type-checking again. Just save the arguments that we
  3768. // received in a ParenListExpr.
  3769. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3770. // of the information that we have about the base
  3771. // initializer. However, deconstructing the ASTs is a dicey process,
  3772. // and this approach is far more likely to get the corner cases right.
  3773. if (CurContext->isDependentContext())
  3774. DelegationInit = Init;
  3775. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3776. DelegationInit.getAs<Expr>(),
  3777. InitRange.getEnd());
  3778. }
  3779. MemInitResult
  3780. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3781. Expr *Init, CXXRecordDecl *ClassDecl,
  3782. SourceLocation EllipsisLoc) {
  3783. SourceLocation BaseLoc
  3784. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3785. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3786. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3787. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3788. // C++ [class.base.init]p2:
  3789. // [...] Unless the mem-initializer-id names a nonstatic data
  3790. // member of the constructor's class or a direct or virtual base
  3791. // of that class, the mem-initializer is ill-formed. A
  3792. // mem-initializer-list can initialize a base class using any
  3793. // name that denotes that base class type.
  3794. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3795. SourceRange InitRange = Init->getSourceRange();
  3796. if (EllipsisLoc.isValid()) {
  3797. // This is a pack expansion.
  3798. if (!BaseType->containsUnexpandedParameterPack()) {
  3799. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3800. << SourceRange(BaseLoc, InitRange.getEnd());
  3801. EllipsisLoc = SourceLocation();
  3802. }
  3803. } else {
  3804. // Check for any unexpanded parameter packs.
  3805. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3806. return true;
  3807. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3808. return true;
  3809. }
  3810. // Check for direct and virtual base classes.
  3811. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3812. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3813. if (!Dependent) {
  3814. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3815. BaseType))
  3816. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3817. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3818. VirtualBaseSpec);
  3819. // C++ [base.class.init]p2:
  3820. // Unless the mem-initializer-id names a nonstatic data member of the
  3821. // constructor's class or a direct or virtual base of that class, the
  3822. // mem-initializer is ill-formed.
  3823. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3824. // If the class has any dependent bases, then it's possible that
  3825. // one of those types will resolve to the same type as
  3826. // BaseType. Therefore, just treat this as a dependent base
  3827. // class initialization. FIXME: Should we try to check the
  3828. // initialization anyway? It seems odd.
  3829. if (ClassDecl->hasAnyDependentBases())
  3830. Dependent = true;
  3831. else
  3832. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3833. << BaseType << Context.getTypeDeclType(ClassDecl)
  3834. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3835. }
  3836. }
  3837. if (Dependent) {
  3838. DiscardCleanupsInEvaluationContext();
  3839. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3840. /*IsVirtual=*/false,
  3841. InitRange.getBegin(), Init,
  3842. InitRange.getEnd(), EllipsisLoc);
  3843. }
  3844. // C++ [base.class.init]p2:
  3845. // If a mem-initializer-id is ambiguous because it designates both
  3846. // a direct non-virtual base class and an inherited virtual base
  3847. // class, the mem-initializer is ill-formed.
  3848. if (DirectBaseSpec && VirtualBaseSpec)
  3849. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3850. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3851. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3852. if (!BaseSpec)
  3853. BaseSpec = VirtualBaseSpec;
  3854. // Initialize the base.
  3855. bool InitList = true;
  3856. MultiExprArg Args = Init;
  3857. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3858. InitList = false;
  3859. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3860. }
  3861. InitializedEntity BaseEntity =
  3862. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3863. InitializationKind Kind =
  3864. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3865. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3866. InitRange.getEnd());
  3867. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3868. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3869. if (BaseInit.isInvalid())
  3870. return true;
  3871. // C++11 [class.base.init]p7:
  3872. // The initialization of each base and member constitutes a
  3873. // full-expression.
  3874. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  3875. /*DiscardedValue*/ false);
  3876. if (BaseInit.isInvalid())
  3877. return true;
  3878. // If we are in a dependent context, template instantiation will
  3879. // perform this type-checking again. Just save the arguments that we
  3880. // received in a ParenListExpr.
  3881. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3882. // of the information that we have about the base
  3883. // initializer. However, deconstructing the ASTs is a dicey process,
  3884. // and this approach is far more likely to get the corner cases right.
  3885. if (CurContext->isDependentContext())
  3886. BaseInit = Init;
  3887. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3888. BaseSpec->isVirtual(),
  3889. InitRange.getBegin(),
  3890. BaseInit.getAs<Expr>(),
  3891. InitRange.getEnd(), EllipsisLoc);
  3892. }
  3893. // Create a static_cast\<T&&>(expr).
  3894. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3895. if (T.isNull()) T = E->getType();
  3896. QualType TargetType = SemaRef.BuildReferenceType(
  3897. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3898. SourceLocation ExprLoc = E->getBeginLoc();
  3899. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3900. TargetType, ExprLoc);
  3901. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3902. SourceRange(ExprLoc, ExprLoc),
  3903. E->getSourceRange()).get();
  3904. }
  3905. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3906. /// initialize its base or member.
  3907. enum ImplicitInitializerKind {
  3908. IIK_Default,
  3909. IIK_Copy,
  3910. IIK_Move,
  3911. IIK_Inherit
  3912. };
  3913. static bool
  3914. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3915. ImplicitInitializerKind ImplicitInitKind,
  3916. CXXBaseSpecifier *BaseSpec,
  3917. bool IsInheritedVirtualBase,
  3918. CXXCtorInitializer *&CXXBaseInit) {
  3919. InitializedEntity InitEntity
  3920. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3921. IsInheritedVirtualBase);
  3922. ExprResult BaseInit;
  3923. switch (ImplicitInitKind) {
  3924. case IIK_Inherit:
  3925. case IIK_Default: {
  3926. InitializationKind InitKind
  3927. = InitializationKind::CreateDefault(Constructor->getLocation());
  3928. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3929. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3930. break;
  3931. }
  3932. case IIK_Move:
  3933. case IIK_Copy: {
  3934. bool Moving = ImplicitInitKind == IIK_Move;
  3935. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3936. QualType ParamType = Param->getType().getNonReferenceType();
  3937. Expr *CopyCtorArg =
  3938. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3939. SourceLocation(), Param, false,
  3940. Constructor->getLocation(), ParamType,
  3941. VK_LValue, nullptr);
  3942. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3943. // Cast to the base class to avoid ambiguities.
  3944. QualType ArgTy =
  3945. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3946. ParamType.getQualifiers());
  3947. if (Moving) {
  3948. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3949. }
  3950. CXXCastPath BasePath;
  3951. BasePath.push_back(BaseSpec);
  3952. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3953. CK_UncheckedDerivedToBase,
  3954. Moving ? VK_XValue : VK_LValue,
  3955. &BasePath).get();
  3956. InitializationKind InitKind
  3957. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3958. SourceLocation(), SourceLocation());
  3959. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3960. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3961. break;
  3962. }
  3963. }
  3964. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3965. if (BaseInit.isInvalid())
  3966. return true;
  3967. CXXBaseInit =
  3968. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3969. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3970. SourceLocation()),
  3971. BaseSpec->isVirtual(),
  3972. SourceLocation(),
  3973. BaseInit.getAs<Expr>(),
  3974. SourceLocation(),
  3975. SourceLocation());
  3976. return false;
  3977. }
  3978. static bool RefersToRValueRef(Expr *MemRef) {
  3979. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3980. return Referenced->getType()->isRValueReferenceType();
  3981. }
  3982. static bool
  3983. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3984. ImplicitInitializerKind ImplicitInitKind,
  3985. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3986. CXXCtorInitializer *&CXXMemberInit) {
  3987. if (Field->isInvalidDecl())
  3988. return true;
  3989. SourceLocation Loc = Constructor->getLocation();
  3990. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3991. bool Moving = ImplicitInitKind == IIK_Move;
  3992. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3993. QualType ParamType = Param->getType().getNonReferenceType();
  3994. // Suppress copying zero-width bitfields.
  3995. if (Field->isZeroLengthBitField(SemaRef.Context))
  3996. return false;
  3997. Expr *MemberExprBase =
  3998. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3999. SourceLocation(), Param, false,
  4000. Loc, ParamType, VK_LValue, nullptr);
  4001. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  4002. if (Moving) {
  4003. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  4004. }
  4005. // Build a reference to this field within the parameter.
  4006. CXXScopeSpec SS;
  4007. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  4008. Sema::LookupMemberName);
  4009. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  4010. : cast<ValueDecl>(Field), AS_public);
  4011. MemberLookup.resolveKind();
  4012. ExprResult CtorArg
  4013. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  4014. ParamType, Loc,
  4015. /*IsArrow=*/false,
  4016. SS,
  4017. /*TemplateKWLoc=*/SourceLocation(),
  4018. /*FirstQualifierInScope=*/nullptr,
  4019. MemberLookup,
  4020. /*TemplateArgs=*/nullptr,
  4021. /*S*/nullptr);
  4022. if (CtorArg.isInvalid())
  4023. return true;
  4024. // C++11 [class.copy]p15:
  4025. // - if a member m has rvalue reference type T&&, it is direct-initialized
  4026. // with static_cast<T&&>(x.m);
  4027. if (RefersToRValueRef(CtorArg.get())) {
  4028. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  4029. }
  4030. InitializedEntity Entity =
  4031. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4032. /*Implicit*/ true)
  4033. : InitializedEntity::InitializeMember(Field, nullptr,
  4034. /*Implicit*/ true);
  4035. // Direct-initialize to use the copy constructor.
  4036. InitializationKind InitKind =
  4037. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  4038. Expr *CtorArgE = CtorArg.getAs<Expr>();
  4039. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  4040. ExprResult MemberInit =
  4041. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  4042. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4043. if (MemberInit.isInvalid())
  4044. return true;
  4045. if (Indirect)
  4046. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4047. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4048. else
  4049. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4050. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4051. return false;
  4052. }
  4053. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  4054. "Unhandled implicit init kind!");
  4055. QualType FieldBaseElementType =
  4056. SemaRef.Context.getBaseElementType(Field->getType());
  4057. if (FieldBaseElementType->isRecordType()) {
  4058. InitializedEntity InitEntity =
  4059. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4060. /*Implicit*/ true)
  4061. : InitializedEntity::InitializeMember(Field, nullptr,
  4062. /*Implicit*/ true);
  4063. InitializationKind InitKind =
  4064. InitializationKind::CreateDefault(Loc);
  4065. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  4066. ExprResult MemberInit =
  4067. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  4068. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4069. if (MemberInit.isInvalid())
  4070. return true;
  4071. if (Indirect)
  4072. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4073. Indirect, Loc,
  4074. Loc,
  4075. MemberInit.get(),
  4076. Loc);
  4077. else
  4078. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4079. Field, Loc, Loc,
  4080. MemberInit.get(),
  4081. Loc);
  4082. return false;
  4083. }
  4084. if (!Field->getParent()->isUnion()) {
  4085. if (FieldBaseElementType->isReferenceType()) {
  4086. SemaRef.Diag(Constructor->getLocation(),
  4087. diag::err_uninitialized_member_in_ctor)
  4088. << (int)Constructor->isImplicit()
  4089. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4090. << 0 << Field->getDeclName();
  4091. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4092. return true;
  4093. }
  4094. if (FieldBaseElementType.isConstQualified()) {
  4095. SemaRef.Diag(Constructor->getLocation(),
  4096. diag::err_uninitialized_member_in_ctor)
  4097. << (int)Constructor->isImplicit()
  4098. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4099. << 1 << Field->getDeclName();
  4100. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4101. return true;
  4102. }
  4103. }
  4104. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  4105. // ARC and Weak:
  4106. // Default-initialize Objective-C pointers to NULL.
  4107. CXXMemberInit
  4108. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  4109. Loc, Loc,
  4110. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  4111. Loc);
  4112. return false;
  4113. }
  4114. // Nothing to initialize.
  4115. CXXMemberInit = nullptr;
  4116. return false;
  4117. }
  4118. namespace {
  4119. struct BaseAndFieldInfo {
  4120. Sema &S;
  4121. CXXConstructorDecl *Ctor;
  4122. bool AnyErrorsInInits;
  4123. ImplicitInitializerKind IIK;
  4124. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4125. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4126. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4127. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4128. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4129. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4130. if (Ctor->getInheritedConstructor())
  4131. IIK = IIK_Inherit;
  4132. else if (Generated && Ctor->isCopyConstructor())
  4133. IIK = IIK_Copy;
  4134. else if (Generated && Ctor->isMoveConstructor())
  4135. IIK = IIK_Move;
  4136. else
  4137. IIK = IIK_Default;
  4138. }
  4139. bool isImplicitCopyOrMove() const {
  4140. switch (IIK) {
  4141. case IIK_Copy:
  4142. case IIK_Move:
  4143. return true;
  4144. case IIK_Default:
  4145. case IIK_Inherit:
  4146. return false;
  4147. }
  4148. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4149. }
  4150. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4151. AllToInit.push_back(Init);
  4152. // Check whether this initializer makes the field "used".
  4153. if (Init->getInit()->HasSideEffects(S.Context))
  4154. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4155. return false;
  4156. }
  4157. bool isInactiveUnionMember(FieldDecl *Field) {
  4158. RecordDecl *Record = Field->getParent();
  4159. if (!Record->isUnion())
  4160. return false;
  4161. if (FieldDecl *Active =
  4162. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4163. return Active != Field->getCanonicalDecl();
  4164. // In an implicit copy or move constructor, ignore any in-class initializer.
  4165. if (isImplicitCopyOrMove())
  4166. return true;
  4167. // If there's no explicit initialization, the field is active only if it
  4168. // has an in-class initializer...
  4169. if (Field->hasInClassInitializer())
  4170. return false;
  4171. // ... or it's an anonymous struct or union whose class has an in-class
  4172. // initializer.
  4173. if (!Field->isAnonymousStructOrUnion())
  4174. return true;
  4175. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4176. return !FieldRD->hasInClassInitializer();
  4177. }
  4178. /// Determine whether the given field is, or is within, a union member
  4179. /// that is inactive (because there was an initializer given for a different
  4180. /// member of the union, or because the union was not initialized at all).
  4181. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4182. IndirectFieldDecl *Indirect) {
  4183. if (!Indirect)
  4184. return isInactiveUnionMember(Field);
  4185. for (auto *C : Indirect->chain()) {
  4186. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4187. if (Field && isInactiveUnionMember(Field))
  4188. return true;
  4189. }
  4190. return false;
  4191. }
  4192. };
  4193. }
  4194. /// Determine whether the given type is an incomplete or zero-lenfgth
  4195. /// array type.
  4196. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4197. if (T->isIncompleteArrayType())
  4198. return true;
  4199. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4200. if (!ArrayT->getSize())
  4201. return true;
  4202. T = ArrayT->getElementType();
  4203. }
  4204. return false;
  4205. }
  4206. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4207. FieldDecl *Field,
  4208. IndirectFieldDecl *Indirect = nullptr) {
  4209. if (Field->isInvalidDecl())
  4210. return false;
  4211. // Overwhelmingly common case: we have a direct initializer for this field.
  4212. if (CXXCtorInitializer *Init =
  4213. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4214. return Info.addFieldInitializer(Init);
  4215. // C++11 [class.base.init]p8:
  4216. // if the entity is a non-static data member that has a
  4217. // brace-or-equal-initializer and either
  4218. // -- the constructor's class is a union and no other variant member of that
  4219. // union is designated by a mem-initializer-id or
  4220. // -- the constructor's class is not a union, and, if the entity is a member
  4221. // of an anonymous union, no other member of that union is designated by
  4222. // a mem-initializer-id,
  4223. // the entity is initialized as specified in [dcl.init].
  4224. //
  4225. // We also apply the same rules to handle anonymous structs within anonymous
  4226. // unions.
  4227. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4228. return false;
  4229. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4230. ExprResult DIE =
  4231. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4232. if (DIE.isInvalid())
  4233. return true;
  4234. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4235. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4236. CXXCtorInitializer *Init;
  4237. if (Indirect)
  4238. Init = new (SemaRef.Context)
  4239. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4240. SourceLocation(), DIE.get(), SourceLocation());
  4241. else
  4242. Init = new (SemaRef.Context)
  4243. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4244. SourceLocation(), DIE.get(), SourceLocation());
  4245. return Info.addFieldInitializer(Init);
  4246. }
  4247. // Don't initialize incomplete or zero-length arrays.
  4248. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4249. return false;
  4250. // Don't try to build an implicit initializer if there were semantic
  4251. // errors in any of the initializers (and therefore we might be
  4252. // missing some that the user actually wrote).
  4253. if (Info.AnyErrorsInInits)
  4254. return false;
  4255. CXXCtorInitializer *Init = nullptr;
  4256. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4257. Indirect, Init))
  4258. return true;
  4259. if (!Init)
  4260. return false;
  4261. return Info.addFieldInitializer(Init);
  4262. }
  4263. bool
  4264. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4265. CXXCtorInitializer *Initializer) {
  4266. assert(Initializer->isDelegatingInitializer());
  4267. Constructor->setNumCtorInitializers(1);
  4268. CXXCtorInitializer **initializer =
  4269. new (Context) CXXCtorInitializer*[1];
  4270. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4271. Constructor->setCtorInitializers(initializer);
  4272. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4273. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4274. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4275. }
  4276. DelegatingCtorDecls.push_back(Constructor);
  4277. DiagnoseUninitializedFields(*this, Constructor);
  4278. return false;
  4279. }
  4280. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4281. ArrayRef<CXXCtorInitializer *> Initializers) {
  4282. if (Constructor->isDependentContext()) {
  4283. // Just store the initializers as written, they will be checked during
  4284. // instantiation.
  4285. if (!Initializers.empty()) {
  4286. Constructor->setNumCtorInitializers(Initializers.size());
  4287. CXXCtorInitializer **baseOrMemberInitializers =
  4288. new (Context) CXXCtorInitializer*[Initializers.size()];
  4289. memcpy(baseOrMemberInitializers, Initializers.data(),
  4290. Initializers.size() * sizeof(CXXCtorInitializer*));
  4291. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4292. }
  4293. // Let template instantiation know whether we had errors.
  4294. if (AnyErrors)
  4295. Constructor->setInvalidDecl();
  4296. return false;
  4297. }
  4298. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4299. // We need to build the initializer AST according to order of construction
  4300. // and not what user specified in the Initializers list.
  4301. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4302. if (!ClassDecl)
  4303. return true;
  4304. bool HadError = false;
  4305. for (unsigned i = 0; i < Initializers.size(); i++) {
  4306. CXXCtorInitializer *Member = Initializers[i];
  4307. if (Member->isBaseInitializer())
  4308. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4309. else {
  4310. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4311. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4312. for (auto *C : F->chain()) {
  4313. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4314. if (FD && FD->getParent()->isUnion())
  4315. Info.ActiveUnionMember.insert(std::make_pair(
  4316. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4317. }
  4318. } else if (FieldDecl *FD = Member->getMember()) {
  4319. if (FD->getParent()->isUnion())
  4320. Info.ActiveUnionMember.insert(std::make_pair(
  4321. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4322. }
  4323. }
  4324. }
  4325. // Keep track of the direct virtual bases.
  4326. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4327. for (auto &I : ClassDecl->bases()) {
  4328. if (I.isVirtual())
  4329. DirectVBases.insert(&I);
  4330. }
  4331. // Push virtual bases before others.
  4332. for (auto &VBase : ClassDecl->vbases()) {
  4333. if (CXXCtorInitializer *Value
  4334. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4335. // [class.base.init]p7, per DR257:
  4336. // A mem-initializer where the mem-initializer-id names a virtual base
  4337. // class is ignored during execution of a constructor of any class that
  4338. // is not the most derived class.
  4339. if (ClassDecl->isAbstract()) {
  4340. // FIXME: Provide a fixit to remove the base specifier. This requires
  4341. // tracking the location of the associated comma for a base specifier.
  4342. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4343. << VBase.getType() << ClassDecl;
  4344. DiagnoseAbstractType(ClassDecl);
  4345. }
  4346. Info.AllToInit.push_back(Value);
  4347. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4348. // [class.base.init]p8, per DR257:
  4349. // If a given [...] base class is not named by a mem-initializer-id
  4350. // [...] and the entity is not a virtual base class of an abstract
  4351. // class, then [...] the entity is default-initialized.
  4352. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4353. CXXCtorInitializer *CXXBaseInit;
  4354. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4355. &VBase, IsInheritedVirtualBase,
  4356. CXXBaseInit)) {
  4357. HadError = true;
  4358. continue;
  4359. }
  4360. Info.AllToInit.push_back(CXXBaseInit);
  4361. }
  4362. }
  4363. // Non-virtual bases.
  4364. for (auto &Base : ClassDecl->bases()) {
  4365. // Virtuals are in the virtual base list and already constructed.
  4366. if (Base.isVirtual())
  4367. continue;
  4368. if (CXXCtorInitializer *Value
  4369. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4370. Info.AllToInit.push_back(Value);
  4371. } else if (!AnyErrors) {
  4372. CXXCtorInitializer *CXXBaseInit;
  4373. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4374. &Base, /*IsInheritedVirtualBase=*/false,
  4375. CXXBaseInit)) {
  4376. HadError = true;
  4377. continue;
  4378. }
  4379. Info.AllToInit.push_back(CXXBaseInit);
  4380. }
  4381. }
  4382. // Fields.
  4383. for (auto *Mem : ClassDecl->decls()) {
  4384. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4385. // C++ [class.bit]p2:
  4386. // A declaration for a bit-field that omits the identifier declares an
  4387. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4388. // initialized.
  4389. if (F->isUnnamedBitfield())
  4390. continue;
  4391. // If we're not generating the implicit copy/move constructor, then we'll
  4392. // handle anonymous struct/union fields based on their individual
  4393. // indirect fields.
  4394. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4395. continue;
  4396. if (CollectFieldInitializer(*this, Info, F))
  4397. HadError = true;
  4398. continue;
  4399. }
  4400. // Beyond this point, we only consider default initialization.
  4401. if (Info.isImplicitCopyOrMove())
  4402. continue;
  4403. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4404. if (F->getType()->isIncompleteArrayType()) {
  4405. assert(ClassDecl->hasFlexibleArrayMember() &&
  4406. "Incomplete array type is not valid");
  4407. continue;
  4408. }
  4409. // Initialize each field of an anonymous struct individually.
  4410. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4411. HadError = true;
  4412. continue;
  4413. }
  4414. }
  4415. unsigned NumInitializers = Info.AllToInit.size();
  4416. if (NumInitializers > 0) {
  4417. Constructor->setNumCtorInitializers(NumInitializers);
  4418. CXXCtorInitializer **baseOrMemberInitializers =
  4419. new (Context) CXXCtorInitializer*[NumInitializers];
  4420. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4421. NumInitializers * sizeof(CXXCtorInitializer*));
  4422. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4423. // Constructors implicitly reference the base and member
  4424. // destructors.
  4425. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4426. Constructor->getParent());
  4427. }
  4428. return HadError;
  4429. }
  4430. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4431. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4432. const RecordDecl *RD = RT->getDecl();
  4433. if (RD->isAnonymousStructOrUnion()) {
  4434. for (auto *Field : RD->fields())
  4435. PopulateKeysForFields(Field, IdealInits);
  4436. return;
  4437. }
  4438. }
  4439. IdealInits.push_back(Field->getCanonicalDecl());
  4440. }
  4441. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4442. return Context.getCanonicalType(BaseType).getTypePtr();
  4443. }
  4444. static const void *GetKeyForMember(ASTContext &Context,
  4445. CXXCtorInitializer *Member) {
  4446. if (!Member->isAnyMemberInitializer())
  4447. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4448. return Member->getAnyMember()->getCanonicalDecl();
  4449. }
  4450. static void DiagnoseBaseOrMemInitializerOrder(
  4451. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4452. ArrayRef<CXXCtorInitializer *> Inits) {
  4453. if (Constructor->getDeclContext()->isDependentContext())
  4454. return;
  4455. // Don't check initializers order unless the warning is enabled at the
  4456. // location of at least one initializer.
  4457. bool ShouldCheckOrder = false;
  4458. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4459. CXXCtorInitializer *Init = Inits[InitIndex];
  4460. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4461. Init->getSourceLocation())) {
  4462. ShouldCheckOrder = true;
  4463. break;
  4464. }
  4465. }
  4466. if (!ShouldCheckOrder)
  4467. return;
  4468. // Build the list of bases and members in the order that they'll
  4469. // actually be initialized. The explicit initializers should be in
  4470. // this same order but may be missing things.
  4471. SmallVector<const void*, 32> IdealInitKeys;
  4472. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4473. // 1. Virtual bases.
  4474. for (const auto &VBase : ClassDecl->vbases())
  4475. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4476. // 2. Non-virtual bases.
  4477. for (const auto &Base : ClassDecl->bases()) {
  4478. if (Base.isVirtual())
  4479. continue;
  4480. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4481. }
  4482. // 3. Direct fields.
  4483. for (auto *Field : ClassDecl->fields()) {
  4484. if (Field->isUnnamedBitfield())
  4485. continue;
  4486. PopulateKeysForFields(Field, IdealInitKeys);
  4487. }
  4488. unsigned NumIdealInits = IdealInitKeys.size();
  4489. unsigned IdealIndex = 0;
  4490. CXXCtorInitializer *PrevInit = nullptr;
  4491. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4492. CXXCtorInitializer *Init = Inits[InitIndex];
  4493. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4494. // Scan forward to try to find this initializer in the idealized
  4495. // initializers list.
  4496. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4497. if (InitKey == IdealInitKeys[IdealIndex])
  4498. break;
  4499. // If we didn't find this initializer, it must be because we
  4500. // scanned past it on a previous iteration. That can only
  4501. // happen if we're out of order; emit a warning.
  4502. if (IdealIndex == NumIdealInits && PrevInit) {
  4503. Sema::SemaDiagnosticBuilder D =
  4504. SemaRef.Diag(PrevInit->getSourceLocation(),
  4505. diag::warn_initializer_out_of_order);
  4506. if (PrevInit->isAnyMemberInitializer())
  4507. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4508. else
  4509. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4510. if (Init->isAnyMemberInitializer())
  4511. D << 0 << Init->getAnyMember()->getDeclName();
  4512. else
  4513. D << 1 << Init->getTypeSourceInfo()->getType();
  4514. // Move back to the initializer's location in the ideal list.
  4515. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4516. if (InitKey == IdealInitKeys[IdealIndex])
  4517. break;
  4518. assert(IdealIndex < NumIdealInits &&
  4519. "initializer not found in initializer list");
  4520. }
  4521. PrevInit = Init;
  4522. }
  4523. }
  4524. namespace {
  4525. bool CheckRedundantInit(Sema &S,
  4526. CXXCtorInitializer *Init,
  4527. CXXCtorInitializer *&PrevInit) {
  4528. if (!PrevInit) {
  4529. PrevInit = Init;
  4530. return false;
  4531. }
  4532. if (FieldDecl *Field = Init->getAnyMember())
  4533. S.Diag(Init->getSourceLocation(),
  4534. diag::err_multiple_mem_initialization)
  4535. << Field->getDeclName()
  4536. << Init->getSourceRange();
  4537. else {
  4538. const Type *BaseClass = Init->getBaseClass();
  4539. assert(BaseClass && "neither field nor base");
  4540. S.Diag(Init->getSourceLocation(),
  4541. diag::err_multiple_base_initialization)
  4542. << QualType(BaseClass, 0)
  4543. << Init->getSourceRange();
  4544. }
  4545. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4546. << 0 << PrevInit->getSourceRange();
  4547. return true;
  4548. }
  4549. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4550. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4551. bool CheckRedundantUnionInit(Sema &S,
  4552. CXXCtorInitializer *Init,
  4553. RedundantUnionMap &Unions) {
  4554. FieldDecl *Field = Init->getAnyMember();
  4555. RecordDecl *Parent = Field->getParent();
  4556. NamedDecl *Child = Field;
  4557. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4558. if (Parent->isUnion()) {
  4559. UnionEntry &En = Unions[Parent];
  4560. if (En.first && En.first != Child) {
  4561. S.Diag(Init->getSourceLocation(),
  4562. diag::err_multiple_mem_union_initialization)
  4563. << Field->getDeclName()
  4564. << Init->getSourceRange();
  4565. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4566. << 0 << En.second->getSourceRange();
  4567. return true;
  4568. }
  4569. if (!En.first) {
  4570. En.first = Child;
  4571. En.second = Init;
  4572. }
  4573. if (!Parent->isAnonymousStructOrUnion())
  4574. return false;
  4575. }
  4576. Child = Parent;
  4577. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4578. }
  4579. return false;
  4580. }
  4581. }
  4582. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4583. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4584. SourceLocation ColonLoc,
  4585. ArrayRef<CXXCtorInitializer*> MemInits,
  4586. bool AnyErrors) {
  4587. if (!ConstructorDecl)
  4588. return;
  4589. AdjustDeclIfTemplate(ConstructorDecl);
  4590. CXXConstructorDecl *Constructor
  4591. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4592. if (!Constructor) {
  4593. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4594. return;
  4595. }
  4596. // Mapping for the duplicate initializers check.
  4597. // For member initializers, this is keyed with a FieldDecl*.
  4598. // For base initializers, this is keyed with a Type*.
  4599. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4600. // Mapping for the inconsistent anonymous-union initializers check.
  4601. RedundantUnionMap MemberUnions;
  4602. bool HadError = false;
  4603. for (unsigned i = 0; i < MemInits.size(); i++) {
  4604. CXXCtorInitializer *Init = MemInits[i];
  4605. // Set the source order index.
  4606. Init->setSourceOrder(i);
  4607. if (Init->isAnyMemberInitializer()) {
  4608. const void *Key = GetKeyForMember(Context, Init);
  4609. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4610. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4611. HadError = true;
  4612. } else if (Init->isBaseInitializer()) {
  4613. const void *Key = GetKeyForMember(Context, Init);
  4614. if (CheckRedundantInit(*this, Init, Members[Key]))
  4615. HadError = true;
  4616. } else {
  4617. assert(Init->isDelegatingInitializer());
  4618. // This must be the only initializer
  4619. if (MemInits.size() != 1) {
  4620. Diag(Init->getSourceLocation(),
  4621. diag::err_delegating_initializer_alone)
  4622. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4623. // We will treat this as being the only initializer.
  4624. }
  4625. SetDelegatingInitializer(Constructor, MemInits[i]);
  4626. // Return immediately as the initializer is set.
  4627. return;
  4628. }
  4629. }
  4630. if (HadError)
  4631. return;
  4632. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4633. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4634. DiagnoseUninitializedFields(*this, Constructor);
  4635. }
  4636. void
  4637. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4638. CXXRecordDecl *ClassDecl) {
  4639. // Ignore dependent contexts. Also ignore unions, since their members never
  4640. // have destructors implicitly called.
  4641. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4642. return;
  4643. // FIXME: all the access-control diagnostics are positioned on the
  4644. // field/base declaration. That's probably good; that said, the
  4645. // user might reasonably want to know why the destructor is being
  4646. // emitted, and we currently don't say.
  4647. // Non-static data members.
  4648. for (auto *Field : ClassDecl->fields()) {
  4649. if (Field->isInvalidDecl())
  4650. continue;
  4651. // Don't destroy incomplete or zero-length arrays.
  4652. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4653. continue;
  4654. QualType FieldType = Context.getBaseElementType(Field->getType());
  4655. const RecordType* RT = FieldType->getAs<RecordType>();
  4656. if (!RT)
  4657. continue;
  4658. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4659. if (FieldClassDecl->isInvalidDecl())
  4660. continue;
  4661. if (FieldClassDecl->hasIrrelevantDestructor())
  4662. continue;
  4663. // The destructor for an implicit anonymous union member is never invoked.
  4664. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4665. continue;
  4666. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4667. assert(Dtor && "No dtor found for FieldClassDecl!");
  4668. CheckDestructorAccess(Field->getLocation(), Dtor,
  4669. PDiag(diag::err_access_dtor_field)
  4670. << Field->getDeclName()
  4671. << FieldType);
  4672. MarkFunctionReferenced(Location, Dtor);
  4673. DiagnoseUseOfDecl(Dtor, Location);
  4674. }
  4675. // We only potentially invoke the destructors of potentially constructed
  4676. // subobjects.
  4677. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4678. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4679. // Bases.
  4680. for (const auto &Base : ClassDecl->bases()) {
  4681. // Bases are always records in a well-formed non-dependent class.
  4682. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4683. // Remember direct virtual bases.
  4684. if (Base.isVirtual()) {
  4685. if (!VisitVirtualBases)
  4686. continue;
  4687. DirectVirtualBases.insert(RT);
  4688. }
  4689. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4690. // If our base class is invalid, we probably can't get its dtor anyway.
  4691. if (BaseClassDecl->isInvalidDecl())
  4692. continue;
  4693. if (BaseClassDecl->hasIrrelevantDestructor())
  4694. continue;
  4695. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4696. assert(Dtor && "No dtor found for BaseClassDecl!");
  4697. // FIXME: caret should be on the start of the class name
  4698. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4699. PDiag(diag::err_access_dtor_base)
  4700. << Base.getType() << Base.getSourceRange(),
  4701. Context.getTypeDeclType(ClassDecl));
  4702. MarkFunctionReferenced(Location, Dtor);
  4703. DiagnoseUseOfDecl(Dtor, Location);
  4704. }
  4705. if (!VisitVirtualBases)
  4706. return;
  4707. // Virtual bases.
  4708. for (const auto &VBase : ClassDecl->vbases()) {
  4709. // Bases are always records in a well-formed non-dependent class.
  4710. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4711. // Ignore direct virtual bases.
  4712. if (DirectVirtualBases.count(RT))
  4713. continue;
  4714. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4715. // If our base class is invalid, we probably can't get its dtor anyway.
  4716. if (BaseClassDecl->isInvalidDecl())
  4717. continue;
  4718. if (BaseClassDecl->hasIrrelevantDestructor())
  4719. continue;
  4720. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4721. assert(Dtor && "No dtor found for BaseClassDecl!");
  4722. if (CheckDestructorAccess(
  4723. ClassDecl->getLocation(), Dtor,
  4724. PDiag(diag::err_access_dtor_vbase)
  4725. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4726. Context.getTypeDeclType(ClassDecl)) ==
  4727. AR_accessible) {
  4728. CheckDerivedToBaseConversion(
  4729. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4730. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4731. SourceRange(), DeclarationName(), nullptr);
  4732. }
  4733. MarkFunctionReferenced(Location, Dtor);
  4734. DiagnoseUseOfDecl(Dtor, Location);
  4735. }
  4736. }
  4737. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4738. if (!CDtorDecl)
  4739. return;
  4740. if (CXXConstructorDecl *Constructor
  4741. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4742. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4743. DiagnoseUninitializedFields(*this, Constructor);
  4744. }
  4745. }
  4746. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4747. if (!getLangOpts().CPlusPlus)
  4748. return false;
  4749. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4750. if (!RD)
  4751. return false;
  4752. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4753. // class template specialization here, but doing so breaks a lot of code.
  4754. // We can't answer whether something is abstract until it has a
  4755. // definition. If it's currently being defined, we'll walk back
  4756. // over all the declarations when we have a full definition.
  4757. const CXXRecordDecl *Def = RD->getDefinition();
  4758. if (!Def || Def->isBeingDefined())
  4759. return false;
  4760. return RD->isAbstract();
  4761. }
  4762. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4763. TypeDiagnoser &Diagnoser) {
  4764. if (!isAbstractType(Loc, T))
  4765. return false;
  4766. T = Context.getBaseElementType(T);
  4767. Diagnoser.diagnose(*this, Loc, T);
  4768. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4769. return true;
  4770. }
  4771. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4772. // Check if we've already emitted the list of pure virtual functions
  4773. // for this class.
  4774. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4775. return;
  4776. // If the diagnostic is suppressed, don't emit the notes. We're only
  4777. // going to emit them once, so try to attach them to a diagnostic we're
  4778. // actually going to show.
  4779. if (Diags.isLastDiagnosticIgnored())
  4780. return;
  4781. CXXFinalOverriderMap FinalOverriders;
  4782. RD->getFinalOverriders(FinalOverriders);
  4783. // Keep a set of seen pure methods so we won't diagnose the same method
  4784. // more than once.
  4785. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4786. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4787. MEnd = FinalOverriders.end();
  4788. M != MEnd;
  4789. ++M) {
  4790. for (OverridingMethods::iterator SO = M->second.begin(),
  4791. SOEnd = M->second.end();
  4792. SO != SOEnd; ++SO) {
  4793. // C++ [class.abstract]p4:
  4794. // A class is abstract if it contains or inherits at least one
  4795. // pure virtual function for which the final overrider is pure
  4796. // virtual.
  4797. //
  4798. if (SO->second.size() != 1)
  4799. continue;
  4800. if (!SO->second.front().Method->isPure())
  4801. continue;
  4802. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4803. continue;
  4804. Diag(SO->second.front().Method->getLocation(),
  4805. diag::note_pure_virtual_function)
  4806. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4807. }
  4808. }
  4809. if (!PureVirtualClassDiagSet)
  4810. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4811. PureVirtualClassDiagSet->insert(RD);
  4812. }
  4813. namespace {
  4814. struct AbstractUsageInfo {
  4815. Sema &S;
  4816. CXXRecordDecl *Record;
  4817. CanQualType AbstractType;
  4818. bool Invalid;
  4819. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4820. : S(S), Record(Record),
  4821. AbstractType(S.Context.getCanonicalType(
  4822. S.Context.getTypeDeclType(Record))),
  4823. Invalid(false) {}
  4824. void DiagnoseAbstractType() {
  4825. if (Invalid) return;
  4826. S.DiagnoseAbstractType(Record);
  4827. Invalid = true;
  4828. }
  4829. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4830. };
  4831. struct CheckAbstractUsage {
  4832. AbstractUsageInfo &Info;
  4833. const NamedDecl *Ctx;
  4834. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4835. : Info(Info), Ctx(Ctx) {}
  4836. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4837. switch (TL.getTypeLocClass()) {
  4838. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4839. #define TYPELOC(CLASS, PARENT) \
  4840. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4841. #include "clang/AST/TypeLocNodes.def"
  4842. }
  4843. }
  4844. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4845. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4846. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4847. if (!TL.getParam(I))
  4848. continue;
  4849. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4850. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4851. }
  4852. }
  4853. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4854. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4855. }
  4856. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4857. // Visit the type parameters from a permissive context.
  4858. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4859. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4860. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4861. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4862. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4863. // TODO: other template argument types?
  4864. }
  4865. }
  4866. // Visit pointee types from a permissive context.
  4867. #define CheckPolymorphic(Type) \
  4868. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4869. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4870. }
  4871. CheckPolymorphic(PointerTypeLoc)
  4872. CheckPolymorphic(ReferenceTypeLoc)
  4873. CheckPolymorphic(MemberPointerTypeLoc)
  4874. CheckPolymorphic(BlockPointerTypeLoc)
  4875. CheckPolymorphic(AtomicTypeLoc)
  4876. /// Handle all the types we haven't given a more specific
  4877. /// implementation for above.
  4878. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4879. // Every other kind of type that we haven't called out already
  4880. // that has an inner type is either (1) sugar or (2) contains that
  4881. // inner type in some way as a subobject.
  4882. if (TypeLoc Next = TL.getNextTypeLoc())
  4883. return Visit(Next, Sel);
  4884. // If there's no inner type and we're in a permissive context,
  4885. // don't diagnose.
  4886. if (Sel == Sema::AbstractNone) return;
  4887. // Check whether the type matches the abstract type.
  4888. QualType T = TL.getType();
  4889. if (T->isArrayType()) {
  4890. Sel = Sema::AbstractArrayType;
  4891. T = Info.S.Context.getBaseElementType(T);
  4892. }
  4893. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4894. if (CT != Info.AbstractType) return;
  4895. // It matched; do some magic.
  4896. if (Sel == Sema::AbstractArrayType) {
  4897. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4898. << T << TL.getSourceRange();
  4899. } else {
  4900. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4901. << Sel << T << TL.getSourceRange();
  4902. }
  4903. Info.DiagnoseAbstractType();
  4904. }
  4905. };
  4906. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4907. Sema::AbstractDiagSelID Sel) {
  4908. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4909. }
  4910. }
  4911. /// Check for invalid uses of an abstract type in a method declaration.
  4912. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4913. CXXMethodDecl *MD) {
  4914. // No need to do the check on definitions, which require that
  4915. // the return/param types be complete.
  4916. if (MD->doesThisDeclarationHaveABody())
  4917. return;
  4918. // For safety's sake, just ignore it if we don't have type source
  4919. // information. This should never happen for non-implicit methods,
  4920. // but...
  4921. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4922. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4923. }
  4924. /// Check for invalid uses of an abstract type within a class definition.
  4925. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4926. CXXRecordDecl *RD) {
  4927. for (auto *D : RD->decls()) {
  4928. if (D->isImplicit()) continue;
  4929. // Methods and method templates.
  4930. if (isa<CXXMethodDecl>(D)) {
  4931. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4932. } else if (isa<FunctionTemplateDecl>(D)) {
  4933. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4934. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4935. // Fields and static variables.
  4936. } else if (isa<FieldDecl>(D)) {
  4937. FieldDecl *FD = cast<FieldDecl>(D);
  4938. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4939. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4940. } else if (isa<VarDecl>(D)) {
  4941. VarDecl *VD = cast<VarDecl>(D);
  4942. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4943. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4944. // Nested classes and class templates.
  4945. } else if (isa<CXXRecordDecl>(D)) {
  4946. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4947. } else if (isa<ClassTemplateDecl>(D)) {
  4948. CheckAbstractClassUsage(Info,
  4949. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4950. }
  4951. }
  4952. }
  4953. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  4954. Attr *ClassAttr = getDLLAttr(Class);
  4955. if (!ClassAttr)
  4956. return;
  4957. assert(ClassAttr->getKind() == attr::DLLExport);
  4958. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4959. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4960. // Don't go any further if this is just an explicit instantiation
  4961. // declaration.
  4962. return;
  4963. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  4964. S.MarkVTableUsed(Class->getLocation(), Class, true);
  4965. for (Decl *Member : Class->decls()) {
  4966. // Defined static variables that are members of an exported base
  4967. // class must be marked export too.
  4968. auto *VD = dyn_cast<VarDecl>(Member);
  4969. if (VD && Member->getAttr<DLLExportAttr>() &&
  4970. VD->getStorageClass() == SC_Static &&
  4971. TSK == TSK_ImplicitInstantiation)
  4972. S.MarkVariableReferenced(VD->getLocation(), VD);
  4973. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  4974. if (!MD)
  4975. continue;
  4976. if (Member->getAttr<DLLExportAttr>()) {
  4977. if (MD->isUserProvided()) {
  4978. // Instantiate non-default class member functions ...
  4979. // .. except for certain kinds of template specializations.
  4980. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4981. continue;
  4982. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4983. // The function will be passed to the consumer when its definition is
  4984. // encountered.
  4985. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4986. MD->isCopyAssignmentOperator() ||
  4987. MD->isMoveAssignmentOperator()) {
  4988. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4989. // defaulted methods, and the copy and move assignment operators. The
  4990. // latter are exported even if they are trivial, because the address of
  4991. // an operator can be taken and should compare equal across libraries.
  4992. DiagnosticErrorTrap Trap(S.Diags);
  4993. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4994. if (Trap.hasErrorOccurred()) {
  4995. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4996. << Class << !S.getLangOpts().CPlusPlus11;
  4997. break;
  4998. }
  4999. // There is no later point when we will see the definition of this
  5000. // function, so pass it to the consumer now.
  5001. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5002. }
  5003. }
  5004. }
  5005. }
  5006. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  5007. CXXRecordDecl *Class) {
  5008. // Only the MS ABI has default constructor closures, so we don't need to do
  5009. // this semantic checking anywhere else.
  5010. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  5011. return;
  5012. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  5013. for (Decl *Member : Class->decls()) {
  5014. // Look for exported default constructors.
  5015. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  5016. if (!CD || !CD->isDefaultConstructor())
  5017. continue;
  5018. auto *Attr = CD->getAttr<DLLExportAttr>();
  5019. if (!Attr)
  5020. continue;
  5021. // If the class is non-dependent, mark the default arguments as ODR-used so
  5022. // that we can properly codegen the constructor closure.
  5023. if (!Class->isDependentContext()) {
  5024. for (ParmVarDecl *PD : CD->parameters()) {
  5025. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  5026. S.DiscardCleanupsInEvaluationContext();
  5027. }
  5028. }
  5029. if (LastExportedDefaultCtor) {
  5030. S.Diag(LastExportedDefaultCtor->getLocation(),
  5031. diag::err_attribute_dll_ambiguous_default_ctor)
  5032. << Class;
  5033. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  5034. << CD->getDeclName();
  5035. return;
  5036. }
  5037. LastExportedDefaultCtor = CD;
  5038. }
  5039. }
  5040. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  5041. // Mark any compiler-generated routines with the implicit code_seg attribute.
  5042. for (auto *Method : Class->methods()) {
  5043. if (Method->isUserProvided())
  5044. continue;
  5045. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  5046. Method->addAttr(A);
  5047. }
  5048. }
  5049. /// Check class-level dllimport/dllexport attribute.
  5050. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  5051. Attr *ClassAttr = getDLLAttr(Class);
  5052. // MSVC inherits DLL attributes to partial class template specializations.
  5053. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  5054. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  5055. if (Attr *TemplateAttr =
  5056. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  5057. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  5058. A->setInherited(true);
  5059. ClassAttr = A;
  5060. }
  5061. }
  5062. }
  5063. if (!ClassAttr)
  5064. return;
  5065. if (!Class->isExternallyVisible()) {
  5066. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  5067. << Class << ClassAttr;
  5068. return;
  5069. }
  5070. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5071. !ClassAttr->isInherited()) {
  5072. // Diagnose dll attributes on members of class with dll attribute.
  5073. for (Decl *Member : Class->decls()) {
  5074. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  5075. continue;
  5076. InheritableAttr *MemberAttr = getDLLAttr(Member);
  5077. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  5078. continue;
  5079. Diag(MemberAttr->getLocation(),
  5080. diag::err_attribute_dll_member_of_dll_class)
  5081. << MemberAttr << ClassAttr;
  5082. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  5083. Member->setInvalidDecl();
  5084. }
  5085. }
  5086. if (Class->getDescribedClassTemplate())
  5087. // Don't inherit dll attribute until the template is instantiated.
  5088. return;
  5089. // The class is either imported or exported.
  5090. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  5091. // Check if this was a dllimport attribute propagated from a derived class to
  5092. // a base class template specialization. We don't apply these attributes to
  5093. // static data members.
  5094. const bool PropagatedImport =
  5095. !ClassExported &&
  5096. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  5097. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5098. // Ignore explicit dllexport on explicit class template instantiation
  5099. // declarations, except in MinGW mode.
  5100. if (ClassExported && !ClassAttr->isInherited() &&
  5101. TSK == TSK_ExplicitInstantiationDeclaration &&
  5102. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  5103. Class->dropAttr<DLLExportAttr>();
  5104. return;
  5105. }
  5106. // Force declaration of implicit members so they can inherit the attribute.
  5107. ForceDeclarationOfImplicitMembers(Class);
  5108. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  5109. // seem to be true in practice?
  5110. for (Decl *Member : Class->decls()) {
  5111. VarDecl *VD = dyn_cast<VarDecl>(Member);
  5112. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5113. // Only methods and static fields inherit the attributes.
  5114. if (!VD && !MD)
  5115. continue;
  5116. if (MD) {
  5117. // Don't process deleted methods.
  5118. if (MD->isDeleted())
  5119. continue;
  5120. if (MD->isInlined()) {
  5121. // MinGW does not import or export inline methods. But do it for
  5122. // template instantiations.
  5123. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5124. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
  5125. TSK != TSK_ExplicitInstantiationDeclaration &&
  5126. TSK != TSK_ExplicitInstantiationDefinition)
  5127. continue;
  5128. // MSVC versions before 2015 don't export the move assignment operators
  5129. // and move constructor, so don't attempt to import/export them if
  5130. // we have a definition.
  5131. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5132. if ((MD->isMoveAssignmentOperator() ||
  5133. (Ctor && Ctor->isMoveConstructor())) &&
  5134. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5135. continue;
  5136. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5137. // operator is exported anyway.
  5138. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5139. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5140. continue;
  5141. }
  5142. }
  5143. // Don't apply dllimport attributes to static data members of class template
  5144. // instantiations when the attribute is propagated from a derived class.
  5145. if (VD && PropagatedImport)
  5146. continue;
  5147. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5148. continue;
  5149. if (!getDLLAttr(Member)) {
  5150. InheritableAttr *NewAttr = nullptr;
  5151. // Do not export/import inline function when -fno-dllexport-inlines is
  5152. // passed. But add attribute for later local static var check.
  5153. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5154. TSK != TSK_ExplicitInstantiationDeclaration &&
  5155. TSK != TSK_ExplicitInstantiationDefinition) {
  5156. if (ClassExported) {
  5157. NewAttr = ::new (getASTContext())
  5158. DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
  5159. } else {
  5160. NewAttr = ::new (getASTContext())
  5161. DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
  5162. }
  5163. } else {
  5164. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5165. }
  5166. NewAttr->setInherited(true);
  5167. Member->addAttr(NewAttr);
  5168. if (MD) {
  5169. // Propagate DLLAttr to friend re-declarations of MD that have already
  5170. // been constructed.
  5171. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5172. FD = FD->getPreviousDecl()) {
  5173. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5174. continue;
  5175. assert(!getDLLAttr(FD) &&
  5176. "friend re-decl should not already have a DLLAttr");
  5177. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5178. NewAttr->setInherited(true);
  5179. FD->addAttr(NewAttr);
  5180. }
  5181. }
  5182. }
  5183. }
  5184. if (ClassExported)
  5185. DelayedDllExportClasses.push_back(Class);
  5186. }
  5187. /// Perform propagation of DLL attributes from a derived class to a
  5188. /// templated base class for MS compatibility.
  5189. void Sema::propagateDLLAttrToBaseClassTemplate(
  5190. CXXRecordDecl *Class, Attr *ClassAttr,
  5191. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5192. if (getDLLAttr(
  5193. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5194. // If the base class template has a DLL attribute, don't try to change it.
  5195. return;
  5196. }
  5197. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5198. if (!getDLLAttr(BaseTemplateSpec) &&
  5199. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5200. TSK == TSK_ImplicitInstantiation)) {
  5201. // The template hasn't been instantiated yet (or it has, but only as an
  5202. // explicit instantiation declaration or implicit instantiation, which means
  5203. // we haven't codegenned any members yet), so propagate the attribute.
  5204. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5205. NewAttr->setInherited(true);
  5206. BaseTemplateSpec->addAttr(NewAttr);
  5207. // If this was an import, mark that we propagated it from a derived class to
  5208. // a base class template specialization.
  5209. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5210. ImportAttr->setPropagatedToBaseTemplate();
  5211. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5212. // needs to be run again to work see the new attribute. Otherwise this will
  5213. // get run whenever the template is instantiated.
  5214. if (TSK != TSK_Undeclared)
  5215. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5216. return;
  5217. }
  5218. if (getDLLAttr(BaseTemplateSpec)) {
  5219. // The template has already been specialized or instantiated with an
  5220. // attribute, explicitly or through propagation. We should not try to change
  5221. // it.
  5222. return;
  5223. }
  5224. // The template was previously instantiated or explicitly specialized without
  5225. // a dll attribute, It's too late for us to add an attribute, so warn that
  5226. // this is unsupported.
  5227. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5228. << BaseTemplateSpec->isExplicitSpecialization();
  5229. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5230. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5231. Diag(BaseTemplateSpec->getLocation(),
  5232. diag::note_template_class_explicit_specialization_was_here)
  5233. << BaseTemplateSpec;
  5234. } else {
  5235. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5236. diag::note_template_class_instantiation_was_here)
  5237. << BaseTemplateSpec;
  5238. }
  5239. }
  5240. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5241. SourceLocation DefaultLoc) {
  5242. switch (S.getSpecialMember(MD)) {
  5243. case Sema::CXXDefaultConstructor:
  5244. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5245. cast<CXXConstructorDecl>(MD));
  5246. break;
  5247. case Sema::CXXCopyConstructor:
  5248. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5249. break;
  5250. case Sema::CXXCopyAssignment:
  5251. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5252. break;
  5253. case Sema::CXXDestructor:
  5254. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5255. break;
  5256. case Sema::CXXMoveConstructor:
  5257. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5258. break;
  5259. case Sema::CXXMoveAssignment:
  5260. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5261. break;
  5262. case Sema::CXXInvalid:
  5263. llvm_unreachable("Invalid special member.");
  5264. }
  5265. }
  5266. /// Determine whether a type is permitted to be passed or returned in
  5267. /// registers, per C++ [class.temporary]p3.
  5268. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5269. TargetInfo::CallingConvKind CCK) {
  5270. if (D->isDependentType() || D->isInvalidDecl())
  5271. return false;
  5272. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5273. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5274. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5275. return !D->hasNonTrivialDestructorForCall() &&
  5276. !D->hasNonTrivialCopyConstructorForCall();
  5277. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5278. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5279. bool DtorIsTrivialForCall = false;
  5280. // If a class has at least one non-deleted, trivial copy constructor, it
  5281. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5282. //
  5283. // Note: This permits classes with non-trivial copy or move ctors to be
  5284. // passed in registers, so long as they *also* have a trivial copy ctor,
  5285. // which is non-conforming.
  5286. if (D->needsImplicitCopyConstructor()) {
  5287. if (!D->defaultedCopyConstructorIsDeleted()) {
  5288. if (D->hasTrivialCopyConstructor())
  5289. CopyCtorIsTrivial = true;
  5290. if (D->hasTrivialCopyConstructorForCall())
  5291. CopyCtorIsTrivialForCall = true;
  5292. }
  5293. } else {
  5294. for (const CXXConstructorDecl *CD : D->ctors()) {
  5295. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5296. if (CD->isTrivial())
  5297. CopyCtorIsTrivial = true;
  5298. if (CD->isTrivialForCall())
  5299. CopyCtorIsTrivialForCall = true;
  5300. }
  5301. }
  5302. }
  5303. if (D->needsImplicitDestructor()) {
  5304. if (!D->defaultedDestructorIsDeleted() &&
  5305. D->hasTrivialDestructorForCall())
  5306. DtorIsTrivialForCall = true;
  5307. } else if (const auto *DD = D->getDestructor()) {
  5308. if (!DD->isDeleted() && DD->isTrivialForCall())
  5309. DtorIsTrivialForCall = true;
  5310. }
  5311. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5312. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5313. return true;
  5314. // If a class has a destructor, we'd really like to pass it indirectly
  5315. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5316. // impossible for small types, which it will pass in a single register or
  5317. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5318. // We can't call out all large objects as being indirect because there are
  5319. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5320. // how we pass large POD types.
  5321. // Note: This permits small classes with nontrivial destructors to be
  5322. // passed in registers, which is non-conforming.
  5323. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5324. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5325. if (CopyCtorIsTrivial &&
  5326. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5327. return true;
  5328. return false;
  5329. }
  5330. // Per C++ [class.temporary]p3, the relevant condition is:
  5331. // each copy constructor, move constructor, and destructor of X is
  5332. // either trivial or deleted, and X has at least one non-deleted copy
  5333. // or move constructor
  5334. bool HasNonDeletedCopyOrMove = false;
  5335. if (D->needsImplicitCopyConstructor() &&
  5336. !D->defaultedCopyConstructorIsDeleted()) {
  5337. if (!D->hasTrivialCopyConstructorForCall())
  5338. return false;
  5339. HasNonDeletedCopyOrMove = true;
  5340. }
  5341. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5342. !D->defaultedMoveConstructorIsDeleted()) {
  5343. if (!D->hasTrivialMoveConstructorForCall())
  5344. return false;
  5345. HasNonDeletedCopyOrMove = true;
  5346. }
  5347. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5348. !D->hasTrivialDestructorForCall())
  5349. return false;
  5350. for (const CXXMethodDecl *MD : D->methods()) {
  5351. if (MD->isDeleted())
  5352. continue;
  5353. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5354. if (CD && CD->isCopyOrMoveConstructor())
  5355. HasNonDeletedCopyOrMove = true;
  5356. else if (!isa<CXXDestructorDecl>(MD))
  5357. continue;
  5358. if (!MD->isTrivialForCall())
  5359. return false;
  5360. }
  5361. return HasNonDeletedCopyOrMove;
  5362. }
  5363. /// Perform semantic checks on a class definition that has been
  5364. /// completing, introducing implicitly-declared members, checking for
  5365. /// abstract types, etc.
  5366. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5367. if (!Record)
  5368. return;
  5369. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5370. AbstractUsageInfo Info(*this, Record);
  5371. CheckAbstractClassUsage(Info, Record);
  5372. }
  5373. // If this is not an aggregate type and has no user-declared constructor,
  5374. // complain about any non-static data members of reference or const scalar
  5375. // type, since they will never get initializers.
  5376. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5377. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5378. !Record->isLambda()) {
  5379. bool Complained = false;
  5380. for (const auto *F : Record->fields()) {
  5381. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5382. continue;
  5383. if (F->getType()->isReferenceType() ||
  5384. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5385. if (!Complained) {
  5386. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5387. << Record->getTagKind() << Record;
  5388. Complained = true;
  5389. }
  5390. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5391. << F->getType()->isReferenceType()
  5392. << F->getDeclName();
  5393. }
  5394. }
  5395. }
  5396. if (Record->getIdentifier()) {
  5397. // C++ [class.mem]p13:
  5398. // If T is the name of a class, then each of the following shall have a
  5399. // name different from T:
  5400. // - every member of every anonymous union that is a member of class T.
  5401. //
  5402. // C++ [class.mem]p14:
  5403. // In addition, if class T has a user-declared constructor (12.1), every
  5404. // non-static data member of class T shall have a name different from T.
  5405. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5406. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5407. ++I) {
  5408. NamedDecl *D = (*I)->getUnderlyingDecl();
  5409. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5410. Record->hasUserDeclaredConstructor()) ||
  5411. isa<IndirectFieldDecl>(D)) {
  5412. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5413. << D->getDeclName();
  5414. break;
  5415. }
  5416. }
  5417. }
  5418. // Warn if the class has virtual methods but non-virtual public destructor.
  5419. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5420. CXXDestructorDecl *dtor = Record->getDestructor();
  5421. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5422. !Record->hasAttr<FinalAttr>())
  5423. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5424. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5425. }
  5426. if (Record->isAbstract()) {
  5427. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5428. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5429. << FA->isSpelledAsSealed();
  5430. DiagnoseAbstractType(Record);
  5431. }
  5432. }
  5433. // Warn if the class has a final destructor but is not itself marked final.
  5434. if (!Record->hasAttr<FinalAttr>()) {
  5435. if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
  5436. if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
  5437. Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
  5438. << FA->isSpelledAsSealed()
  5439. << FixItHint::CreateInsertion(
  5440. getLocForEndOfToken(Record->getLocation()),
  5441. (FA->isSpelledAsSealed() ? " sealed" : " final"));
  5442. Diag(Record->getLocation(),
  5443. diag::note_final_dtor_non_final_class_silence)
  5444. << Context.getRecordType(Record) << FA->isSpelledAsSealed();
  5445. }
  5446. }
  5447. }
  5448. // See if trivial_abi has to be dropped.
  5449. if (Record->hasAttr<TrivialABIAttr>())
  5450. checkIllFormedTrivialABIStruct(*Record);
  5451. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5452. // "trivial_abi".
  5453. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5454. if (HasTrivialABI)
  5455. Record->setHasTrivialSpecialMemberForCall();
  5456. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  5457. // Check whether the explicitly-defaulted special members are valid.
  5458. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5459. CheckExplicitlyDefaultedSpecialMember(M);
  5460. // For an explicitly defaulted or deleted special member, we defer
  5461. // determining triviality until the class is complete. That time is now!
  5462. CXXSpecialMember CSM = getSpecialMember(M);
  5463. if (!M->isImplicit() && !M->isUserProvided()) {
  5464. if (CSM != CXXInvalid) {
  5465. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5466. // Inform the class that we've finished declaring this member.
  5467. Record->finishedDefaultedOrDeletedMember(M);
  5468. M->setTrivialForCall(
  5469. HasTrivialABI ||
  5470. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5471. Record->setTrivialForCallFlags(M);
  5472. }
  5473. }
  5474. // Set triviality for the purpose of calls if this is a user-provided
  5475. // copy/move constructor or destructor.
  5476. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5477. CSM == CXXDestructor) && M->isUserProvided()) {
  5478. M->setTrivialForCall(HasTrivialABI);
  5479. Record->setTrivialForCallFlags(M);
  5480. }
  5481. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5482. M->hasAttr<DLLExportAttr>()) {
  5483. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5484. M->isTrivial() &&
  5485. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5486. CSM == CXXDestructor))
  5487. M->dropAttr<DLLExportAttr>();
  5488. if (M->hasAttr<DLLExportAttr>()) {
  5489. // Define after any fields with in-class initializers have been parsed.
  5490. DelayedDllExportMemberFunctions.push_back(M);
  5491. }
  5492. }
  5493. };
  5494. bool HasMethodWithOverrideControl = false,
  5495. HasOverridingMethodWithoutOverrideControl = false;
  5496. if (!Record->isDependentType()) {
  5497. // Check the destructor before any other member function. We need to
  5498. // determine whether it's trivial in order to determine whether the claas
  5499. // type is a literal type, which is a prerequisite for determining whether
  5500. // other special member functions are valid and whether they're implicitly
  5501. // 'constexpr'.
  5502. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  5503. CompleteMemberFunction(Dtor);
  5504. for (auto *M : Record->methods()) {
  5505. // See if a method overloads virtual methods in a base
  5506. // class without overriding any.
  5507. if (!M->isStatic())
  5508. DiagnoseHiddenVirtualMethods(M);
  5509. if (M->hasAttr<OverrideAttr>())
  5510. HasMethodWithOverrideControl = true;
  5511. else if (M->size_overridden_methods() > 0)
  5512. HasOverridingMethodWithoutOverrideControl = true;
  5513. if (!isa<CXXDestructorDecl>(M))
  5514. CompleteMemberFunction(M);
  5515. }
  5516. }
  5517. if (HasMethodWithOverrideControl &&
  5518. HasOverridingMethodWithoutOverrideControl) {
  5519. // At least one method has the 'override' control declared.
  5520. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5521. for (auto *M : Record->methods())
  5522. DiagnoseAbsenceOfOverrideControl(M);
  5523. }
  5524. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5525. // whether this class uses any C++ features that are implemented
  5526. // completely differently in MSVC, and if so, emit a diagnostic.
  5527. // That diagnostic defaults to an error, but we allow projects to
  5528. // map it down to a warning (or ignore it). It's a fairly common
  5529. // practice among users of the ms_struct pragma to mass-annotate
  5530. // headers, sweeping up a bunch of types that the project doesn't
  5531. // really rely on MSVC-compatible layout for. We must therefore
  5532. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5533. if (Record->isMsStruct(Context) &&
  5534. (Record->isPolymorphic() || Record->getNumBases())) {
  5535. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5536. }
  5537. checkClassLevelDLLAttribute(Record);
  5538. checkClassLevelCodeSegAttribute(Record);
  5539. bool ClangABICompat4 =
  5540. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5541. TargetInfo::CallingConvKind CCK =
  5542. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5543. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5544. // Do not change ArgPassingRestrictions if it has already been set to
  5545. // APK_CanNeverPassInRegs.
  5546. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5547. Record->setArgPassingRestrictions(CanPass
  5548. ? RecordDecl::APK_CanPassInRegs
  5549. : RecordDecl::APK_CannotPassInRegs);
  5550. // If canPassInRegisters returns true despite the record having a non-trivial
  5551. // destructor, the record is destructed in the callee. This happens only when
  5552. // the record or one of its subobjects has a field annotated with trivial_abi
  5553. // or a field qualified with ObjC __strong/__weak.
  5554. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5555. Record->setParamDestroyedInCallee(true);
  5556. else if (Record->hasNonTrivialDestructor())
  5557. Record->setParamDestroyedInCallee(CanPass);
  5558. if (getLangOpts().ForceEmitVTables) {
  5559. // If we want to emit all the vtables, we need to mark it as used. This
  5560. // is especially required for cases like vtable assumption loads.
  5561. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5562. }
  5563. }
  5564. /// Look up the special member function that would be called by a special
  5565. /// member function for a subobject of class type.
  5566. ///
  5567. /// \param Class The class type of the subobject.
  5568. /// \param CSM The kind of special member function.
  5569. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5570. /// \param ConstRHS True if this is a copy operation with a const object
  5571. /// on its RHS, that is, if the argument to the outer special member
  5572. /// function is 'const' and this is not a field marked 'mutable'.
  5573. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5574. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5575. unsigned FieldQuals, bool ConstRHS) {
  5576. unsigned LHSQuals = 0;
  5577. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5578. LHSQuals = FieldQuals;
  5579. unsigned RHSQuals = FieldQuals;
  5580. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5581. RHSQuals = 0;
  5582. else if (ConstRHS)
  5583. RHSQuals |= Qualifiers::Const;
  5584. return S.LookupSpecialMember(Class, CSM,
  5585. RHSQuals & Qualifiers::Const,
  5586. RHSQuals & Qualifiers::Volatile,
  5587. false,
  5588. LHSQuals & Qualifiers::Const,
  5589. LHSQuals & Qualifiers::Volatile);
  5590. }
  5591. class Sema::InheritedConstructorInfo {
  5592. Sema &S;
  5593. SourceLocation UseLoc;
  5594. /// A mapping from the base classes through which the constructor was
  5595. /// inherited to the using shadow declaration in that base class (or a null
  5596. /// pointer if the constructor was declared in that base class).
  5597. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5598. InheritedFromBases;
  5599. public:
  5600. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5601. ConstructorUsingShadowDecl *Shadow)
  5602. : S(S), UseLoc(UseLoc) {
  5603. bool DiagnosedMultipleConstructedBases = false;
  5604. CXXRecordDecl *ConstructedBase = nullptr;
  5605. UsingDecl *ConstructedBaseUsing = nullptr;
  5606. // Find the set of such base class subobjects and check that there's a
  5607. // unique constructed subobject.
  5608. for (auto *D : Shadow->redecls()) {
  5609. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5610. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5611. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5612. InheritedFromBases.insert(
  5613. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5614. DShadow->getNominatedBaseClassShadowDecl()));
  5615. if (DShadow->constructsVirtualBase())
  5616. InheritedFromBases.insert(
  5617. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5618. DShadow->getConstructedBaseClassShadowDecl()));
  5619. else
  5620. assert(DNominatedBase == DConstructedBase);
  5621. // [class.inhctor.init]p2:
  5622. // If the constructor was inherited from multiple base class subobjects
  5623. // of type B, the program is ill-formed.
  5624. if (!ConstructedBase) {
  5625. ConstructedBase = DConstructedBase;
  5626. ConstructedBaseUsing = D->getUsingDecl();
  5627. } else if (ConstructedBase != DConstructedBase &&
  5628. !Shadow->isInvalidDecl()) {
  5629. if (!DiagnosedMultipleConstructedBases) {
  5630. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5631. << Shadow->getTargetDecl();
  5632. S.Diag(ConstructedBaseUsing->getLocation(),
  5633. diag::note_ambiguous_inherited_constructor_using)
  5634. << ConstructedBase;
  5635. DiagnosedMultipleConstructedBases = true;
  5636. }
  5637. S.Diag(D->getUsingDecl()->getLocation(),
  5638. diag::note_ambiguous_inherited_constructor_using)
  5639. << DConstructedBase;
  5640. }
  5641. }
  5642. if (DiagnosedMultipleConstructedBases)
  5643. Shadow->setInvalidDecl();
  5644. }
  5645. /// Find the constructor to use for inherited construction of a base class,
  5646. /// and whether that base class constructor inherits the constructor from a
  5647. /// virtual base class (in which case it won't actually invoke it).
  5648. std::pair<CXXConstructorDecl *, bool>
  5649. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5650. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5651. if (It == InheritedFromBases.end())
  5652. return std::make_pair(nullptr, false);
  5653. // This is an intermediary class.
  5654. if (It->second)
  5655. return std::make_pair(
  5656. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5657. It->second->constructsVirtualBase());
  5658. // This is the base class from which the constructor was inherited.
  5659. return std::make_pair(Ctor, false);
  5660. }
  5661. };
  5662. /// Is the special member function which would be selected to perform the
  5663. /// specified operation on the specified class type a constexpr constructor?
  5664. static bool
  5665. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5666. Sema::CXXSpecialMember CSM, unsigned Quals,
  5667. bool ConstRHS,
  5668. CXXConstructorDecl *InheritedCtor = nullptr,
  5669. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5670. // If we're inheriting a constructor, see if we need to call it for this base
  5671. // class.
  5672. if (InheritedCtor) {
  5673. assert(CSM == Sema::CXXDefaultConstructor);
  5674. auto BaseCtor =
  5675. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5676. if (BaseCtor)
  5677. return BaseCtor->isConstexpr();
  5678. }
  5679. if (CSM == Sema::CXXDefaultConstructor)
  5680. return ClassDecl->hasConstexprDefaultConstructor();
  5681. Sema::SpecialMemberOverloadResult SMOR =
  5682. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5683. if (!SMOR.getMethod())
  5684. // A constructor we wouldn't select can't be "involved in initializing"
  5685. // anything.
  5686. return true;
  5687. return SMOR.getMethod()->isConstexpr();
  5688. }
  5689. /// Determine whether the specified special member function would be constexpr
  5690. /// if it were implicitly defined.
  5691. static bool defaultedSpecialMemberIsConstexpr(
  5692. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5693. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5694. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5695. if (!S.getLangOpts().CPlusPlus11)
  5696. return false;
  5697. // C++11 [dcl.constexpr]p4:
  5698. // In the definition of a constexpr constructor [...]
  5699. bool Ctor = true;
  5700. switch (CSM) {
  5701. case Sema::CXXDefaultConstructor:
  5702. if (Inherited)
  5703. break;
  5704. // Since default constructor lookup is essentially trivial (and cannot
  5705. // involve, for instance, template instantiation), we compute whether a
  5706. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5707. //
  5708. // This is important for performance; we need to know whether the default
  5709. // constructor is constexpr to determine whether the type is a literal type.
  5710. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5711. case Sema::CXXCopyConstructor:
  5712. case Sema::CXXMoveConstructor:
  5713. // For copy or move constructors, we need to perform overload resolution.
  5714. break;
  5715. case Sema::CXXCopyAssignment:
  5716. case Sema::CXXMoveAssignment:
  5717. if (!S.getLangOpts().CPlusPlus14)
  5718. return false;
  5719. // In C++1y, we need to perform overload resolution.
  5720. Ctor = false;
  5721. break;
  5722. case Sema::CXXDestructor:
  5723. case Sema::CXXInvalid:
  5724. return false;
  5725. }
  5726. // -- if the class is a non-empty union, or for each non-empty anonymous
  5727. // union member of a non-union class, exactly one non-static data member
  5728. // shall be initialized; [DR1359]
  5729. //
  5730. // If we squint, this is guaranteed, since exactly one non-static data member
  5731. // will be initialized (if the constructor isn't deleted), we just don't know
  5732. // which one.
  5733. if (Ctor && ClassDecl->isUnion())
  5734. return CSM == Sema::CXXDefaultConstructor
  5735. ? ClassDecl->hasInClassInitializer() ||
  5736. !ClassDecl->hasVariantMembers()
  5737. : true;
  5738. // -- the class shall not have any virtual base classes;
  5739. if (Ctor && ClassDecl->getNumVBases())
  5740. return false;
  5741. // C++1y [class.copy]p26:
  5742. // -- [the class] is a literal type, and
  5743. if (!Ctor && !ClassDecl->isLiteral())
  5744. return false;
  5745. // -- every constructor involved in initializing [...] base class
  5746. // sub-objects shall be a constexpr constructor;
  5747. // -- the assignment operator selected to copy/move each direct base
  5748. // class is a constexpr function, and
  5749. for (const auto &B : ClassDecl->bases()) {
  5750. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5751. if (!BaseType) continue;
  5752. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5753. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5754. InheritedCtor, Inherited))
  5755. return false;
  5756. }
  5757. // -- every constructor involved in initializing non-static data members
  5758. // [...] shall be a constexpr constructor;
  5759. // -- every non-static data member and base class sub-object shall be
  5760. // initialized
  5761. // -- for each non-static data member of X that is of class type (or array
  5762. // thereof), the assignment operator selected to copy/move that member is
  5763. // a constexpr function
  5764. for (const auto *F : ClassDecl->fields()) {
  5765. if (F->isInvalidDecl())
  5766. continue;
  5767. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5768. continue;
  5769. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5770. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5771. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5772. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5773. BaseType.getCVRQualifiers(),
  5774. ConstArg && !F->isMutable()))
  5775. return false;
  5776. } else if (CSM == Sema::CXXDefaultConstructor) {
  5777. return false;
  5778. }
  5779. }
  5780. // All OK, it's constexpr!
  5781. return true;
  5782. }
  5783. static Sema::ImplicitExceptionSpecification
  5784. ComputeDefaultedSpecialMemberExceptionSpec(
  5785. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5786. Sema::InheritedConstructorInfo *ICI);
  5787. static Sema::ImplicitExceptionSpecification
  5788. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5789. auto CSM = S.getSpecialMember(MD);
  5790. if (CSM != Sema::CXXInvalid)
  5791. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5792. auto *CD = cast<CXXConstructorDecl>(MD);
  5793. assert(CD->getInheritedConstructor() &&
  5794. "only special members have implicit exception specs");
  5795. Sema::InheritedConstructorInfo ICI(
  5796. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5797. return ComputeDefaultedSpecialMemberExceptionSpec(
  5798. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5799. }
  5800. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5801. CXXMethodDecl *MD) {
  5802. FunctionProtoType::ExtProtoInfo EPI;
  5803. // Build an exception specification pointing back at this member.
  5804. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5805. EPI.ExceptionSpec.SourceDecl = MD;
  5806. // Set the calling convention to the default for C++ instance methods.
  5807. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5808. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5809. /*IsCXXMethod=*/true));
  5810. return EPI;
  5811. }
  5812. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5813. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5814. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5815. return;
  5816. // Evaluate the exception specification.
  5817. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5818. auto ESI = IES.getExceptionSpec();
  5819. // Update the type of the special member to use it.
  5820. UpdateExceptionSpec(MD, ESI);
  5821. // A user-provided destructor can be defined outside the class. When that
  5822. // happens, be sure to update the exception specification on both
  5823. // declarations.
  5824. const FunctionProtoType *CanonicalFPT =
  5825. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5826. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5827. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5828. }
  5829. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5830. CXXRecordDecl *RD = MD->getParent();
  5831. CXXSpecialMember CSM = getSpecialMember(MD);
  5832. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5833. "not an explicitly-defaulted special member");
  5834. // Whether this was the first-declared instance of the constructor.
  5835. // This affects whether we implicitly add an exception spec and constexpr.
  5836. bool First = MD == MD->getCanonicalDecl();
  5837. bool HadError = false;
  5838. // C++11 [dcl.fct.def.default]p1:
  5839. // A function that is explicitly defaulted shall
  5840. // -- be a special member function (checked elsewhere),
  5841. // -- have the same type (except for ref-qualifiers, and except that a
  5842. // copy operation can take a non-const reference) as an implicit
  5843. // declaration, and
  5844. // -- not have default arguments.
  5845. // C++2a changes the second bullet to instead delete the function if it's
  5846. // defaulted on its first declaration, unless it's "an assignment operator,
  5847. // and its return type differs or its parameter type is not a reference".
  5848. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
  5849. bool ShouldDeleteForTypeMismatch = false;
  5850. unsigned ExpectedParams = 1;
  5851. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5852. ExpectedParams = 0;
  5853. if (MD->getNumParams() != ExpectedParams) {
  5854. // This checks for default arguments: a copy or move constructor with a
  5855. // default argument is classified as a default constructor, and assignment
  5856. // operations and destructors can't have default arguments.
  5857. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5858. << CSM << MD->getSourceRange();
  5859. HadError = true;
  5860. } else if (MD->isVariadic()) {
  5861. if (DeleteOnTypeMismatch)
  5862. ShouldDeleteForTypeMismatch = true;
  5863. else {
  5864. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5865. << CSM << MD->getSourceRange();
  5866. HadError = true;
  5867. }
  5868. }
  5869. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5870. bool CanHaveConstParam = false;
  5871. if (CSM == CXXCopyConstructor)
  5872. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5873. else if (CSM == CXXCopyAssignment)
  5874. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5875. QualType ReturnType = Context.VoidTy;
  5876. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5877. // Check for return type matching.
  5878. ReturnType = Type->getReturnType();
  5879. QualType DeclType = Context.getTypeDeclType(RD);
  5880. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  5881. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  5882. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5883. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5884. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5885. HadError = true;
  5886. }
  5887. // A defaulted special member cannot have cv-qualifiers.
  5888. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  5889. if (DeleteOnTypeMismatch)
  5890. ShouldDeleteForTypeMismatch = true;
  5891. else {
  5892. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5893. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5894. HadError = true;
  5895. }
  5896. }
  5897. }
  5898. // Check for parameter type matching.
  5899. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5900. bool HasConstParam = false;
  5901. if (ExpectedParams && ArgType->isReferenceType()) {
  5902. // Argument must be reference to possibly-const T.
  5903. QualType ReferentType = ArgType->getPointeeType();
  5904. HasConstParam = ReferentType.isConstQualified();
  5905. if (ReferentType.isVolatileQualified()) {
  5906. if (DeleteOnTypeMismatch)
  5907. ShouldDeleteForTypeMismatch = true;
  5908. else {
  5909. Diag(MD->getLocation(),
  5910. diag::err_defaulted_special_member_volatile_param) << CSM;
  5911. HadError = true;
  5912. }
  5913. }
  5914. if (HasConstParam && !CanHaveConstParam) {
  5915. if (DeleteOnTypeMismatch)
  5916. ShouldDeleteForTypeMismatch = true;
  5917. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5918. Diag(MD->getLocation(),
  5919. diag::err_defaulted_special_member_copy_const_param)
  5920. << (CSM == CXXCopyAssignment);
  5921. // FIXME: Explain why this special member can't be const.
  5922. HadError = true;
  5923. } else {
  5924. Diag(MD->getLocation(),
  5925. diag::err_defaulted_special_member_move_const_param)
  5926. << (CSM == CXXMoveAssignment);
  5927. HadError = true;
  5928. }
  5929. }
  5930. } else if (ExpectedParams) {
  5931. // A copy assignment operator can take its argument by value, but a
  5932. // defaulted one cannot.
  5933. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5934. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5935. HadError = true;
  5936. }
  5937. // C++11 [dcl.fct.def.default]p2:
  5938. // An explicitly-defaulted function may be declared constexpr only if it
  5939. // would have been implicitly declared as constexpr,
  5940. // Do not apply this rule to members of class templates, since core issue 1358
  5941. // makes such functions always instantiate to constexpr functions. For
  5942. // functions which cannot be constexpr (for non-constructors in C++11 and for
  5943. // destructors in C++1y), this is checked elsewhere.
  5944. //
  5945. // FIXME: This should not apply if the member is deleted.
  5946. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  5947. HasConstParam);
  5948. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  5949. : isa<CXXConstructorDecl>(MD)) &&
  5950. MD->isConstexpr() && !Constexpr &&
  5951. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  5952. Diag(MD->getBeginLoc(), MD->isConsteval()
  5953. ? diag::err_incorrect_defaulted_consteval
  5954. : diag::err_incorrect_defaulted_constexpr)
  5955. << CSM;
  5956. // FIXME: Explain why the special member can't be constexpr.
  5957. HadError = true;
  5958. }
  5959. if (First) {
  5960. // C++2a [dcl.fct.def.default]p3:
  5961. // If a function is explicitly defaulted on its first declaration, it is
  5962. // implicitly considered to be constexpr if the implicit declaration
  5963. // would be.
  5964. MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
  5965. if (!Type->hasExceptionSpec()) {
  5966. // C++2a [except.spec]p3:
  5967. // If a declaration of a function does not have a noexcept-specifier
  5968. // [and] is defaulted on its first declaration, [...] the exception
  5969. // specification is as specified below
  5970. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  5971. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5972. EPI.ExceptionSpec.SourceDecl = MD;
  5973. MD->setType(Context.getFunctionType(ReturnType,
  5974. llvm::makeArrayRef(&ArgType,
  5975. ExpectedParams),
  5976. EPI));
  5977. }
  5978. }
  5979. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  5980. if (First) {
  5981. SetDeclDeleted(MD, MD->getLocation());
  5982. if (!inTemplateInstantiation() && !HadError) {
  5983. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  5984. if (ShouldDeleteForTypeMismatch) {
  5985. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  5986. } else {
  5987. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5988. }
  5989. }
  5990. if (ShouldDeleteForTypeMismatch && !HadError) {
  5991. Diag(MD->getLocation(),
  5992. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  5993. }
  5994. } else {
  5995. // C++11 [dcl.fct.def.default]p4:
  5996. // [For a] user-provided explicitly-defaulted function [...] if such a
  5997. // function is implicitly defined as deleted, the program is ill-formed.
  5998. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  5999. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  6000. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6001. HadError = true;
  6002. }
  6003. }
  6004. if (HadError)
  6005. MD->setInvalidDecl();
  6006. }
  6007. void Sema::CheckDelayedMemberExceptionSpecs() {
  6008. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  6009. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  6010. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  6011. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  6012. // Perform any deferred checking of exception specifications for virtual
  6013. // destructors.
  6014. for (auto &Check : Overriding)
  6015. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  6016. // Perform any deferred checking of exception specifications for befriended
  6017. // special members.
  6018. for (auto &Check : Equivalent)
  6019. CheckEquivalentExceptionSpec(Check.second, Check.first);
  6020. }
  6021. namespace {
  6022. /// CRTP base class for visiting operations performed by a special member
  6023. /// function (or inherited constructor).
  6024. template<typename Derived>
  6025. struct SpecialMemberVisitor {
  6026. Sema &S;
  6027. CXXMethodDecl *MD;
  6028. Sema::CXXSpecialMember CSM;
  6029. Sema::InheritedConstructorInfo *ICI;
  6030. // Properties of the special member, computed for convenience.
  6031. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  6032. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  6033. Sema::InheritedConstructorInfo *ICI)
  6034. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  6035. switch (CSM) {
  6036. case Sema::CXXDefaultConstructor:
  6037. case Sema::CXXCopyConstructor:
  6038. case Sema::CXXMoveConstructor:
  6039. IsConstructor = true;
  6040. break;
  6041. case Sema::CXXCopyAssignment:
  6042. case Sema::CXXMoveAssignment:
  6043. IsAssignment = true;
  6044. break;
  6045. case Sema::CXXDestructor:
  6046. break;
  6047. case Sema::CXXInvalid:
  6048. llvm_unreachable("invalid special member kind");
  6049. }
  6050. if (MD->getNumParams()) {
  6051. if (const ReferenceType *RT =
  6052. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  6053. ConstArg = RT->getPointeeType().isConstQualified();
  6054. }
  6055. }
  6056. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6057. /// Is this a "move" special member?
  6058. bool isMove() const {
  6059. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  6060. }
  6061. /// Look up the corresponding special member in the given class.
  6062. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  6063. unsigned Quals, bool IsMutable) {
  6064. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  6065. ConstArg && !IsMutable);
  6066. }
  6067. /// Look up the constructor for the specified base class to see if it's
  6068. /// overridden due to this being an inherited constructor.
  6069. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  6070. if (!ICI)
  6071. return {};
  6072. assert(CSM == Sema::CXXDefaultConstructor);
  6073. auto *BaseCtor =
  6074. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  6075. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  6076. return MD;
  6077. return {};
  6078. }
  6079. /// A base or member subobject.
  6080. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  6081. /// Get the location to use for a subobject in diagnostics.
  6082. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  6083. // FIXME: For an indirect virtual base, the direct base leading to
  6084. // the indirect virtual base would be a more useful choice.
  6085. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  6086. return B->getBaseTypeLoc();
  6087. else
  6088. return Subobj.get<FieldDecl*>()->getLocation();
  6089. }
  6090. enum BasesToVisit {
  6091. /// Visit all non-virtual (direct) bases.
  6092. VisitNonVirtualBases,
  6093. /// Visit all direct bases, virtual or not.
  6094. VisitDirectBases,
  6095. /// Visit all non-virtual bases, and all virtual bases if the class
  6096. /// is not abstract.
  6097. VisitPotentiallyConstructedBases,
  6098. /// Visit all direct or virtual bases.
  6099. VisitAllBases
  6100. };
  6101. // Visit the bases and members of the class.
  6102. bool visit(BasesToVisit Bases) {
  6103. CXXRecordDecl *RD = MD->getParent();
  6104. if (Bases == VisitPotentiallyConstructedBases)
  6105. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  6106. for (auto &B : RD->bases())
  6107. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  6108. getDerived().visitBase(&B))
  6109. return true;
  6110. if (Bases == VisitAllBases)
  6111. for (auto &B : RD->vbases())
  6112. if (getDerived().visitBase(&B))
  6113. return true;
  6114. for (auto *F : RD->fields())
  6115. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  6116. getDerived().visitField(F))
  6117. return true;
  6118. return false;
  6119. }
  6120. };
  6121. }
  6122. namespace {
  6123. struct SpecialMemberDeletionInfo
  6124. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  6125. bool Diagnose;
  6126. SourceLocation Loc;
  6127. bool AllFieldsAreConst;
  6128. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  6129. Sema::CXXSpecialMember CSM,
  6130. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  6131. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  6132. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  6133. bool inUnion() const { return MD->getParent()->isUnion(); }
  6134. Sema::CXXSpecialMember getEffectiveCSM() {
  6135. return ICI ? Sema::CXXInvalid : CSM;
  6136. }
  6137. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  6138. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  6139. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  6140. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  6141. bool shouldDeleteForField(FieldDecl *FD);
  6142. bool shouldDeleteForAllConstMembers();
  6143. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  6144. unsigned Quals);
  6145. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  6146. Sema::SpecialMemberOverloadResult SMOR,
  6147. bool IsDtorCallInCtor);
  6148. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  6149. };
  6150. }
  6151. /// Is the given special member inaccessible when used on the given
  6152. /// sub-object.
  6153. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  6154. CXXMethodDecl *target) {
  6155. /// If we're operating on a base class, the object type is the
  6156. /// type of this special member.
  6157. QualType objectTy;
  6158. AccessSpecifier access = target->getAccess();
  6159. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  6160. objectTy = S.Context.getTypeDeclType(MD->getParent());
  6161. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  6162. // If we're operating on a field, the object type is the type of the field.
  6163. } else {
  6164. objectTy = S.Context.getTypeDeclType(target->getParent());
  6165. }
  6166. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  6167. }
  6168. /// Check whether we should delete a special member due to the implicit
  6169. /// definition containing a call to a special member of a subobject.
  6170. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  6171. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  6172. bool IsDtorCallInCtor) {
  6173. CXXMethodDecl *Decl = SMOR.getMethod();
  6174. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6175. int DiagKind = -1;
  6176. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  6177. DiagKind = !Decl ? 0 : 1;
  6178. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6179. DiagKind = 2;
  6180. else if (!isAccessible(Subobj, Decl))
  6181. DiagKind = 3;
  6182. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  6183. !Decl->isTrivial()) {
  6184. // A member of a union must have a trivial corresponding special member.
  6185. // As a weird special case, a destructor call from a union's constructor
  6186. // must be accessible and non-deleted, but need not be trivial. Such a
  6187. // destructor is never actually called, but is semantically checked as
  6188. // if it were.
  6189. DiagKind = 4;
  6190. }
  6191. if (DiagKind == -1)
  6192. return false;
  6193. if (Diagnose) {
  6194. if (Field) {
  6195. S.Diag(Field->getLocation(),
  6196. diag::note_deleted_special_member_class_subobject)
  6197. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  6198. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  6199. } else {
  6200. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  6201. S.Diag(Base->getBeginLoc(),
  6202. diag::note_deleted_special_member_class_subobject)
  6203. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6204. << Base->getType() << DiagKind << IsDtorCallInCtor
  6205. << /*IsObjCPtr*/false;
  6206. }
  6207. if (DiagKind == 1)
  6208. S.NoteDeletedFunction(Decl);
  6209. // FIXME: Explain inaccessibility if DiagKind == 3.
  6210. }
  6211. return true;
  6212. }
  6213. /// Check whether we should delete a special member function due to having a
  6214. /// direct or virtual base class or non-static data member of class type M.
  6215. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  6216. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  6217. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6218. bool IsMutable = Field && Field->isMutable();
  6219. // C++11 [class.ctor]p5:
  6220. // -- any direct or virtual base class, or non-static data member with no
  6221. // brace-or-equal-initializer, has class type M (or array thereof) and
  6222. // either M has no default constructor or overload resolution as applied
  6223. // to M's default constructor results in an ambiguity or in a function
  6224. // that is deleted or inaccessible
  6225. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6226. // -- a direct or virtual base class B that cannot be copied/moved because
  6227. // overload resolution, as applied to B's corresponding special member,
  6228. // results in an ambiguity or a function that is deleted or inaccessible
  6229. // from the defaulted special member
  6230. // C++11 [class.dtor]p5:
  6231. // -- any direct or virtual base class [...] has a type with a destructor
  6232. // that is deleted or inaccessible
  6233. if (!(CSM == Sema::CXXDefaultConstructor &&
  6234. Field && Field->hasInClassInitializer()) &&
  6235. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6236. false))
  6237. return true;
  6238. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6239. // -- any direct or virtual base class or non-static data member has a
  6240. // type with a destructor that is deleted or inaccessible
  6241. if (IsConstructor) {
  6242. Sema::SpecialMemberOverloadResult SMOR =
  6243. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6244. false, false, false, false, false);
  6245. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6246. return true;
  6247. }
  6248. return false;
  6249. }
  6250. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  6251. FieldDecl *FD, QualType FieldType) {
  6252. // The defaulted special functions are defined as deleted if this is a variant
  6253. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  6254. // type under ARC.
  6255. if (!FieldType.hasNonTrivialObjCLifetime())
  6256. return false;
  6257. // Don't make the defaulted default constructor defined as deleted if the
  6258. // member has an in-class initializer.
  6259. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  6260. return false;
  6261. if (Diagnose) {
  6262. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  6263. S.Diag(FD->getLocation(),
  6264. diag::note_deleted_special_member_class_subobject)
  6265. << getEffectiveCSM() << ParentClass << /*IsField*/true
  6266. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  6267. }
  6268. return true;
  6269. }
  6270. /// Check whether we should delete a special member function due to the class
  6271. /// having a particular direct or virtual base class.
  6272. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6273. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6274. // If program is correct, BaseClass cannot be null, but if it is, the error
  6275. // must be reported elsewhere.
  6276. if (!BaseClass)
  6277. return false;
  6278. // If we have an inheriting constructor, check whether we're calling an
  6279. // inherited constructor instead of a default constructor.
  6280. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6281. if (auto *BaseCtor = SMOR.getMethod()) {
  6282. // Note that we do not check access along this path; other than that,
  6283. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6284. // FIXME: Check that the base has a usable destructor! Sink this into
  6285. // shouldDeleteForClassSubobject.
  6286. if (BaseCtor->isDeleted() && Diagnose) {
  6287. S.Diag(Base->getBeginLoc(),
  6288. diag::note_deleted_special_member_class_subobject)
  6289. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6290. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  6291. << /*IsObjCPtr*/false;
  6292. S.NoteDeletedFunction(BaseCtor);
  6293. }
  6294. return BaseCtor->isDeleted();
  6295. }
  6296. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6297. }
  6298. /// Check whether we should delete a special member function due to the class
  6299. /// having a particular non-static data member.
  6300. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6301. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6302. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6303. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  6304. return true;
  6305. if (CSM == Sema::CXXDefaultConstructor) {
  6306. // For a default constructor, all references must be initialized in-class
  6307. // and, if a union, it must have a non-const member.
  6308. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6309. if (Diagnose)
  6310. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6311. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6312. return true;
  6313. }
  6314. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6315. // const-qualified type (or array thereof) with no
  6316. // brace-or-equal-initializer does not have a user-provided default
  6317. // constructor.
  6318. if (!inUnion() && FieldType.isConstQualified() &&
  6319. !FD->hasInClassInitializer() &&
  6320. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6321. if (Diagnose)
  6322. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6323. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6324. return true;
  6325. }
  6326. if (inUnion() && !FieldType.isConstQualified())
  6327. AllFieldsAreConst = false;
  6328. } else if (CSM == Sema::CXXCopyConstructor) {
  6329. // For a copy constructor, data members must not be of rvalue reference
  6330. // type.
  6331. if (FieldType->isRValueReferenceType()) {
  6332. if (Diagnose)
  6333. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6334. << MD->getParent() << FD << FieldType;
  6335. return true;
  6336. }
  6337. } else if (IsAssignment) {
  6338. // For an assignment operator, data members must not be of reference type.
  6339. if (FieldType->isReferenceType()) {
  6340. if (Diagnose)
  6341. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6342. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6343. return true;
  6344. }
  6345. if (!FieldRecord && FieldType.isConstQualified()) {
  6346. // C++11 [class.copy]p23:
  6347. // -- a non-static data member of const non-class type (or array thereof)
  6348. if (Diagnose)
  6349. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6350. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6351. return true;
  6352. }
  6353. }
  6354. if (FieldRecord) {
  6355. // Some additional restrictions exist on the variant members.
  6356. if (!inUnion() && FieldRecord->isUnion() &&
  6357. FieldRecord->isAnonymousStructOrUnion()) {
  6358. bool AllVariantFieldsAreConst = true;
  6359. // FIXME: Handle anonymous unions declared within anonymous unions.
  6360. for (auto *UI : FieldRecord->fields()) {
  6361. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6362. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  6363. return true;
  6364. if (!UnionFieldType.isConstQualified())
  6365. AllVariantFieldsAreConst = false;
  6366. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6367. if (UnionFieldRecord &&
  6368. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6369. UnionFieldType.getCVRQualifiers()))
  6370. return true;
  6371. }
  6372. // At least one member in each anonymous union must be non-const
  6373. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6374. !FieldRecord->field_empty()) {
  6375. if (Diagnose)
  6376. S.Diag(FieldRecord->getLocation(),
  6377. diag::note_deleted_default_ctor_all_const)
  6378. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6379. return true;
  6380. }
  6381. // Don't check the implicit member of the anonymous union type.
  6382. // This is technically non-conformant, but sanity demands it.
  6383. return false;
  6384. }
  6385. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6386. FieldType.getCVRQualifiers()))
  6387. return true;
  6388. }
  6389. return false;
  6390. }
  6391. /// C++11 [class.ctor] p5:
  6392. /// A defaulted default constructor for a class X is defined as deleted if
  6393. /// X is a union and all of its variant members are of const-qualified type.
  6394. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6395. // This is a silly definition, because it gives an empty union a deleted
  6396. // default constructor. Don't do that.
  6397. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6398. bool AnyFields = false;
  6399. for (auto *F : MD->getParent()->fields())
  6400. if ((AnyFields = !F->isUnnamedBitfield()))
  6401. break;
  6402. if (!AnyFields)
  6403. return false;
  6404. if (Diagnose)
  6405. S.Diag(MD->getParent()->getLocation(),
  6406. diag::note_deleted_default_ctor_all_const)
  6407. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6408. return true;
  6409. }
  6410. return false;
  6411. }
  6412. /// Determine whether a defaulted special member function should be defined as
  6413. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6414. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6415. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6416. InheritedConstructorInfo *ICI,
  6417. bool Diagnose) {
  6418. if (MD->isInvalidDecl())
  6419. return false;
  6420. CXXRecordDecl *RD = MD->getParent();
  6421. assert(!RD->isDependentType() && "do deletion after instantiation");
  6422. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6423. return false;
  6424. // C++11 [expr.lambda.prim]p19:
  6425. // The closure type associated with a lambda-expression has a
  6426. // deleted (8.4.3) default constructor and a deleted copy
  6427. // assignment operator.
  6428. // C++2a adds back these operators if the lambda has no lambda-capture.
  6429. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  6430. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6431. if (Diagnose)
  6432. Diag(RD->getLocation(), diag::note_lambda_decl);
  6433. return true;
  6434. }
  6435. // For an anonymous struct or union, the copy and assignment special members
  6436. // will never be used, so skip the check. For an anonymous union declared at
  6437. // namespace scope, the constructor and destructor are used.
  6438. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6439. RD->isAnonymousStructOrUnion())
  6440. return false;
  6441. // C++11 [class.copy]p7, p18:
  6442. // If the class definition declares a move constructor or move assignment
  6443. // operator, an implicitly declared copy constructor or copy assignment
  6444. // operator is defined as deleted.
  6445. if (MD->isImplicit() &&
  6446. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6447. CXXMethodDecl *UserDeclaredMove = nullptr;
  6448. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6449. // deletion of the corresponding copy operation, not both copy operations.
  6450. // MSVC 2015 has adopted the standards conforming behavior.
  6451. bool DeletesOnlyMatchingCopy =
  6452. getLangOpts().MSVCCompat &&
  6453. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6454. if (RD->hasUserDeclaredMoveConstructor() &&
  6455. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6456. if (!Diagnose) return true;
  6457. // Find any user-declared move constructor.
  6458. for (auto *I : RD->ctors()) {
  6459. if (I->isMoveConstructor()) {
  6460. UserDeclaredMove = I;
  6461. break;
  6462. }
  6463. }
  6464. assert(UserDeclaredMove);
  6465. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6466. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6467. if (!Diagnose) return true;
  6468. // Find any user-declared move assignment operator.
  6469. for (auto *I : RD->methods()) {
  6470. if (I->isMoveAssignmentOperator()) {
  6471. UserDeclaredMove = I;
  6472. break;
  6473. }
  6474. }
  6475. assert(UserDeclaredMove);
  6476. }
  6477. if (UserDeclaredMove) {
  6478. Diag(UserDeclaredMove->getLocation(),
  6479. diag::note_deleted_copy_user_declared_move)
  6480. << (CSM == CXXCopyAssignment) << RD
  6481. << UserDeclaredMove->isMoveAssignmentOperator();
  6482. return true;
  6483. }
  6484. }
  6485. // Do access control from the special member function
  6486. ContextRAII MethodContext(*this, MD);
  6487. // C++11 [class.dtor]p5:
  6488. // -- for a virtual destructor, lookup of the non-array deallocation function
  6489. // results in an ambiguity or in a function that is deleted or inaccessible
  6490. if (CSM == CXXDestructor && MD->isVirtual()) {
  6491. FunctionDecl *OperatorDelete = nullptr;
  6492. DeclarationName Name =
  6493. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6494. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6495. OperatorDelete, /*Diagnose*/false)) {
  6496. if (Diagnose)
  6497. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6498. return true;
  6499. }
  6500. }
  6501. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6502. // Per DR1611, do not consider virtual bases of constructors of abstract
  6503. // classes, since we are not going to construct them.
  6504. // Per DR1658, do not consider virtual bases of destructors of abstract
  6505. // classes either.
  6506. // Per DR2180, for assignment operators we only assign (and thus only
  6507. // consider) direct bases.
  6508. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6509. : SMI.VisitPotentiallyConstructedBases))
  6510. return true;
  6511. if (SMI.shouldDeleteForAllConstMembers())
  6512. return true;
  6513. if (getLangOpts().CUDA) {
  6514. // We should delete the special member in CUDA mode if target inference
  6515. // failed.
  6516. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  6517. // is treated as certain special member, which may not reflect what special
  6518. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  6519. // expects CSM to match MD, therefore recalculate CSM.
  6520. assert(ICI || CSM == getSpecialMember(MD));
  6521. auto RealCSM = CSM;
  6522. if (ICI)
  6523. RealCSM = getSpecialMember(MD);
  6524. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  6525. SMI.ConstArg, Diagnose);
  6526. }
  6527. return false;
  6528. }
  6529. /// Perform lookup for a special member of the specified kind, and determine
  6530. /// whether it is trivial. If the triviality can be determined without the
  6531. /// lookup, skip it. This is intended for use when determining whether a
  6532. /// special member of a containing object is trivial, and thus does not ever
  6533. /// perform overload resolution for default constructors.
  6534. ///
  6535. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6536. /// member that was most likely to be intended to be trivial, if any.
  6537. ///
  6538. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6539. /// determine whether the special member is trivial.
  6540. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6541. Sema::CXXSpecialMember CSM, unsigned Quals,
  6542. bool ConstRHS,
  6543. Sema::TrivialABIHandling TAH,
  6544. CXXMethodDecl **Selected) {
  6545. if (Selected)
  6546. *Selected = nullptr;
  6547. switch (CSM) {
  6548. case Sema::CXXInvalid:
  6549. llvm_unreachable("not a special member");
  6550. case Sema::CXXDefaultConstructor:
  6551. // C++11 [class.ctor]p5:
  6552. // A default constructor is trivial if:
  6553. // - all the [direct subobjects] have trivial default constructors
  6554. //
  6555. // Note, no overload resolution is performed in this case.
  6556. if (RD->hasTrivialDefaultConstructor())
  6557. return true;
  6558. if (Selected) {
  6559. // If there's a default constructor which could have been trivial, dig it
  6560. // out. Otherwise, if there's any user-provided default constructor, point
  6561. // to that as an example of why there's not a trivial one.
  6562. CXXConstructorDecl *DefCtor = nullptr;
  6563. if (RD->needsImplicitDefaultConstructor())
  6564. S.DeclareImplicitDefaultConstructor(RD);
  6565. for (auto *CI : RD->ctors()) {
  6566. if (!CI->isDefaultConstructor())
  6567. continue;
  6568. DefCtor = CI;
  6569. if (!DefCtor->isUserProvided())
  6570. break;
  6571. }
  6572. *Selected = DefCtor;
  6573. }
  6574. return false;
  6575. case Sema::CXXDestructor:
  6576. // C++11 [class.dtor]p5:
  6577. // A destructor is trivial if:
  6578. // - all the direct [subobjects] have trivial destructors
  6579. if (RD->hasTrivialDestructor() ||
  6580. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6581. RD->hasTrivialDestructorForCall()))
  6582. return true;
  6583. if (Selected) {
  6584. if (RD->needsImplicitDestructor())
  6585. S.DeclareImplicitDestructor(RD);
  6586. *Selected = RD->getDestructor();
  6587. }
  6588. return false;
  6589. case Sema::CXXCopyConstructor:
  6590. // C++11 [class.copy]p12:
  6591. // A copy constructor is trivial if:
  6592. // - the constructor selected to copy each direct [subobject] is trivial
  6593. if (RD->hasTrivialCopyConstructor() ||
  6594. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6595. RD->hasTrivialCopyConstructorForCall())) {
  6596. if (Quals == Qualifiers::Const)
  6597. // We must either select the trivial copy constructor or reach an
  6598. // ambiguity; no need to actually perform overload resolution.
  6599. return true;
  6600. } else if (!Selected) {
  6601. return false;
  6602. }
  6603. // In C++98, we are not supposed to perform overload resolution here, but we
  6604. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6605. // cases like B as having a non-trivial copy constructor:
  6606. // struct A { template<typename T> A(T&); };
  6607. // struct B { mutable A a; };
  6608. goto NeedOverloadResolution;
  6609. case Sema::CXXCopyAssignment:
  6610. // C++11 [class.copy]p25:
  6611. // A copy assignment operator is trivial if:
  6612. // - the assignment operator selected to copy each direct [subobject] is
  6613. // trivial
  6614. if (RD->hasTrivialCopyAssignment()) {
  6615. if (Quals == Qualifiers::Const)
  6616. return true;
  6617. } else if (!Selected) {
  6618. return false;
  6619. }
  6620. // In C++98, we are not supposed to perform overload resolution here, but we
  6621. // treat that as a language defect.
  6622. goto NeedOverloadResolution;
  6623. case Sema::CXXMoveConstructor:
  6624. case Sema::CXXMoveAssignment:
  6625. NeedOverloadResolution:
  6626. Sema::SpecialMemberOverloadResult SMOR =
  6627. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6628. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6629. // We treat it as not making the member non-trivial, just like the standard
  6630. // mandates for the default constructor. This should rarely matter, because
  6631. // the member will also be deleted.
  6632. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6633. return true;
  6634. if (!SMOR.getMethod()) {
  6635. assert(SMOR.getKind() ==
  6636. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6637. return false;
  6638. }
  6639. // We deliberately don't check if we found a deleted special member. We're
  6640. // not supposed to!
  6641. if (Selected)
  6642. *Selected = SMOR.getMethod();
  6643. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6644. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6645. return SMOR.getMethod()->isTrivialForCall();
  6646. return SMOR.getMethod()->isTrivial();
  6647. }
  6648. llvm_unreachable("unknown special method kind");
  6649. }
  6650. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6651. for (auto *CI : RD->ctors())
  6652. if (!CI->isImplicit())
  6653. return CI;
  6654. // Look for constructor templates.
  6655. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6656. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6657. if (CXXConstructorDecl *CD =
  6658. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6659. return CD;
  6660. }
  6661. return nullptr;
  6662. }
  6663. /// The kind of subobject we are checking for triviality. The values of this
  6664. /// enumeration are used in diagnostics.
  6665. enum TrivialSubobjectKind {
  6666. /// The subobject is a base class.
  6667. TSK_BaseClass,
  6668. /// The subobject is a non-static data member.
  6669. TSK_Field,
  6670. /// The object is actually the complete object.
  6671. TSK_CompleteObject
  6672. };
  6673. /// Check whether the special member selected for a given type would be trivial.
  6674. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6675. QualType SubType, bool ConstRHS,
  6676. Sema::CXXSpecialMember CSM,
  6677. TrivialSubobjectKind Kind,
  6678. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6679. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6680. if (!SubRD)
  6681. return true;
  6682. CXXMethodDecl *Selected;
  6683. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6684. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6685. return true;
  6686. if (Diagnose) {
  6687. if (ConstRHS)
  6688. SubType.addConst();
  6689. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6690. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6691. << Kind << SubType.getUnqualifiedType();
  6692. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6693. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6694. } else if (!Selected)
  6695. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6696. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6697. else if (Selected->isUserProvided()) {
  6698. if (Kind == TSK_CompleteObject)
  6699. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6700. << Kind << SubType.getUnqualifiedType() << CSM;
  6701. else {
  6702. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6703. << Kind << SubType.getUnqualifiedType() << CSM;
  6704. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6705. }
  6706. } else {
  6707. if (Kind != TSK_CompleteObject)
  6708. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6709. << Kind << SubType.getUnqualifiedType() << CSM;
  6710. // Explain why the defaulted or deleted special member isn't trivial.
  6711. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6712. Diagnose);
  6713. }
  6714. }
  6715. return false;
  6716. }
  6717. /// Check whether the members of a class type allow a special member to be
  6718. /// trivial.
  6719. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6720. Sema::CXXSpecialMember CSM,
  6721. bool ConstArg,
  6722. Sema::TrivialABIHandling TAH,
  6723. bool Diagnose) {
  6724. for (const auto *FI : RD->fields()) {
  6725. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6726. continue;
  6727. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6728. // Pretend anonymous struct or union members are members of this class.
  6729. if (FI->isAnonymousStructOrUnion()) {
  6730. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6731. CSM, ConstArg, TAH, Diagnose))
  6732. return false;
  6733. continue;
  6734. }
  6735. // C++11 [class.ctor]p5:
  6736. // A default constructor is trivial if [...]
  6737. // -- no non-static data member of its class has a
  6738. // brace-or-equal-initializer
  6739. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6740. if (Diagnose)
  6741. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6742. return false;
  6743. }
  6744. // Objective C ARC 4.3.5:
  6745. // [...] nontrivally ownership-qualified types are [...] not trivially
  6746. // default constructible, copy constructible, move constructible, copy
  6747. // assignable, move assignable, or destructible [...]
  6748. if (FieldType.hasNonTrivialObjCLifetime()) {
  6749. if (Diagnose)
  6750. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6751. << RD << FieldType.getObjCLifetime();
  6752. return false;
  6753. }
  6754. bool ConstRHS = ConstArg && !FI->isMutable();
  6755. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6756. CSM, TSK_Field, TAH, Diagnose))
  6757. return false;
  6758. }
  6759. return true;
  6760. }
  6761. /// Diagnose why the specified class does not have a trivial special member of
  6762. /// the given kind.
  6763. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6764. QualType Ty = Context.getRecordType(RD);
  6765. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6766. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6767. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6768. /*Diagnose*/true);
  6769. }
  6770. /// Determine whether a defaulted or deleted special member function is trivial,
  6771. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6772. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6773. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6774. TrivialABIHandling TAH, bool Diagnose) {
  6775. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6776. CXXRecordDecl *RD = MD->getParent();
  6777. bool ConstArg = false;
  6778. // C++11 [class.copy]p12, p25: [DR1593]
  6779. // A [special member] is trivial if [...] its parameter-type-list is
  6780. // equivalent to the parameter-type-list of an implicit declaration [...]
  6781. switch (CSM) {
  6782. case CXXDefaultConstructor:
  6783. case CXXDestructor:
  6784. // Trivial default constructors and destructors cannot have parameters.
  6785. break;
  6786. case CXXCopyConstructor:
  6787. case CXXCopyAssignment: {
  6788. // Trivial copy operations always have const, non-volatile parameter types.
  6789. ConstArg = true;
  6790. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6791. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6792. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6793. if (Diagnose)
  6794. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6795. << Param0->getSourceRange() << Param0->getType()
  6796. << Context.getLValueReferenceType(
  6797. Context.getRecordType(RD).withConst());
  6798. return false;
  6799. }
  6800. break;
  6801. }
  6802. case CXXMoveConstructor:
  6803. case CXXMoveAssignment: {
  6804. // Trivial move operations always have non-cv-qualified parameters.
  6805. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6806. const RValueReferenceType *RT =
  6807. Param0->getType()->getAs<RValueReferenceType>();
  6808. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6809. if (Diagnose)
  6810. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6811. << Param0->getSourceRange() << Param0->getType()
  6812. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6813. return false;
  6814. }
  6815. break;
  6816. }
  6817. case CXXInvalid:
  6818. llvm_unreachable("not a special member");
  6819. }
  6820. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6821. if (Diagnose)
  6822. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6823. diag::note_nontrivial_default_arg)
  6824. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6825. return false;
  6826. }
  6827. if (MD->isVariadic()) {
  6828. if (Diagnose)
  6829. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6830. return false;
  6831. }
  6832. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6833. // A copy/move [constructor or assignment operator] is trivial if
  6834. // -- the [member] selected to copy/move each direct base class subobject
  6835. // is trivial
  6836. //
  6837. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6838. // A [default constructor or destructor] is trivial if
  6839. // -- all the direct base classes have trivial [default constructors or
  6840. // destructors]
  6841. for (const auto &BI : RD->bases())
  6842. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6843. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6844. return false;
  6845. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6846. // A copy/move [constructor or assignment operator] for a class X is
  6847. // trivial if
  6848. // -- for each non-static data member of X that is of class type (or array
  6849. // thereof), the constructor selected to copy/move that member is
  6850. // trivial
  6851. //
  6852. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6853. // A [default constructor or destructor] is trivial if
  6854. // -- for all of the non-static data members of its class that are of class
  6855. // type (or array thereof), each such class has a trivial [default
  6856. // constructor or destructor]
  6857. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6858. return false;
  6859. // C++11 [class.dtor]p5:
  6860. // A destructor is trivial if [...]
  6861. // -- the destructor is not virtual
  6862. if (CSM == CXXDestructor && MD->isVirtual()) {
  6863. if (Diagnose)
  6864. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6865. return false;
  6866. }
  6867. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6868. // A [special member] for class X is trivial if [...]
  6869. // -- class X has no virtual functions and no virtual base classes
  6870. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6871. if (!Diagnose)
  6872. return false;
  6873. if (RD->getNumVBases()) {
  6874. // Check for virtual bases. We already know that the corresponding
  6875. // member in all bases is trivial, so vbases must all be direct.
  6876. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6877. assert(BS.isVirtual());
  6878. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6879. return false;
  6880. }
  6881. // Must have a virtual method.
  6882. for (const auto *MI : RD->methods()) {
  6883. if (MI->isVirtual()) {
  6884. SourceLocation MLoc = MI->getBeginLoc();
  6885. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6886. return false;
  6887. }
  6888. }
  6889. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6890. }
  6891. // Looks like it's trivial!
  6892. return true;
  6893. }
  6894. namespace {
  6895. struct FindHiddenVirtualMethod {
  6896. Sema *S;
  6897. CXXMethodDecl *Method;
  6898. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6899. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6900. private:
  6901. /// Check whether any most overridden method from MD in Methods
  6902. static bool CheckMostOverridenMethods(
  6903. const CXXMethodDecl *MD,
  6904. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6905. if (MD->size_overridden_methods() == 0)
  6906. return Methods.count(MD->getCanonicalDecl());
  6907. for (const CXXMethodDecl *O : MD->overridden_methods())
  6908. if (CheckMostOverridenMethods(O, Methods))
  6909. return true;
  6910. return false;
  6911. }
  6912. public:
  6913. /// Member lookup function that determines whether a given C++
  6914. /// method overloads virtual methods in a base class without overriding any,
  6915. /// to be used with CXXRecordDecl::lookupInBases().
  6916. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6917. RecordDecl *BaseRecord =
  6918. Specifier->getType()->getAs<RecordType>()->getDecl();
  6919. DeclarationName Name = Method->getDeclName();
  6920. assert(Name.getNameKind() == DeclarationName::Identifier);
  6921. bool foundSameNameMethod = false;
  6922. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6923. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6924. Path.Decls = Path.Decls.slice(1)) {
  6925. NamedDecl *D = Path.Decls.front();
  6926. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6927. MD = MD->getCanonicalDecl();
  6928. foundSameNameMethod = true;
  6929. // Interested only in hidden virtual methods.
  6930. if (!MD->isVirtual())
  6931. continue;
  6932. // If the method we are checking overrides a method from its base
  6933. // don't warn about the other overloaded methods. Clang deviates from
  6934. // GCC by only diagnosing overloads of inherited virtual functions that
  6935. // do not override any other virtual functions in the base. GCC's
  6936. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  6937. // function from a base class. These cases may be better served by a
  6938. // warning (not specific to virtual functions) on call sites when the
  6939. // call would select a different function from the base class, were it
  6940. // visible.
  6941. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  6942. if (!S->IsOverload(Method, MD, false))
  6943. return true;
  6944. // Collect the overload only if its hidden.
  6945. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  6946. overloadedMethods.push_back(MD);
  6947. }
  6948. }
  6949. if (foundSameNameMethod)
  6950. OverloadedMethods.append(overloadedMethods.begin(),
  6951. overloadedMethods.end());
  6952. return foundSameNameMethod;
  6953. }
  6954. };
  6955. } // end anonymous namespace
  6956. /// Add the most overriden methods from MD to Methods
  6957. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  6958. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  6959. if (MD->size_overridden_methods() == 0)
  6960. Methods.insert(MD->getCanonicalDecl());
  6961. else
  6962. for (const CXXMethodDecl *O : MD->overridden_methods())
  6963. AddMostOverridenMethods(O, Methods);
  6964. }
  6965. /// Check if a method overloads virtual methods in a base class without
  6966. /// overriding any.
  6967. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  6968. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6969. if (!MD->getDeclName().isIdentifier())
  6970. return;
  6971. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  6972. /*bool RecordPaths=*/false,
  6973. /*bool DetectVirtual=*/false);
  6974. FindHiddenVirtualMethod FHVM;
  6975. FHVM.Method = MD;
  6976. FHVM.S = this;
  6977. // Keep the base methods that were overridden or introduced in the subclass
  6978. // by 'using' in a set. A base method not in this set is hidden.
  6979. CXXRecordDecl *DC = MD->getParent();
  6980. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  6981. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6982. NamedDecl *ND = *I;
  6983. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  6984. ND = shad->getTargetDecl();
  6985. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6986. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  6987. }
  6988. if (DC->lookupInBases(FHVM, Paths))
  6989. OverloadedMethods = FHVM.OverloadedMethods;
  6990. }
  6991. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  6992. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6993. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  6994. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  6995. PartialDiagnostic PD = PDiag(
  6996. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  6997. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  6998. Diag(overloadedMD->getLocation(), PD);
  6999. }
  7000. }
  7001. /// Diagnose methods which overload virtual methods in a base class
  7002. /// without overriding any.
  7003. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  7004. if (MD->isInvalidDecl())
  7005. return;
  7006. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  7007. return;
  7008. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  7009. FindHiddenVirtualMethods(MD, OverloadedMethods);
  7010. if (!OverloadedMethods.empty()) {
  7011. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  7012. << MD << (OverloadedMethods.size() > 1);
  7013. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  7014. }
  7015. }
  7016. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  7017. auto PrintDiagAndRemoveAttr = [&]() {
  7018. // No diagnostics if this is a template instantiation.
  7019. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  7020. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  7021. diag::ext_cannot_use_trivial_abi) << &RD;
  7022. RD.dropAttr<TrivialABIAttr>();
  7023. };
  7024. // Ill-formed if the struct has virtual functions.
  7025. if (RD.isPolymorphic()) {
  7026. PrintDiagAndRemoveAttr();
  7027. return;
  7028. }
  7029. for (const auto &B : RD.bases()) {
  7030. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  7031. // virtual base.
  7032. if ((!B.getType()->isDependentType() &&
  7033. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  7034. B.isVirtual()) {
  7035. PrintDiagAndRemoveAttr();
  7036. return;
  7037. }
  7038. }
  7039. for (const auto *FD : RD.fields()) {
  7040. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  7041. // non-trivial for the purpose of calls.
  7042. QualType FT = FD->getType();
  7043. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  7044. PrintDiagAndRemoveAttr();
  7045. return;
  7046. }
  7047. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  7048. if (!RT->isDependentType() &&
  7049. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  7050. PrintDiagAndRemoveAttr();
  7051. return;
  7052. }
  7053. }
  7054. }
  7055. void Sema::ActOnFinishCXXMemberSpecification(
  7056. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  7057. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  7058. if (!TagDecl)
  7059. return;
  7060. AdjustDeclIfTemplate(TagDecl);
  7061. for (const ParsedAttr &AL : AttrList) {
  7062. if (AL.getKind() != ParsedAttr::AT_Visibility)
  7063. continue;
  7064. AL.setInvalid();
  7065. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
  7066. }
  7067. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  7068. // strict aliasing violation!
  7069. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  7070. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  7071. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  7072. }
  7073. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  7074. /// special functions, such as the default constructor, copy
  7075. /// constructor, or destructor, to the given C++ class (C++
  7076. /// [special]p1). This routine can only be executed just before the
  7077. /// definition of the class is complete.
  7078. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  7079. if (ClassDecl->needsImplicitDefaultConstructor()) {
  7080. ++getASTContext().NumImplicitDefaultConstructors;
  7081. if (ClassDecl->hasInheritedConstructor())
  7082. DeclareImplicitDefaultConstructor(ClassDecl);
  7083. }
  7084. if (ClassDecl->needsImplicitCopyConstructor()) {
  7085. ++getASTContext().NumImplicitCopyConstructors;
  7086. // If the properties or semantics of the copy constructor couldn't be
  7087. // determined while the class was being declared, force a declaration
  7088. // of it now.
  7089. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  7090. ClassDecl->hasInheritedConstructor())
  7091. DeclareImplicitCopyConstructor(ClassDecl);
  7092. // For the MS ABI we need to know whether the copy ctor is deleted. A
  7093. // prerequisite for deleting the implicit copy ctor is that the class has a
  7094. // move ctor or move assignment that is either user-declared or whose
  7095. // semantics are inherited from a subobject. FIXME: We should provide a more
  7096. // direct way for CodeGen to ask whether the constructor was deleted.
  7097. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  7098. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  7099. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7100. ClassDecl->hasUserDeclaredMoveAssignment() ||
  7101. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  7102. DeclareImplicitCopyConstructor(ClassDecl);
  7103. }
  7104. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  7105. ++getASTContext().NumImplicitMoveConstructors;
  7106. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  7107. ClassDecl->hasInheritedConstructor())
  7108. DeclareImplicitMoveConstructor(ClassDecl);
  7109. }
  7110. if (ClassDecl->needsImplicitCopyAssignment()) {
  7111. ++getASTContext().NumImplicitCopyAssignmentOperators;
  7112. // If we have a dynamic class, then the copy assignment operator may be
  7113. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  7114. // it shows up in the right place in the vtable and that we diagnose
  7115. // problems with the implicit exception specification.
  7116. if (ClassDecl->isDynamicClass() ||
  7117. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  7118. ClassDecl->hasInheritedAssignment())
  7119. DeclareImplicitCopyAssignment(ClassDecl);
  7120. }
  7121. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  7122. ++getASTContext().NumImplicitMoveAssignmentOperators;
  7123. // Likewise for the move assignment operator.
  7124. if (ClassDecl->isDynamicClass() ||
  7125. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  7126. ClassDecl->hasInheritedAssignment())
  7127. DeclareImplicitMoveAssignment(ClassDecl);
  7128. }
  7129. if (ClassDecl->needsImplicitDestructor()) {
  7130. ++getASTContext().NumImplicitDestructors;
  7131. // If we have a dynamic class, then the destructor may be virtual, so we
  7132. // have to declare the destructor immediately. This ensures that, e.g., it
  7133. // shows up in the right place in the vtable and that we diagnose problems
  7134. // with the implicit exception specification.
  7135. if (ClassDecl->isDynamicClass() ||
  7136. ClassDecl->needsOverloadResolutionForDestructor())
  7137. DeclareImplicitDestructor(ClassDecl);
  7138. }
  7139. }
  7140. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  7141. if (!D)
  7142. return 0;
  7143. // The order of template parameters is not important here. All names
  7144. // get added to the same scope.
  7145. SmallVector<TemplateParameterList *, 4> ParameterLists;
  7146. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  7147. D = TD->getTemplatedDecl();
  7148. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  7149. ParameterLists.push_back(PSD->getTemplateParameters());
  7150. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  7151. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  7152. ParameterLists.push_back(DD->getTemplateParameterList(i));
  7153. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7154. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  7155. ParameterLists.push_back(FTD->getTemplateParameters());
  7156. }
  7157. }
  7158. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7159. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  7160. ParameterLists.push_back(TD->getTemplateParameterList(i));
  7161. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  7162. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  7163. ParameterLists.push_back(CTD->getTemplateParameters());
  7164. }
  7165. }
  7166. unsigned Count = 0;
  7167. for (TemplateParameterList *Params : ParameterLists) {
  7168. if (Params->size() > 0)
  7169. // Ignore explicit specializations; they don't contribute to the template
  7170. // depth.
  7171. ++Count;
  7172. for (NamedDecl *Param : *Params) {
  7173. if (Param->getDeclName()) {
  7174. S->AddDecl(Param);
  7175. IdResolver.AddDecl(Param);
  7176. }
  7177. }
  7178. }
  7179. return Count;
  7180. }
  7181. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7182. if (!RecordD) return;
  7183. AdjustDeclIfTemplate(RecordD);
  7184. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  7185. PushDeclContext(S, Record);
  7186. }
  7187. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7188. if (!RecordD) return;
  7189. PopDeclContext();
  7190. }
  7191. /// This is used to implement the constant expression evaluation part of the
  7192. /// attribute enable_if extension. There is nothing in standard C++ which would
  7193. /// require reentering parameters.
  7194. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  7195. if (!Param)
  7196. return;
  7197. S->AddDecl(Param);
  7198. if (Param->getDeclName())
  7199. IdResolver.AddDecl(Param);
  7200. }
  7201. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  7202. /// parsing a top-level (non-nested) C++ class, and we are now
  7203. /// parsing those parts of the given Method declaration that could
  7204. /// not be parsed earlier (C++ [class.mem]p2), such as default
  7205. /// arguments. This action should enter the scope of the given
  7206. /// Method declaration as if we had just parsed the qualified method
  7207. /// name. However, it should not bring the parameters into scope;
  7208. /// that will be performed by ActOnDelayedCXXMethodParameter.
  7209. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7210. }
  7211. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  7212. /// C++ method declaration. We're (re-)introducing the given
  7213. /// function parameter into scope for use in parsing later parts of
  7214. /// the method declaration. For example, we could see an
  7215. /// ActOnParamDefaultArgument event for this parameter.
  7216. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  7217. if (!ParamD)
  7218. return;
  7219. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  7220. // If this parameter has an unparsed default argument, clear it out
  7221. // to make way for the parsed default argument.
  7222. if (Param->hasUnparsedDefaultArg())
  7223. Param->setDefaultArg(nullptr);
  7224. S->AddDecl(Param);
  7225. if (Param->getDeclName())
  7226. IdResolver.AddDecl(Param);
  7227. }
  7228. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  7229. /// processing the delayed method declaration for Method. The method
  7230. /// declaration is now considered finished. There may be a separate
  7231. /// ActOnStartOfFunctionDef action later (not necessarily
  7232. /// immediately!) for this method, if it was also defined inside the
  7233. /// class body.
  7234. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7235. if (!MethodD)
  7236. return;
  7237. AdjustDeclIfTemplate(MethodD);
  7238. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  7239. // Now that we have our default arguments, check the constructor
  7240. // again. It could produce additional diagnostics or affect whether
  7241. // the class has implicitly-declared destructors, among other
  7242. // things.
  7243. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  7244. CheckConstructor(Constructor);
  7245. // Check the default arguments, which we may have added.
  7246. if (!Method->isInvalidDecl())
  7247. CheckCXXDefaultArguments(Method);
  7248. }
  7249. // Emit the given diagnostic for each non-address-space qualifier.
  7250. // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
  7251. static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
  7252. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7253. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  7254. bool DiagOccured = false;
  7255. FTI.MethodQualifiers->forEachQualifier(
  7256. [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
  7257. SourceLocation SL) {
  7258. // This diagnostic should be emitted on any qualifier except an addr
  7259. // space qualifier. However, forEachQualifier currently doesn't visit
  7260. // addr space qualifiers, so there's no way to write this condition
  7261. // right now; we just diagnose on everything.
  7262. S.Diag(SL, DiagID) << QualName << SourceRange(SL);
  7263. DiagOccured = true;
  7264. });
  7265. if (DiagOccured)
  7266. D.setInvalidType();
  7267. }
  7268. }
  7269. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  7270. /// the well-formedness of the constructor declarator @p D with type @p
  7271. /// R. If there are any errors in the declarator, this routine will
  7272. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7273. /// will be updated to reflect a well-formed type for the constructor and
  7274. /// returned.
  7275. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7276. StorageClass &SC) {
  7277. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7278. // C++ [class.ctor]p3:
  7279. // A constructor shall not be virtual (10.3) or static (9.4). A
  7280. // constructor can be invoked for a const, volatile or const
  7281. // volatile object. A constructor shall not be declared const,
  7282. // volatile, or const volatile (9.3.2).
  7283. if (isVirtual) {
  7284. if (!D.isInvalidType())
  7285. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7286. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7287. << SourceRange(D.getIdentifierLoc());
  7288. D.setInvalidType();
  7289. }
  7290. if (SC == SC_Static) {
  7291. if (!D.isInvalidType())
  7292. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7293. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7294. << SourceRange(D.getIdentifierLoc());
  7295. D.setInvalidType();
  7296. SC = SC_None;
  7297. }
  7298. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7299. diagnoseIgnoredQualifiers(
  7300. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7301. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7302. D.getDeclSpec().getRestrictSpecLoc(),
  7303. D.getDeclSpec().getAtomicSpecLoc());
  7304. D.setInvalidType();
  7305. }
  7306. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
  7307. // C++0x [class.ctor]p4:
  7308. // A constructor shall not be declared with a ref-qualifier.
  7309. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7310. if (FTI.hasRefQualifier()) {
  7311. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7312. << FTI.RefQualifierIsLValueRef
  7313. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7314. D.setInvalidType();
  7315. }
  7316. // Rebuild the function type "R" without any type qualifiers (in
  7317. // case any of the errors above fired) and with "void" as the
  7318. // return type, since constructors don't have return types.
  7319. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7320. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7321. return R;
  7322. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7323. EPI.TypeQuals = Qualifiers();
  7324. EPI.RefQualifier = RQ_None;
  7325. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7326. }
  7327. /// CheckConstructor - Checks a fully-formed constructor for
  7328. /// well-formedness, issuing any diagnostics required. Returns true if
  7329. /// the constructor declarator is invalid.
  7330. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7331. CXXRecordDecl *ClassDecl
  7332. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7333. if (!ClassDecl)
  7334. return Constructor->setInvalidDecl();
  7335. // C++ [class.copy]p3:
  7336. // A declaration of a constructor for a class X is ill-formed if
  7337. // its first parameter is of type (optionally cv-qualified) X and
  7338. // either there are no other parameters or else all other
  7339. // parameters have default arguments.
  7340. if (!Constructor->isInvalidDecl() &&
  7341. ((Constructor->getNumParams() == 1) ||
  7342. (Constructor->getNumParams() > 1 &&
  7343. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7344. Constructor->getTemplateSpecializationKind()
  7345. != TSK_ImplicitInstantiation) {
  7346. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7347. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7348. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7349. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7350. const char *ConstRef
  7351. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7352. : " const &";
  7353. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7354. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7355. // FIXME: Rather that making the constructor invalid, we should endeavor
  7356. // to fix the type.
  7357. Constructor->setInvalidDecl();
  7358. }
  7359. }
  7360. }
  7361. /// CheckDestructor - Checks a fully-formed destructor definition for
  7362. /// well-formedness, issuing any diagnostics required. Returns true
  7363. /// on error.
  7364. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7365. CXXRecordDecl *RD = Destructor->getParent();
  7366. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7367. SourceLocation Loc;
  7368. if (!Destructor->isImplicit())
  7369. Loc = Destructor->getLocation();
  7370. else
  7371. Loc = RD->getLocation();
  7372. // If we have a virtual destructor, look up the deallocation function
  7373. if (FunctionDecl *OperatorDelete =
  7374. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7375. Expr *ThisArg = nullptr;
  7376. // If the notional 'delete this' expression requires a non-trivial
  7377. // conversion from 'this' to the type of a destroying operator delete's
  7378. // first parameter, perform that conversion now.
  7379. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7380. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7381. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7382. // C++ [class.dtor]p13:
  7383. // ... as if for the expression 'delete this' appearing in a
  7384. // non-virtual destructor of the destructor's class.
  7385. ContextRAII SwitchContext(*this, Destructor);
  7386. ExprResult This =
  7387. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7388. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7389. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7390. if (This.isInvalid()) {
  7391. // FIXME: Register this as a context note so that it comes out
  7392. // in the right order.
  7393. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7394. return true;
  7395. }
  7396. ThisArg = This.get();
  7397. }
  7398. }
  7399. DiagnoseUseOfDecl(OperatorDelete, Loc);
  7400. MarkFunctionReferenced(Loc, OperatorDelete);
  7401. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7402. }
  7403. }
  7404. return false;
  7405. }
  7406. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7407. /// the well-formednes of the destructor declarator @p D with type @p
  7408. /// R. If there are any errors in the declarator, this routine will
  7409. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7410. /// will be updated to reflect a well-formed type for the destructor and
  7411. /// returned.
  7412. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7413. StorageClass& SC) {
  7414. // C++ [class.dtor]p1:
  7415. // [...] A typedef-name that names a class is a class-name
  7416. // (7.1.3); however, a typedef-name that names a class shall not
  7417. // be used as the identifier in the declarator for a destructor
  7418. // declaration.
  7419. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7420. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7421. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7422. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7423. else if (const TemplateSpecializationType *TST =
  7424. DeclaratorType->getAs<TemplateSpecializationType>())
  7425. if (TST->isTypeAlias())
  7426. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7427. << DeclaratorType << 1;
  7428. // C++ [class.dtor]p2:
  7429. // A destructor is used to destroy objects of its class type. A
  7430. // destructor takes no parameters, and no return type can be
  7431. // specified for it (not even void). The address of a destructor
  7432. // shall not be taken. A destructor shall not be static. A
  7433. // destructor can be invoked for a const, volatile or const
  7434. // volatile object. A destructor shall not be declared const,
  7435. // volatile or const volatile (9.3.2).
  7436. if (SC == SC_Static) {
  7437. if (!D.isInvalidType())
  7438. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7439. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7440. << SourceRange(D.getIdentifierLoc())
  7441. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7442. SC = SC_None;
  7443. }
  7444. if (!D.isInvalidType()) {
  7445. // Destructors don't have return types, but the parser will
  7446. // happily parse something like:
  7447. //
  7448. // class X {
  7449. // float ~X();
  7450. // };
  7451. //
  7452. // The return type will be eliminated later.
  7453. if (D.getDeclSpec().hasTypeSpecifier())
  7454. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7455. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7456. << SourceRange(D.getIdentifierLoc());
  7457. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7458. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7459. SourceLocation(),
  7460. D.getDeclSpec().getConstSpecLoc(),
  7461. D.getDeclSpec().getVolatileSpecLoc(),
  7462. D.getDeclSpec().getRestrictSpecLoc(),
  7463. D.getDeclSpec().getAtomicSpecLoc());
  7464. D.setInvalidType();
  7465. }
  7466. }
  7467. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
  7468. // C++0x [class.dtor]p2:
  7469. // A destructor shall not be declared with a ref-qualifier.
  7470. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7471. if (FTI.hasRefQualifier()) {
  7472. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7473. << FTI.RefQualifierIsLValueRef
  7474. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7475. D.setInvalidType();
  7476. }
  7477. // Make sure we don't have any parameters.
  7478. if (FTIHasNonVoidParameters(FTI)) {
  7479. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7480. // Delete the parameters.
  7481. FTI.freeParams();
  7482. D.setInvalidType();
  7483. }
  7484. // Make sure the destructor isn't variadic.
  7485. if (FTI.isVariadic) {
  7486. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7487. D.setInvalidType();
  7488. }
  7489. // Rebuild the function type "R" without any type qualifiers or
  7490. // parameters (in case any of the errors above fired) and with
  7491. // "void" as the return type, since destructors don't have return
  7492. // types.
  7493. if (!D.isInvalidType())
  7494. return R;
  7495. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7496. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7497. EPI.Variadic = false;
  7498. EPI.TypeQuals = Qualifiers();
  7499. EPI.RefQualifier = RQ_None;
  7500. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7501. }
  7502. static void extendLeft(SourceRange &R, SourceRange Before) {
  7503. if (Before.isInvalid())
  7504. return;
  7505. R.setBegin(Before.getBegin());
  7506. if (R.getEnd().isInvalid())
  7507. R.setEnd(Before.getEnd());
  7508. }
  7509. static void extendRight(SourceRange &R, SourceRange After) {
  7510. if (After.isInvalid())
  7511. return;
  7512. if (R.getBegin().isInvalid())
  7513. R.setBegin(After.getBegin());
  7514. R.setEnd(After.getEnd());
  7515. }
  7516. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7517. /// well-formednes of the conversion function declarator @p D with
  7518. /// type @p R. If there are any errors in the declarator, this routine
  7519. /// will emit diagnostics and return true. Otherwise, it will return
  7520. /// false. Either way, the type @p R will be updated to reflect a
  7521. /// well-formed type for the conversion operator.
  7522. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7523. StorageClass& SC) {
  7524. // C++ [class.conv.fct]p1:
  7525. // Neither parameter types nor return type can be specified. The
  7526. // type of a conversion function (8.3.5) is "function taking no
  7527. // parameter returning conversion-type-id."
  7528. if (SC == SC_Static) {
  7529. if (!D.isInvalidType())
  7530. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7531. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7532. << D.getName().getSourceRange();
  7533. D.setInvalidType();
  7534. SC = SC_None;
  7535. }
  7536. TypeSourceInfo *ConvTSI = nullptr;
  7537. QualType ConvType =
  7538. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7539. const DeclSpec &DS = D.getDeclSpec();
  7540. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7541. // Conversion functions don't have return types, but the parser will
  7542. // happily parse something like:
  7543. //
  7544. // class X {
  7545. // float operator bool();
  7546. // };
  7547. //
  7548. // The return type will be changed later anyway.
  7549. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7550. << SourceRange(DS.getTypeSpecTypeLoc())
  7551. << SourceRange(D.getIdentifierLoc());
  7552. D.setInvalidType();
  7553. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7554. // It's also plausible that the user writes type qualifiers in the wrong
  7555. // place, such as:
  7556. // struct S { const operator int(); };
  7557. // FIXME: we could provide a fixit to move the qualifiers onto the
  7558. // conversion type.
  7559. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7560. << SourceRange(D.getIdentifierLoc()) << 0;
  7561. D.setInvalidType();
  7562. }
  7563. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7564. // Make sure we don't have any parameters.
  7565. if (Proto->getNumParams() > 0) {
  7566. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7567. // Delete the parameters.
  7568. D.getFunctionTypeInfo().freeParams();
  7569. D.setInvalidType();
  7570. } else if (Proto->isVariadic()) {
  7571. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7572. D.setInvalidType();
  7573. }
  7574. // Diagnose "&operator bool()" and other such nonsense. This
  7575. // is actually a gcc extension which we don't support.
  7576. if (Proto->getReturnType() != ConvType) {
  7577. bool NeedsTypedef = false;
  7578. SourceRange Before, After;
  7579. // Walk the chunks and extract information on them for our diagnostic.
  7580. bool PastFunctionChunk = false;
  7581. for (auto &Chunk : D.type_objects()) {
  7582. switch (Chunk.Kind) {
  7583. case DeclaratorChunk::Function:
  7584. if (!PastFunctionChunk) {
  7585. if (Chunk.Fun.HasTrailingReturnType) {
  7586. TypeSourceInfo *TRT = nullptr;
  7587. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7588. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7589. }
  7590. PastFunctionChunk = true;
  7591. break;
  7592. }
  7593. LLVM_FALLTHROUGH;
  7594. case DeclaratorChunk::Array:
  7595. NeedsTypedef = true;
  7596. extendRight(After, Chunk.getSourceRange());
  7597. break;
  7598. case DeclaratorChunk::Pointer:
  7599. case DeclaratorChunk::BlockPointer:
  7600. case DeclaratorChunk::Reference:
  7601. case DeclaratorChunk::MemberPointer:
  7602. case DeclaratorChunk::Pipe:
  7603. extendLeft(Before, Chunk.getSourceRange());
  7604. break;
  7605. case DeclaratorChunk::Paren:
  7606. extendLeft(Before, Chunk.Loc);
  7607. extendRight(After, Chunk.EndLoc);
  7608. break;
  7609. }
  7610. }
  7611. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7612. After.isValid() ? After.getBegin() :
  7613. D.getIdentifierLoc();
  7614. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7615. DB << Before << After;
  7616. if (!NeedsTypedef) {
  7617. DB << /*don't need a typedef*/0;
  7618. // If we can provide a correct fix-it hint, do so.
  7619. if (After.isInvalid() && ConvTSI) {
  7620. SourceLocation InsertLoc =
  7621. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7622. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7623. << FixItHint::CreateInsertionFromRange(
  7624. InsertLoc, CharSourceRange::getTokenRange(Before))
  7625. << FixItHint::CreateRemoval(Before);
  7626. }
  7627. } else if (!Proto->getReturnType()->isDependentType()) {
  7628. DB << /*typedef*/1 << Proto->getReturnType();
  7629. } else if (getLangOpts().CPlusPlus11) {
  7630. DB << /*alias template*/2 << Proto->getReturnType();
  7631. } else {
  7632. DB << /*might not be fixable*/3;
  7633. }
  7634. // Recover by incorporating the other type chunks into the result type.
  7635. // Note, this does *not* change the name of the function. This is compatible
  7636. // with the GCC extension:
  7637. // struct S { &operator int(); } s;
  7638. // int &r = s.operator int(); // ok in GCC
  7639. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7640. ConvType = Proto->getReturnType();
  7641. }
  7642. // C++ [class.conv.fct]p4:
  7643. // The conversion-type-id shall not represent a function type nor
  7644. // an array type.
  7645. if (ConvType->isArrayType()) {
  7646. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7647. ConvType = Context.getPointerType(ConvType);
  7648. D.setInvalidType();
  7649. } else if (ConvType->isFunctionType()) {
  7650. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7651. ConvType = Context.getPointerType(ConvType);
  7652. D.setInvalidType();
  7653. }
  7654. // Rebuild the function type "R" without any parameters (in case any
  7655. // of the errors above fired) and with the conversion type as the
  7656. // return type.
  7657. if (D.isInvalidType())
  7658. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7659. // C++0x explicit conversion operators.
  7660. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
  7661. Diag(DS.getExplicitSpecLoc(),
  7662. getLangOpts().CPlusPlus11
  7663. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7664. : diag::ext_explicit_conversion_functions)
  7665. << SourceRange(DS.getExplicitSpecRange());
  7666. }
  7667. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7668. /// the declaration of the given C++ conversion function. This routine
  7669. /// is responsible for recording the conversion function in the C++
  7670. /// class, if possible.
  7671. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7672. assert(Conversion && "Expected to receive a conversion function declaration");
  7673. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7674. // Make sure we aren't redeclaring the conversion function.
  7675. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7676. // C++ [class.conv.fct]p1:
  7677. // [...] A conversion function is never used to convert a
  7678. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7679. // same object type (or a reference to it), to a (possibly
  7680. // cv-qualified) base class of that type (or a reference to it),
  7681. // or to (possibly cv-qualified) void.
  7682. // FIXME: Suppress this warning if the conversion function ends up being a
  7683. // virtual function that overrides a virtual function in a base class.
  7684. QualType ClassType
  7685. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7686. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7687. ConvType = ConvTypeRef->getPointeeType();
  7688. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7689. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7690. /* Suppress diagnostics for instantiations. */;
  7691. else if (ConvType->isRecordType()) {
  7692. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7693. if (ConvType == ClassType)
  7694. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7695. << ClassType;
  7696. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7697. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7698. << ClassType << ConvType;
  7699. } else if (ConvType->isVoidType()) {
  7700. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7701. << ClassType << ConvType;
  7702. }
  7703. if (FunctionTemplateDecl *ConversionTemplate
  7704. = Conversion->getDescribedFunctionTemplate())
  7705. return ConversionTemplate;
  7706. return Conversion;
  7707. }
  7708. namespace {
  7709. /// Utility class to accumulate and print a diagnostic listing the invalid
  7710. /// specifier(s) on a declaration.
  7711. struct BadSpecifierDiagnoser {
  7712. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7713. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7714. ~BadSpecifierDiagnoser() {
  7715. Diagnostic << Specifiers;
  7716. }
  7717. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7718. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7719. }
  7720. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7721. return check(SpecLoc,
  7722. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7723. }
  7724. void check(SourceLocation SpecLoc, const char *Spec) {
  7725. if (SpecLoc.isInvalid()) return;
  7726. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7727. if (!Specifiers.empty()) Specifiers += " ";
  7728. Specifiers += Spec;
  7729. }
  7730. Sema &S;
  7731. Sema::SemaDiagnosticBuilder Diagnostic;
  7732. std::string Specifiers;
  7733. };
  7734. }
  7735. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7736. /// These aren't actually declarators in the grammar, so we need to check that
  7737. /// the user didn't specify any pieces that are not part of the deduction-guide
  7738. /// grammar.
  7739. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7740. StorageClass &SC) {
  7741. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7742. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7743. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7744. // C++ [temp.deduct.guide]p3:
  7745. // A deduction-gide shall be declared in the same scope as the
  7746. // corresponding class template.
  7747. if (!CurContext->getRedeclContext()->Equals(
  7748. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7749. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7750. << GuidedTemplateDecl;
  7751. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7752. }
  7753. auto &DS = D.getMutableDeclSpec();
  7754. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7755. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7756. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7757. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  7758. BadSpecifierDiagnoser Diagnoser(
  7759. *this, D.getIdentifierLoc(),
  7760. diag::err_deduction_guide_invalid_specifier);
  7761. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7762. DS.ClearStorageClassSpecs();
  7763. SC = SC_None;
  7764. // 'explicit' is permitted.
  7765. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7766. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7767. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7768. DS.ClearConstexprSpec();
  7769. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7770. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7771. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7772. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7773. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7774. DS.ClearTypeQualifiers();
  7775. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7776. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7777. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7778. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7779. DS.ClearTypeSpecType();
  7780. }
  7781. if (D.isInvalidType())
  7782. return;
  7783. // Check the declarator is simple enough.
  7784. bool FoundFunction = false;
  7785. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7786. if (Chunk.Kind == DeclaratorChunk::Paren)
  7787. continue;
  7788. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7789. Diag(D.getDeclSpec().getBeginLoc(),
  7790. diag::err_deduction_guide_with_complex_decl)
  7791. << D.getSourceRange();
  7792. break;
  7793. }
  7794. if (!Chunk.Fun.hasTrailingReturnType()) {
  7795. Diag(D.getName().getBeginLoc(),
  7796. diag::err_deduction_guide_no_trailing_return_type);
  7797. break;
  7798. }
  7799. // Check that the return type is written as a specialization of
  7800. // the template specified as the deduction-guide's name.
  7801. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7802. TypeSourceInfo *TSI = nullptr;
  7803. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7804. assert(TSI && "deduction guide has valid type but invalid return type?");
  7805. bool AcceptableReturnType = false;
  7806. bool MightInstantiateToSpecialization = false;
  7807. if (auto RetTST =
  7808. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7809. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7810. bool TemplateMatches =
  7811. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7812. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7813. AcceptableReturnType = true;
  7814. else {
  7815. // This could still instantiate to the right type, unless we know it
  7816. // names the wrong class template.
  7817. auto *TD = SpecifiedName.getAsTemplateDecl();
  7818. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7819. !TemplateMatches);
  7820. }
  7821. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7822. MightInstantiateToSpecialization = true;
  7823. }
  7824. if (!AcceptableReturnType) {
  7825. Diag(TSI->getTypeLoc().getBeginLoc(),
  7826. diag::err_deduction_guide_bad_trailing_return_type)
  7827. << GuidedTemplate << TSI->getType()
  7828. << MightInstantiateToSpecialization
  7829. << TSI->getTypeLoc().getSourceRange();
  7830. }
  7831. // Keep going to check that we don't have any inner declarator pieces (we
  7832. // could still have a function returning a pointer to a function).
  7833. FoundFunction = true;
  7834. }
  7835. if (D.isFunctionDefinition())
  7836. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7837. }
  7838. //===----------------------------------------------------------------------===//
  7839. // Namespace Handling
  7840. //===----------------------------------------------------------------------===//
  7841. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7842. /// reopened.
  7843. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7844. SourceLocation Loc,
  7845. IdentifierInfo *II, bool *IsInline,
  7846. NamespaceDecl *PrevNS) {
  7847. assert(*IsInline != PrevNS->isInline());
  7848. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7849. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7850. // inline namespaces, with the intention of bringing names into namespace std.
  7851. //
  7852. // We support this just well enough to get that case working; this is not
  7853. // sufficient to support reopening namespaces as inline in general.
  7854. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7855. S.getSourceManager().isInSystemHeader(Loc)) {
  7856. // Mark all prior declarations of the namespace as inline.
  7857. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7858. NS = NS->getPreviousDecl())
  7859. NS->setInline(*IsInline);
  7860. // Patch up the lookup table for the containing namespace. This isn't really
  7861. // correct, but it's good enough for this particular case.
  7862. for (auto *I : PrevNS->decls())
  7863. if (auto *ND = dyn_cast<NamedDecl>(I))
  7864. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7865. return;
  7866. }
  7867. if (PrevNS->isInline())
  7868. // The user probably just forgot the 'inline', so suggest that it
  7869. // be added back.
  7870. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7871. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7872. else
  7873. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7874. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7875. *IsInline = PrevNS->isInline();
  7876. }
  7877. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7878. /// definition.
  7879. Decl *Sema::ActOnStartNamespaceDef(
  7880. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7881. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7882. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7883. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7884. // For anonymous namespace, take the location of the left brace.
  7885. SourceLocation Loc = II ? IdentLoc : LBrace;
  7886. bool IsInline = InlineLoc.isValid();
  7887. bool IsInvalid = false;
  7888. bool IsStd = false;
  7889. bool AddToKnown = false;
  7890. Scope *DeclRegionScope = NamespcScope->getParent();
  7891. NamespaceDecl *PrevNS = nullptr;
  7892. if (II) {
  7893. // C++ [namespace.def]p2:
  7894. // The identifier in an original-namespace-definition shall not
  7895. // have been previously defined in the declarative region in
  7896. // which the original-namespace-definition appears. The
  7897. // identifier in an original-namespace-definition is the name of
  7898. // the namespace. Subsequently in that declarative region, it is
  7899. // treated as an original-namespace-name.
  7900. //
  7901. // Since namespace names are unique in their scope, and we don't
  7902. // look through using directives, just look for any ordinary names
  7903. // as if by qualified name lookup.
  7904. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7905. ForExternalRedeclaration);
  7906. LookupQualifiedName(R, CurContext->getRedeclContext());
  7907. NamedDecl *PrevDecl =
  7908. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7909. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7910. if (PrevNS) {
  7911. // This is an extended namespace definition.
  7912. if (IsInline != PrevNS->isInline())
  7913. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7914. &IsInline, PrevNS);
  7915. } else if (PrevDecl) {
  7916. // This is an invalid name redefinition.
  7917. Diag(Loc, diag::err_redefinition_different_kind)
  7918. << II;
  7919. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7920. IsInvalid = true;
  7921. // Continue on to push Namespc as current DeclContext and return it.
  7922. } else if (II->isStr("std") &&
  7923. CurContext->getRedeclContext()->isTranslationUnit()) {
  7924. // This is the first "real" definition of the namespace "std", so update
  7925. // our cache of the "std" namespace to point at this definition.
  7926. PrevNS = getStdNamespace();
  7927. IsStd = true;
  7928. AddToKnown = !IsInline;
  7929. } else {
  7930. // We've seen this namespace for the first time.
  7931. AddToKnown = !IsInline;
  7932. }
  7933. } else {
  7934. // Anonymous namespaces.
  7935. // Determine whether the parent already has an anonymous namespace.
  7936. DeclContext *Parent = CurContext->getRedeclContext();
  7937. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7938. PrevNS = TU->getAnonymousNamespace();
  7939. } else {
  7940. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  7941. PrevNS = ND->getAnonymousNamespace();
  7942. }
  7943. if (PrevNS && IsInline != PrevNS->isInline())
  7944. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  7945. &IsInline, PrevNS);
  7946. }
  7947. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  7948. StartLoc, Loc, II, PrevNS);
  7949. if (IsInvalid)
  7950. Namespc->setInvalidDecl();
  7951. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  7952. AddPragmaAttributes(DeclRegionScope, Namespc);
  7953. // FIXME: Should we be merging attributes?
  7954. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  7955. PushNamespaceVisibilityAttr(Attr, Loc);
  7956. if (IsStd)
  7957. StdNamespace = Namespc;
  7958. if (AddToKnown)
  7959. KnownNamespaces[Namespc] = false;
  7960. if (II) {
  7961. PushOnScopeChains(Namespc, DeclRegionScope);
  7962. } else {
  7963. // Link the anonymous namespace into its parent.
  7964. DeclContext *Parent = CurContext->getRedeclContext();
  7965. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7966. TU->setAnonymousNamespace(Namespc);
  7967. } else {
  7968. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  7969. }
  7970. CurContext->addDecl(Namespc);
  7971. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  7972. // behaves as if it were replaced by
  7973. // namespace unique { /* empty body */ }
  7974. // using namespace unique;
  7975. // namespace unique { namespace-body }
  7976. // where all occurrences of 'unique' in a translation unit are
  7977. // replaced by the same identifier and this identifier differs
  7978. // from all other identifiers in the entire program.
  7979. // We just create the namespace with an empty name and then add an
  7980. // implicit using declaration, just like the standard suggests.
  7981. //
  7982. // CodeGen enforces the "universally unique" aspect by giving all
  7983. // declarations semantically contained within an anonymous
  7984. // namespace internal linkage.
  7985. if (!PrevNS) {
  7986. UD = UsingDirectiveDecl::Create(Context, Parent,
  7987. /* 'using' */ LBrace,
  7988. /* 'namespace' */ SourceLocation(),
  7989. /* qualifier */ NestedNameSpecifierLoc(),
  7990. /* identifier */ SourceLocation(),
  7991. Namespc,
  7992. /* Ancestor */ Parent);
  7993. UD->setImplicit();
  7994. Parent->addDecl(UD);
  7995. }
  7996. }
  7997. ActOnDocumentableDecl(Namespc);
  7998. // Although we could have an invalid decl (i.e. the namespace name is a
  7999. // redefinition), push it as current DeclContext and try to continue parsing.
  8000. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  8001. // for the namespace has the declarations that showed up in that particular
  8002. // namespace definition.
  8003. PushDeclContext(NamespcScope, Namespc);
  8004. return Namespc;
  8005. }
  8006. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  8007. /// is a namespace alias, returns the namespace it points to.
  8008. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  8009. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  8010. return AD->getNamespace();
  8011. return dyn_cast_or_null<NamespaceDecl>(D);
  8012. }
  8013. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  8014. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  8015. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  8016. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  8017. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  8018. Namespc->setRBraceLoc(RBrace);
  8019. PopDeclContext();
  8020. if (Namespc->hasAttr<VisibilityAttr>())
  8021. PopPragmaVisibility(true, RBrace);
  8022. // If this namespace contains an export-declaration, export it now.
  8023. if (DeferredExportedNamespaces.erase(Namespc))
  8024. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  8025. }
  8026. CXXRecordDecl *Sema::getStdBadAlloc() const {
  8027. return cast_or_null<CXXRecordDecl>(
  8028. StdBadAlloc.get(Context.getExternalSource()));
  8029. }
  8030. EnumDecl *Sema::getStdAlignValT() const {
  8031. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  8032. }
  8033. NamespaceDecl *Sema::getStdNamespace() const {
  8034. return cast_or_null<NamespaceDecl>(
  8035. StdNamespace.get(Context.getExternalSource()));
  8036. }
  8037. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  8038. if (!StdExperimentalNamespaceCache) {
  8039. if (auto Std = getStdNamespace()) {
  8040. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  8041. SourceLocation(), LookupNamespaceName);
  8042. if (!LookupQualifiedName(Result, Std) ||
  8043. !(StdExperimentalNamespaceCache =
  8044. Result.getAsSingle<NamespaceDecl>()))
  8045. Result.suppressDiagnostics();
  8046. }
  8047. }
  8048. return StdExperimentalNamespaceCache;
  8049. }
  8050. namespace {
  8051. enum UnsupportedSTLSelect {
  8052. USS_InvalidMember,
  8053. USS_MissingMember,
  8054. USS_NonTrivial,
  8055. USS_Other
  8056. };
  8057. struct InvalidSTLDiagnoser {
  8058. Sema &S;
  8059. SourceLocation Loc;
  8060. QualType TyForDiags;
  8061. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  8062. const VarDecl *VD = nullptr) {
  8063. {
  8064. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  8065. << TyForDiags << ((int)Sel);
  8066. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  8067. assert(!Name.empty());
  8068. D << Name;
  8069. }
  8070. }
  8071. if (Sel == USS_InvalidMember) {
  8072. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  8073. << VD << VD->getSourceRange();
  8074. }
  8075. return QualType();
  8076. }
  8077. };
  8078. } // namespace
  8079. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  8080. SourceLocation Loc) {
  8081. assert(getLangOpts().CPlusPlus &&
  8082. "Looking for comparison category type outside of C++.");
  8083. // Check if we've already successfully checked the comparison category type
  8084. // before. If so, skip checking it again.
  8085. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  8086. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  8087. return Info->getType();
  8088. // If lookup failed
  8089. if (!Info) {
  8090. std::string NameForDiags = "std::";
  8091. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  8092. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  8093. << NameForDiags;
  8094. return QualType();
  8095. }
  8096. assert(Info->Kind == Kind);
  8097. assert(Info->Record);
  8098. // Update the Record decl in case we encountered a forward declaration on our
  8099. // first pass. FIXME: This is a bit of a hack.
  8100. if (Info->Record->hasDefinition())
  8101. Info->Record = Info->Record->getDefinition();
  8102. // Use an elaborated type for diagnostics which has a name containing the
  8103. // prepended 'std' namespace but not any inline namespace names.
  8104. QualType TyForDiags = [&]() {
  8105. auto *NNS =
  8106. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  8107. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  8108. }();
  8109. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  8110. return QualType();
  8111. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  8112. if (!Info->Record->isTriviallyCopyable())
  8113. return UnsupportedSTLError(USS_NonTrivial);
  8114. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  8115. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  8116. // Tolerate empty base classes.
  8117. if (Base->isEmpty())
  8118. continue;
  8119. // Reject STL implementations which have at least one non-empty base.
  8120. return UnsupportedSTLError();
  8121. }
  8122. // Check that the STL has implemented the types using a single integer field.
  8123. // This expectation allows better codegen for builtin operators. We require:
  8124. // (1) The class has exactly one field.
  8125. // (2) The field is an integral or enumeration type.
  8126. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  8127. if (std::distance(FIt, FEnd) != 1 ||
  8128. !FIt->getType()->isIntegralOrEnumerationType()) {
  8129. return UnsupportedSTLError();
  8130. }
  8131. // Build each of the require values and store them in Info.
  8132. for (ComparisonCategoryResult CCR :
  8133. ComparisonCategories::getPossibleResultsForType(Kind)) {
  8134. StringRef MemName = ComparisonCategories::getResultString(CCR);
  8135. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  8136. if (!ValInfo)
  8137. return UnsupportedSTLError(USS_MissingMember, MemName);
  8138. VarDecl *VD = ValInfo->VD;
  8139. assert(VD && "should not be null!");
  8140. // Attempt to diagnose reasons why the STL definition of this type
  8141. // might be foobar, including it failing to be a constant expression.
  8142. // TODO Handle more ways the lookup or result can be invalid.
  8143. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  8144. !VD->checkInitIsICE())
  8145. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  8146. // Attempt to evaluate the var decl as a constant expression and extract
  8147. // the value of its first field as a ICE. If this fails, the STL
  8148. // implementation is not supported.
  8149. if (!ValInfo->hasValidIntValue())
  8150. return UnsupportedSTLError();
  8151. MarkVariableReferenced(Loc, VD);
  8152. }
  8153. // We've successfully built the required types and expressions. Update
  8154. // the cache and return the newly cached value.
  8155. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  8156. return Info->getType();
  8157. }
  8158. /// Retrieve the special "std" namespace, which may require us to
  8159. /// implicitly define the namespace.
  8160. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  8161. if (!StdNamespace) {
  8162. // The "std" namespace has not yet been defined, so build one implicitly.
  8163. StdNamespace = NamespaceDecl::Create(Context,
  8164. Context.getTranslationUnitDecl(),
  8165. /*Inline=*/false,
  8166. SourceLocation(), SourceLocation(),
  8167. &PP.getIdentifierTable().get("std"),
  8168. /*PrevDecl=*/nullptr);
  8169. getStdNamespace()->setImplicit(true);
  8170. }
  8171. return getStdNamespace();
  8172. }
  8173. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  8174. assert(getLangOpts().CPlusPlus &&
  8175. "Looking for std::initializer_list outside of C++.");
  8176. // We're looking for implicit instantiations of
  8177. // template <typename E> class std::initializer_list.
  8178. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  8179. return false;
  8180. ClassTemplateDecl *Template = nullptr;
  8181. const TemplateArgument *Arguments = nullptr;
  8182. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  8183. ClassTemplateSpecializationDecl *Specialization =
  8184. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8185. if (!Specialization)
  8186. return false;
  8187. Template = Specialization->getSpecializedTemplate();
  8188. Arguments = Specialization->getTemplateArgs().data();
  8189. } else if (const TemplateSpecializationType *TST =
  8190. Ty->getAs<TemplateSpecializationType>()) {
  8191. Template = dyn_cast_or_null<ClassTemplateDecl>(
  8192. TST->getTemplateName().getAsTemplateDecl());
  8193. Arguments = TST->getArgs();
  8194. }
  8195. if (!Template)
  8196. return false;
  8197. if (!StdInitializerList) {
  8198. // Haven't recognized std::initializer_list yet, maybe this is it.
  8199. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  8200. if (TemplateClass->getIdentifier() !=
  8201. &PP.getIdentifierTable().get("initializer_list") ||
  8202. !getStdNamespace()->InEnclosingNamespaceSetOf(
  8203. TemplateClass->getDeclContext()))
  8204. return false;
  8205. // This is a template called std::initializer_list, but is it the right
  8206. // template?
  8207. TemplateParameterList *Params = Template->getTemplateParameters();
  8208. if (Params->getMinRequiredArguments() != 1)
  8209. return false;
  8210. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  8211. return false;
  8212. // It's the right template.
  8213. StdInitializerList = Template;
  8214. }
  8215. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  8216. return false;
  8217. // This is an instance of std::initializer_list. Find the argument type.
  8218. if (Element)
  8219. *Element = Arguments[0].getAsType();
  8220. return true;
  8221. }
  8222. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  8223. NamespaceDecl *Std = S.getStdNamespace();
  8224. if (!Std) {
  8225. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8226. return nullptr;
  8227. }
  8228. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  8229. Loc, Sema::LookupOrdinaryName);
  8230. if (!S.LookupQualifiedName(Result, Std)) {
  8231. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8232. return nullptr;
  8233. }
  8234. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  8235. if (!Template) {
  8236. Result.suppressDiagnostics();
  8237. // We found something weird. Complain about the first thing we found.
  8238. NamedDecl *Found = *Result.begin();
  8239. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  8240. return nullptr;
  8241. }
  8242. // We found some template called std::initializer_list. Now verify that it's
  8243. // correct.
  8244. TemplateParameterList *Params = Template->getTemplateParameters();
  8245. if (Params->getMinRequiredArguments() != 1 ||
  8246. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  8247. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  8248. return nullptr;
  8249. }
  8250. return Template;
  8251. }
  8252. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  8253. if (!StdInitializerList) {
  8254. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8255. if (!StdInitializerList)
  8256. return QualType();
  8257. }
  8258. TemplateArgumentListInfo Args(Loc, Loc);
  8259. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8260. Context.getTrivialTypeSourceInfo(Element,
  8261. Loc)));
  8262. return Context.getCanonicalType(
  8263. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8264. }
  8265. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8266. // C++ [dcl.init.list]p2:
  8267. // A constructor is an initializer-list constructor if its first parameter
  8268. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8269. // std::initializer_list<E> for some type E, and either there are no other
  8270. // parameters or else all other parameters have default arguments.
  8271. if (Ctor->getNumParams() < 1 ||
  8272. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8273. return false;
  8274. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8275. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8276. ArgType = RT->getPointeeType().getUnqualifiedType();
  8277. return isStdInitializerList(ArgType, nullptr);
  8278. }
  8279. /// Determine whether a using statement is in a context where it will be
  8280. /// apply in all contexts.
  8281. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8282. switch (CurContext->getDeclKind()) {
  8283. case Decl::TranslationUnit:
  8284. return true;
  8285. case Decl::LinkageSpec:
  8286. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8287. default:
  8288. return false;
  8289. }
  8290. }
  8291. namespace {
  8292. // Callback to only accept typo corrections that are namespaces.
  8293. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  8294. public:
  8295. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8296. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8297. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8298. return false;
  8299. }
  8300. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8301. return std::make_unique<NamespaceValidatorCCC>(*this);
  8302. }
  8303. };
  8304. }
  8305. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8306. CXXScopeSpec &SS,
  8307. SourceLocation IdentLoc,
  8308. IdentifierInfo *Ident) {
  8309. R.clear();
  8310. NamespaceValidatorCCC CCC{};
  8311. if (TypoCorrection Corrected =
  8312. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  8313. Sema::CTK_ErrorRecovery)) {
  8314. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8315. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8316. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8317. Ident->getName().equals(CorrectedStr);
  8318. S.diagnoseTypo(Corrected,
  8319. S.PDiag(diag::err_using_directive_member_suggest)
  8320. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8321. S.PDiag(diag::note_namespace_defined_here));
  8322. } else {
  8323. S.diagnoseTypo(Corrected,
  8324. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8325. S.PDiag(diag::note_namespace_defined_here));
  8326. }
  8327. R.addDecl(Corrected.getFoundDecl());
  8328. return true;
  8329. }
  8330. return false;
  8331. }
  8332. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8333. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8334. SourceLocation IdentLoc,
  8335. IdentifierInfo *NamespcName,
  8336. const ParsedAttributesView &AttrList) {
  8337. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8338. assert(NamespcName && "Invalid NamespcName.");
  8339. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8340. // This can only happen along a recovery path.
  8341. while (S->isTemplateParamScope())
  8342. S = S->getParent();
  8343. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8344. UsingDirectiveDecl *UDir = nullptr;
  8345. NestedNameSpecifier *Qualifier = nullptr;
  8346. if (SS.isSet())
  8347. Qualifier = SS.getScopeRep();
  8348. // Lookup namespace name.
  8349. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8350. LookupParsedName(R, S, &SS);
  8351. if (R.isAmbiguous())
  8352. return nullptr;
  8353. if (R.empty()) {
  8354. R.clear();
  8355. // Allow "using namespace std;" or "using namespace ::std;" even if
  8356. // "std" hasn't been defined yet, for GCC compatibility.
  8357. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8358. NamespcName->isStr("std")) {
  8359. Diag(IdentLoc, diag::ext_using_undefined_std);
  8360. R.addDecl(getOrCreateStdNamespace());
  8361. R.resolveKind();
  8362. }
  8363. // Otherwise, attempt typo correction.
  8364. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8365. }
  8366. if (!R.empty()) {
  8367. NamedDecl *Named = R.getRepresentativeDecl();
  8368. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8369. assert(NS && "expected namespace decl");
  8370. // The use of a nested name specifier may trigger deprecation warnings.
  8371. DiagnoseUseOfDecl(Named, IdentLoc);
  8372. // C++ [namespace.udir]p1:
  8373. // A using-directive specifies that the names in the nominated
  8374. // namespace can be used in the scope in which the
  8375. // using-directive appears after the using-directive. During
  8376. // unqualified name lookup (3.4.1), the names appear as if they
  8377. // were declared in the nearest enclosing namespace which
  8378. // contains both the using-directive and the nominated
  8379. // namespace. [Note: in this context, "contains" means "contains
  8380. // directly or indirectly". ]
  8381. // Find enclosing context containing both using-directive and
  8382. // nominated namespace.
  8383. DeclContext *CommonAncestor = NS;
  8384. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8385. CommonAncestor = CommonAncestor->getParent();
  8386. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8387. SS.getWithLocInContext(Context),
  8388. IdentLoc, Named, CommonAncestor);
  8389. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8390. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8391. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8392. }
  8393. PushUsingDirective(S, UDir);
  8394. } else {
  8395. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8396. }
  8397. if (UDir)
  8398. ProcessDeclAttributeList(S, UDir, AttrList);
  8399. return UDir;
  8400. }
  8401. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8402. // If the scope has an associated entity and the using directive is at
  8403. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8404. // its lookup structure so qualified name lookup can find it.
  8405. DeclContext *Ctx = S->getEntity();
  8406. if (Ctx && !Ctx->isFunctionOrMethod())
  8407. Ctx->addDecl(UDir);
  8408. else
  8409. // Otherwise, it is at block scope. The using-directives will affect lookup
  8410. // only to the end of the scope.
  8411. S->PushUsingDirective(UDir);
  8412. }
  8413. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8414. SourceLocation UsingLoc,
  8415. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8416. UnqualifiedId &Name,
  8417. SourceLocation EllipsisLoc,
  8418. const ParsedAttributesView &AttrList) {
  8419. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8420. if (SS.isEmpty()) {
  8421. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8422. return nullptr;
  8423. }
  8424. switch (Name.getKind()) {
  8425. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8426. case UnqualifiedIdKind::IK_Identifier:
  8427. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8428. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8429. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8430. break;
  8431. case UnqualifiedIdKind::IK_ConstructorName:
  8432. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8433. // C++11 inheriting constructors.
  8434. Diag(Name.getBeginLoc(),
  8435. getLangOpts().CPlusPlus11
  8436. ? diag::warn_cxx98_compat_using_decl_constructor
  8437. : diag::err_using_decl_constructor)
  8438. << SS.getRange();
  8439. if (getLangOpts().CPlusPlus11) break;
  8440. return nullptr;
  8441. case UnqualifiedIdKind::IK_DestructorName:
  8442. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8443. return nullptr;
  8444. case UnqualifiedIdKind::IK_TemplateId:
  8445. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8446. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8447. return nullptr;
  8448. case UnqualifiedIdKind::IK_DeductionGuideName:
  8449. llvm_unreachable("cannot parse qualified deduction guide name");
  8450. }
  8451. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8452. DeclarationName TargetName = TargetNameInfo.getName();
  8453. if (!TargetName)
  8454. return nullptr;
  8455. // Warn about access declarations.
  8456. if (UsingLoc.isInvalid()) {
  8457. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8458. ? diag::err_access_decl
  8459. : diag::warn_access_decl_deprecated)
  8460. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8461. }
  8462. if (EllipsisLoc.isInvalid()) {
  8463. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8464. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8465. return nullptr;
  8466. } else {
  8467. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8468. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8469. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8470. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8471. EllipsisLoc = SourceLocation();
  8472. }
  8473. }
  8474. NamedDecl *UD =
  8475. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8476. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8477. /*IsInstantiation*/false);
  8478. if (UD)
  8479. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8480. return UD;
  8481. }
  8482. /// Determine whether a using declaration considers the given
  8483. /// declarations as "equivalent", e.g., if they are redeclarations of
  8484. /// the same entity or are both typedefs of the same type.
  8485. static bool
  8486. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8487. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8488. return true;
  8489. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8490. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8491. return Context.hasSameType(TD1->getUnderlyingType(),
  8492. TD2->getUnderlyingType());
  8493. return false;
  8494. }
  8495. /// Determines whether to create a using shadow decl for a particular
  8496. /// decl, given the set of decls existing prior to this using lookup.
  8497. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8498. const LookupResult &Previous,
  8499. UsingShadowDecl *&PrevShadow) {
  8500. // Diagnose finding a decl which is not from a base class of the
  8501. // current class. We do this now because there are cases where this
  8502. // function will silently decide not to build a shadow decl, which
  8503. // will pre-empt further diagnostics.
  8504. //
  8505. // We don't need to do this in C++11 because we do the check once on
  8506. // the qualifier.
  8507. //
  8508. // FIXME: diagnose the following if we care enough:
  8509. // struct A { int foo; };
  8510. // struct B : A { using A::foo; };
  8511. // template <class T> struct C : A {};
  8512. // template <class T> struct D : C<T> { using B::foo; } // <---
  8513. // This is invalid (during instantiation) in C++03 because B::foo
  8514. // resolves to the using decl in B, which is not a base class of D<T>.
  8515. // We can't diagnose it immediately because C<T> is an unknown
  8516. // specialization. The UsingShadowDecl in D<T> then points directly
  8517. // to A::foo, which will look well-formed when we instantiate.
  8518. // The right solution is to not collapse the shadow-decl chain.
  8519. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8520. DeclContext *OrigDC = Orig->getDeclContext();
  8521. // Handle enums and anonymous structs.
  8522. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8523. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8524. while (OrigRec->isAnonymousStructOrUnion())
  8525. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8526. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8527. if (OrigDC == CurContext) {
  8528. Diag(Using->getLocation(),
  8529. diag::err_using_decl_nested_name_specifier_is_current_class)
  8530. << Using->getQualifierLoc().getSourceRange();
  8531. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8532. Using->setInvalidDecl();
  8533. return true;
  8534. }
  8535. Diag(Using->getQualifierLoc().getBeginLoc(),
  8536. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8537. << Using->getQualifier()
  8538. << cast<CXXRecordDecl>(CurContext)
  8539. << Using->getQualifierLoc().getSourceRange();
  8540. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8541. Using->setInvalidDecl();
  8542. return true;
  8543. }
  8544. }
  8545. if (Previous.empty()) return false;
  8546. NamedDecl *Target = Orig;
  8547. if (isa<UsingShadowDecl>(Target))
  8548. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8549. // If the target happens to be one of the previous declarations, we
  8550. // don't have a conflict.
  8551. //
  8552. // FIXME: but we might be increasing its access, in which case we
  8553. // should redeclare it.
  8554. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8555. bool FoundEquivalentDecl = false;
  8556. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8557. I != E; ++I) {
  8558. NamedDecl *D = (*I)->getUnderlyingDecl();
  8559. // We can have UsingDecls in our Previous results because we use the same
  8560. // LookupResult for checking whether the UsingDecl itself is a valid
  8561. // redeclaration.
  8562. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8563. continue;
  8564. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8565. // C++ [class.mem]p19:
  8566. // If T is the name of a class, then [every named member other than
  8567. // a non-static data member] shall have a name different from T
  8568. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8569. !isa<IndirectFieldDecl>(Target) &&
  8570. !isa<UnresolvedUsingValueDecl>(Target) &&
  8571. DiagnoseClassNameShadow(
  8572. CurContext,
  8573. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8574. return true;
  8575. }
  8576. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8577. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8578. PrevShadow = Shadow;
  8579. FoundEquivalentDecl = true;
  8580. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8581. // We don't conflict with an existing using shadow decl of an equivalent
  8582. // declaration, but we're not a redeclaration of it.
  8583. FoundEquivalentDecl = true;
  8584. }
  8585. if (isVisible(D))
  8586. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8587. }
  8588. if (FoundEquivalentDecl)
  8589. return false;
  8590. if (FunctionDecl *FD = Target->getAsFunction()) {
  8591. NamedDecl *OldDecl = nullptr;
  8592. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8593. /*IsForUsingDecl*/ true)) {
  8594. case Ovl_Overload:
  8595. return false;
  8596. case Ovl_NonFunction:
  8597. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8598. break;
  8599. // We found a decl with the exact signature.
  8600. case Ovl_Match:
  8601. // If we're in a record, we want to hide the target, so we
  8602. // return true (without a diagnostic) to tell the caller not to
  8603. // build a shadow decl.
  8604. if (CurContext->isRecord())
  8605. return true;
  8606. // If we're not in a record, this is an error.
  8607. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8608. break;
  8609. }
  8610. Diag(Target->getLocation(), diag::note_using_decl_target);
  8611. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8612. Using->setInvalidDecl();
  8613. return true;
  8614. }
  8615. // Target is not a function.
  8616. if (isa<TagDecl>(Target)) {
  8617. // No conflict between a tag and a non-tag.
  8618. if (!Tag) return false;
  8619. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8620. Diag(Target->getLocation(), diag::note_using_decl_target);
  8621. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8622. Using->setInvalidDecl();
  8623. return true;
  8624. }
  8625. // No conflict between a tag and a non-tag.
  8626. if (!NonTag) return false;
  8627. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8628. Diag(Target->getLocation(), diag::note_using_decl_target);
  8629. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8630. Using->setInvalidDecl();
  8631. return true;
  8632. }
  8633. /// Determine whether a direct base class is a virtual base class.
  8634. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8635. if (!Derived->getNumVBases())
  8636. return false;
  8637. for (auto &B : Derived->bases())
  8638. if (B.getType()->getAsCXXRecordDecl() == Base)
  8639. return B.isVirtual();
  8640. llvm_unreachable("not a direct base class");
  8641. }
  8642. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8643. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8644. UsingDecl *UD,
  8645. NamedDecl *Orig,
  8646. UsingShadowDecl *PrevDecl) {
  8647. // If we resolved to another shadow declaration, just coalesce them.
  8648. NamedDecl *Target = Orig;
  8649. if (isa<UsingShadowDecl>(Target)) {
  8650. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8651. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8652. }
  8653. NamedDecl *NonTemplateTarget = Target;
  8654. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8655. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8656. UsingShadowDecl *Shadow;
  8657. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8658. bool IsVirtualBase =
  8659. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8660. UD->getQualifier()->getAsRecordDecl());
  8661. Shadow = ConstructorUsingShadowDecl::Create(
  8662. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8663. } else {
  8664. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8665. Target);
  8666. }
  8667. UD->addShadowDecl(Shadow);
  8668. Shadow->setAccess(UD->getAccess());
  8669. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8670. Shadow->setInvalidDecl();
  8671. Shadow->setPreviousDecl(PrevDecl);
  8672. if (S)
  8673. PushOnScopeChains(Shadow, S);
  8674. else
  8675. CurContext->addDecl(Shadow);
  8676. return Shadow;
  8677. }
  8678. /// Hides a using shadow declaration. This is required by the current
  8679. /// using-decl implementation when a resolvable using declaration in a
  8680. /// class is followed by a declaration which would hide or override
  8681. /// one or more of the using decl's targets; for example:
  8682. ///
  8683. /// struct Base { void foo(int); };
  8684. /// struct Derived : Base {
  8685. /// using Base::foo;
  8686. /// void foo(int);
  8687. /// };
  8688. ///
  8689. /// The governing language is C++03 [namespace.udecl]p12:
  8690. ///
  8691. /// When a using-declaration brings names from a base class into a
  8692. /// derived class scope, member functions in the derived class
  8693. /// override and/or hide member functions with the same name and
  8694. /// parameter types in a base class (rather than conflicting).
  8695. ///
  8696. /// There are two ways to implement this:
  8697. /// (1) optimistically create shadow decls when they're not hidden
  8698. /// by existing declarations, or
  8699. /// (2) don't create any shadow decls (or at least don't make them
  8700. /// visible) until we've fully parsed/instantiated the class.
  8701. /// The problem with (1) is that we might have to retroactively remove
  8702. /// a shadow decl, which requires several O(n) operations because the
  8703. /// decl structures are (very reasonably) not designed for removal.
  8704. /// (2) avoids this but is very fiddly and phase-dependent.
  8705. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8706. if (Shadow->getDeclName().getNameKind() ==
  8707. DeclarationName::CXXConversionFunctionName)
  8708. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8709. // Remove it from the DeclContext...
  8710. Shadow->getDeclContext()->removeDecl(Shadow);
  8711. // ...and the scope, if applicable...
  8712. if (S) {
  8713. S->RemoveDecl(Shadow);
  8714. IdResolver.RemoveDecl(Shadow);
  8715. }
  8716. // ...and the using decl.
  8717. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8718. // TODO: complain somehow if Shadow was used. It shouldn't
  8719. // be possible for this to happen, because...?
  8720. }
  8721. /// Find the base specifier for a base class with the given type.
  8722. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8723. QualType DesiredBase,
  8724. bool &AnyDependentBases) {
  8725. // Check whether the named type is a direct base class.
  8726. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
  8727. .getUnqualifiedType();
  8728. for (auto &Base : Derived->bases()) {
  8729. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8730. if (CanonicalDesiredBase == BaseType)
  8731. return &Base;
  8732. if (BaseType->isDependentType())
  8733. AnyDependentBases = true;
  8734. }
  8735. return nullptr;
  8736. }
  8737. namespace {
  8738. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  8739. public:
  8740. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8741. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8742. : HasTypenameKeyword(HasTypenameKeyword),
  8743. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8744. RequireMemberOf(RequireMemberOf) {}
  8745. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8746. NamedDecl *ND = Candidate.getCorrectionDecl();
  8747. // Keywords are not valid here.
  8748. if (!ND || isa<NamespaceDecl>(ND))
  8749. return false;
  8750. // Completely unqualified names are invalid for a 'using' declaration.
  8751. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8752. return false;
  8753. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8754. // reject.
  8755. if (RequireMemberOf) {
  8756. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8757. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8758. // No-one ever wants a using-declaration to name an injected-class-name
  8759. // of a base class, unless they're declaring an inheriting constructor.
  8760. ASTContext &Ctx = ND->getASTContext();
  8761. if (!Ctx.getLangOpts().CPlusPlus11)
  8762. return false;
  8763. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8764. // Check that the injected-class-name is named as a member of its own
  8765. // type; we don't want to suggest 'using Derived::Base;', since that
  8766. // means something else.
  8767. NestedNameSpecifier *Specifier =
  8768. Candidate.WillReplaceSpecifier()
  8769. ? Candidate.getCorrectionSpecifier()
  8770. : OldNNS;
  8771. if (!Specifier->getAsType() ||
  8772. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8773. return false;
  8774. // Check that this inheriting constructor declaration actually names a
  8775. // direct base class of the current class.
  8776. bool AnyDependentBases = false;
  8777. if (!findDirectBaseWithType(RequireMemberOf,
  8778. Ctx.getRecordType(FoundRecord),
  8779. AnyDependentBases) &&
  8780. !AnyDependentBases)
  8781. return false;
  8782. } else {
  8783. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8784. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8785. return false;
  8786. // FIXME: Check that the base class member is accessible?
  8787. }
  8788. } else {
  8789. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8790. if (FoundRecord && FoundRecord->isInjectedClassName())
  8791. return false;
  8792. }
  8793. if (isa<TypeDecl>(ND))
  8794. return HasTypenameKeyword || !IsInstantiation;
  8795. return !HasTypenameKeyword;
  8796. }
  8797. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8798. return std::make_unique<UsingValidatorCCC>(*this);
  8799. }
  8800. private:
  8801. bool HasTypenameKeyword;
  8802. bool IsInstantiation;
  8803. NestedNameSpecifier *OldNNS;
  8804. CXXRecordDecl *RequireMemberOf;
  8805. };
  8806. } // end anonymous namespace
  8807. /// Builds a using declaration.
  8808. ///
  8809. /// \param IsInstantiation - Whether this call arises from an
  8810. /// instantiation of an unresolved using declaration. We treat
  8811. /// the lookup differently for these declarations.
  8812. NamedDecl *Sema::BuildUsingDeclaration(
  8813. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8814. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8815. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8816. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8817. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8818. SourceLocation IdentLoc = NameInfo.getLoc();
  8819. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8820. // FIXME: We ignore attributes for now.
  8821. // For an inheriting constructor declaration, the name of the using
  8822. // declaration is the name of a constructor in this class, not in the
  8823. // base class.
  8824. DeclarationNameInfo UsingName = NameInfo;
  8825. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8826. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8827. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8828. Context.getCanonicalType(Context.getRecordType(RD))));
  8829. // Do the redeclaration lookup in the current scope.
  8830. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8831. ForVisibleRedeclaration);
  8832. Previous.setHideTags(false);
  8833. if (S) {
  8834. LookupName(Previous, S);
  8835. // It is really dumb that we have to do this.
  8836. LookupResult::Filter F = Previous.makeFilter();
  8837. while (F.hasNext()) {
  8838. NamedDecl *D = F.next();
  8839. if (!isDeclInScope(D, CurContext, S))
  8840. F.erase();
  8841. // If we found a local extern declaration that's not ordinarily visible,
  8842. // and this declaration is being added to a non-block scope, ignore it.
  8843. // We're only checking for scope conflicts here, not also for violations
  8844. // of the linkage rules.
  8845. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8846. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8847. F.erase();
  8848. }
  8849. F.done();
  8850. } else {
  8851. assert(IsInstantiation && "no scope in non-instantiation");
  8852. if (CurContext->isRecord())
  8853. LookupQualifiedName(Previous, CurContext);
  8854. else {
  8855. // No redeclaration check is needed here; in non-member contexts we
  8856. // diagnosed all possible conflicts with other using-declarations when
  8857. // building the template:
  8858. //
  8859. // For a dependent non-type using declaration, the only valid case is
  8860. // if we instantiate to a single enumerator. We check for conflicts
  8861. // between shadow declarations we introduce, and we check in the template
  8862. // definition for conflicts between a non-type using declaration and any
  8863. // other declaration, which together covers all cases.
  8864. //
  8865. // A dependent typename using declaration will never successfully
  8866. // instantiate, since it will always name a class member, so we reject
  8867. // that in the template definition.
  8868. }
  8869. }
  8870. // Check for invalid redeclarations.
  8871. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8872. SS, IdentLoc, Previous))
  8873. return nullptr;
  8874. // Check for bad qualifiers.
  8875. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8876. IdentLoc))
  8877. return nullptr;
  8878. DeclContext *LookupContext = computeDeclContext(SS);
  8879. NamedDecl *D;
  8880. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8881. if (!LookupContext || EllipsisLoc.isValid()) {
  8882. if (HasTypenameKeyword) {
  8883. // FIXME: not all declaration name kinds are legal here
  8884. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8885. UsingLoc, TypenameLoc,
  8886. QualifierLoc,
  8887. IdentLoc, NameInfo.getName(),
  8888. EllipsisLoc);
  8889. } else {
  8890. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8891. QualifierLoc, NameInfo, EllipsisLoc);
  8892. }
  8893. D->setAccess(AS);
  8894. CurContext->addDecl(D);
  8895. return D;
  8896. }
  8897. auto Build = [&](bool Invalid) {
  8898. UsingDecl *UD =
  8899. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8900. UsingName, HasTypenameKeyword);
  8901. UD->setAccess(AS);
  8902. CurContext->addDecl(UD);
  8903. UD->setInvalidDecl(Invalid);
  8904. return UD;
  8905. };
  8906. auto BuildInvalid = [&]{ return Build(true); };
  8907. auto BuildValid = [&]{ return Build(false); };
  8908. if (RequireCompleteDeclContext(SS, LookupContext))
  8909. return BuildInvalid();
  8910. // Look up the target name.
  8911. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8912. // Unlike most lookups, we don't always want to hide tag
  8913. // declarations: tag names are visible through the using declaration
  8914. // even if hidden by ordinary names, *except* in a dependent context
  8915. // where it's important for the sanity of two-phase lookup.
  8916. if (!IsInstantiation)
  8917. R.setHideTags(false);
  8918. // For the purposes of this lookup, we have a base object type
  8919. // equal to that of the current context.
  8920. if (CurContext->isRecord()) {
  8921. R.setBaseObjectType(
  8922. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8923. }
  8924. LookupQualifiedName(R, LookupContext);
  8925. // Try to correct typos if possible. If constructor name lookup finds no
  8926. // results, that means the named class has no explicit constructors, and we
  8927. // suppressed declaring implicit ones (probably because it's dependent or
  8928. // invalid).
  8929. if (R.empty() &&
  8930. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8931. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8932. // it will believe that glibc provides a ::gets in cases where it does not,
  8933. // and will try to pull it into namespace std with a using-declaration.
  8934. // Just ignore the using-declaration in that case.
  8935. auto *II = NameInfo.getName().getAsIdentifierInfo();
  8936. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  8937. CurContext->isStdNamespace() &&
  8938. isa<TranslationUnitDecl>(LookupContext) &&
  8939. getSourceManager().isInSystemHeader(UsingLoc))
  8940. return nullptr;
  8941. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  8942. dyn_cast<CXXRecordDecl>(CurContext));
  8943. if (TypoCorrection Corrected =
  8944. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  8945. CTK_ErrorRecovery)) {
  8946. // We reject candidates where DroppedSpecifier == true, hence the
  8947. // literal '0' below.
  8948. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  8949. << NameInfo.getName() << LookupContext << 0
  8950. << SS.getRange());
  8951. // If we picked a correction with no attached Decl we can't do anything
  8952. // useful with it, bail out.
  8953. NamedDecl *ND = Corrected.getCorrectionDecl();
  8954. if (!ND)
  8955. return BuildInvalid();
  8956. // If we corrected to an inheriting constructor, handle it as one.
  8957. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  8958. if (RD && RD->isInjectedClassName()) {
  8959. // The parent of the injected class name is the class itself.
  8960. RD = cast<CXXRecordDecl>(RD->getParent());
  8961. // Fix up the information we'll use to build the using declaration.
  8962. if (Corrected.WillReplaceSpecifier()) {
  8963. NestedNameSpecifierLocBuilder Builder;
  8964. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  8965. QualifierLoc.getSourceRange());
  8966. QualifierLoc = Builder.getWithLocInContext(Context);
  8967. }
  8968. // In this case, the name we introduce is the name of a derived class
  8969. // constructor.
  8970. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  8971. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8972. Context.getCanonicalType(Context.getRecordType(CurClass))));
  8973. UsingName.setNamedTypeInfo(nullptr);
  8974. for (auto *Ctor : LookupConstructors(RD))
  8975. R.addDecl(Ctor);
  8976. R.resolveKind();
  8977. } else {
  8978. // FIXME: Pick up all the declarations if we found an overloaded
  8979. // function.
  8980. UsingName.setName(ND->getDeclName());
  8981. R.addDecl(ND);
  8982. }
  8983. } else {
  8984. Diag(IdentLoc, diag::err_no_member)
  8985. << NameInfo.getName() << LookupContext << SS.getRange();
  8986. return BuildInvalid();
  8987. }
  8988. }
  8989. if (R.isAmbiguous())
  8990. return BuildInvalid();
  8991. if (HasTypenameKeyword) {
  8992. // If we asked for a typename and got a non-type decl, error out.
  8993. if (!R.getAsSingle<TypeDecl>()) {
  8994. Diag(IdentLoc, diag::err_using_typename_non_type);
  8995. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8996. Diag((*I)->getUnderlyingDecl()->getLocation(),
  8997. diag::note_using_decl_target);
  8998. return BuildInvalid();
  8999. }
  9000. } else {
  9001. // If we asked for a non-typename and we got a type, error out,
  9002. // but only if this is an instantiation of an unresolved using
  9003. // decl. Otherwise just silently find the type name.
  9004. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  9005. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  9006. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  9007. return BuildInvalid();
  9008. }
  9009. }
  9010. // C++14 [namespace.udecl]p6:
  9011. // A using-declaration shall not name a namespace.
  9012. if (R.getAsSingle<NamespaceDecl>()) {
  9013. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  9014. << SS.getRange();
  9015. return BuildInvalid();
  9016. }
  9017. // C++14 [namespace.udecl]p7:
  9018. // A using-declaration shall not name a scoped enumerator.
  9019. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  9020. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  9021. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  9022. << SS.getRange();
  9023. return BuildInvalid();
  9024. }
  9025. }
  9026. UsingDecl *UD = BuildValid();
  9027. // Some additional rules apply to inheriting constructors.
  9028. if (UsingName.getName().getNameKind() ==
  9029. DeclarationName::CXXConstructorName) {
  9030. // Suppress access diagnostics; the access check is instead performed at the
  9031. // point of use for an inheriting constructor.
  9032. R.suppressDiagnostics();
  9033. if (CheckInheritingConstructorUsingDecl(UD))
  9034. return UD;
  9035. }
  9036. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  9037. UsingShadowDecl *PrevDecl = nullptr;
  9038. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  9039. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  9040. }
  9041. return UD;
  9042. }
  9043. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  9044. ArrayRef<NamedDecl *> Expansions) {
  9045. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  9046. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  9047. isa<UsingPackDecl>(InstantiatedFrom));
  9048. auto *UPD =
  9049. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  9050. UPD->setAccess(InstantiatedFrom->getAccess());
  9051. CurContext->addDecl(UPD);
  9052. return UPD;
  9053. }
  9054. /// Additional checks for a using declaration referring to a constructor name.
  9055. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  9056. assert(!UD->hasTypename() && "expecting a constructor name");
  9057. const Type *SourceType = UD->getQualifier()->getAsType();
  9058. assert(SourceType &&
  9059. "Using decl naming constructor doesn't have type in scope spec.");
  9060. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  9061. // Check whether the named type is a direct base class.
  9062. bool AnyDependentBases = false;
  9063. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  9064. AnyDependentBases);
  9065. if (!Base && !AnyDependentBases) {
  9066. Diag(UD->getUsingLoc(),
  9067. diag::err_using_decl_constructor_not_in_direct_base)
  9068. << UD->getNameInfo().getSourceRange()
  9069. << QualType(SourceType, 0) << TargetClass;
  9070. UD->setInvalidDecl();
  9071. return true;
  9072. }
  9073. if (Base)
  9074. Base->setInheritConstructors();
  9075. return false;
  9076. }
  9077. /// Checks that the given using declaration is not an invalid
  9078. /// redeclaration. Note that this is checking only for the using decl
  9079. /// itself, not for any ill-formedness among the UsingShadowDecls.
  9080. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  9081. bool HasTypenameKeyword,
  9082. const CXXScopeSpec &SS,
  9083. SourceLocation NameLoc,
  9084. const LookupResult &Prev) {
  9085. NestedNameSpecifier *Qual = SS.getScopeRep();
  9086. // C++03 [namespace.udecl]p8:
  9087. // C++0x [namespace.udecl]p10:
  9088. // A using-declaration is a declaration and can therefore be used
  9089. // repeatedly where (and only where) multiple declarations are
  9090. // allowed.
  9091. //
  9092. // That's in non-member contexts.
  9093. if (!CurContext->getRedeclContext()->isRecord()) {
  9094. // A dependent qualifier outside a class can only ever resolve to an
  9095. // enumeration type. Therefore it conflicts with any other non-type
  9096. // declaration in the same scope.
  9097. // FIXME: How should we check for dependent type-type conflicts at block
  9098. // scope?
  9099. if (Qual->isDependent() && !HasTypenameKeyword) {
  9100. for (auto *D : Prev) {
  9101. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  9102. bool OldCouldBeEnumerator =
  9103. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  9104. Diag(NameLoc,
  9105. OldCouldBeEnumerator ? diag::err_redefinition
  9106. : diag::err_redefinition_different_kind)
  9107. << Prev.getLookupName();
  9108. Diag(D->getLocation(), diag::note_previous_definition);
  9109. return true;
  9110. }
  9111. }
  9112. }
  9113. return false;
  9114. }
  9115. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  9116. NamedDecl *D = *I;
  9117. bool DTypename;
  9118. NestedNameSpecifier *DQual;
  9119. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  9120. DTypename = UD->hasTypename();
  9121. DQual = UD->getQualifier();
  9122. } else if (UnresolvedUsingValueDecl *UD
  9123. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  9124. DTypename = false;
  9125. DQual = UD->getQualifier();
  9126. } else if (UnresolvedUsingTypenameDecl *UD
  9127. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  9128. DTypename = true;
  9129. DQual = UD->getQualifier();
  9130. } else continue;
  9131. // using decls differ if one says 'typename' and the other doesn't.
  9132. // FIXME: non-dependent using decls?
  9133. if (HasTypenameKeyword != DTypename) continue;
  9134. // using decls differ if they name different scopes (but note that
  9135. // template instantiation can cause this check to trigger when it
  9136. // didn't before instantiation).
  9137. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  9138. Context.getCanonicalNestedNameSpecifier(DQual))
  9139. continue;
  9140. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  9141. Diag(D->getLocation(), diag::note_using_decl) << 1;
  9142. return true;
  9143. }
  9144. return false;
  9145. }
  9146. /// Checks that the given nested-name qualifier used in a using decl
  9147. /// in the current context is appropriately related to the current
  9148. /// scope. If an error is found, diagnoses it and returns true.
  9149. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  9150. bool HasTypename,
  9151. const CXXScopeSpec &SS,
  9152. const DeclarationNameInfo &NameInfo,
  9153. SourceLocation NameLoc) {
  9154. DeclContext *NamedContext = computeDeclContext(SS);
  9155. if (!CurContext->isRecord()) {
  9156. // C++03 [namespace.udecl]p3:
  9157. // C++0x [namespace.udecl]p8:
  9158. // A using-declaration for a class member shall be a member-declaration.
  9159. // If we weren't able to compute a valid scope, it might validly be a
  9160. // dependent class scope or a dependent enumeration unscoped scope. If
  9161. // we have a 'typename' keyword, the scope must resolve to a class type.
  9162. if ((HasTypename && !NamedContext) ||
  9163. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  9164. auto *RD = NamedContext
  9165. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  9166. : nullptr;
  9167. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  9168. RD = nullptr;
  9169. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  9170. << SS.getRange();
  9171. // If we have a complete, non-dependent source type, try to suggest a
  9172. // way to get the same effect.
  9173. if (!RD)
  9174. return true;
  9175. // Find what this using-declaration was referring to.
  9176. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  9177. R.setHideTags(false);
  9178. R.suppressDiagnostics();
  9179. LookupQualifiedName(R, RD);
  9180. if (R.getAsSingle<TypeDecl>()) {
  9181. if (getLangOpts().CPlusPlus11) {
  9182. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  9183. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  9184. << 0 // alias declaration
  9185. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  9186. NameInfo.getName().getAsString() +
  9187. " = ");
  9188. } else {
  9189. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  9190. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  9191. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  9192. << 1 // typedef declaration
  9193. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  9194. << FixItHint::CreateInsertion(
  9195. InsertLoc, " " + NameInfo.getName().getAsString());
  9196. }
  9197. } else if (R.getAsSingle<VarDecl>()) {
  9198. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9199. // repeating the type of the static data member here.
  9200. FixItHint FixIt;
  9201. if (getLangOpts().CPlusPlus11) {
  9202. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9203. FixIt = FixItHint::CreateReplacement(
  9204. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  9205. }
  9206. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9207. << 2 // reference declaration
  9208. << FixIt;
  9209. } else if (R.getAsSingle<EnumConstantDecl>()) {
  9210. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9211. // repeating the type of the enumeration here, and we can't do so if
  9212. // the type is anonymous.
  9213. FixItHint FixIt;
  9214. if (getLangOpts().CPlusPlus11) {
  9215. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9216. FixIt = FixItHint::CreateReplacement(
  9217. UsingLoc,
  9218. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  9219. }
  9220. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9221. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  9222. << FixIt;
  9223. }
  9224. return true;
  9225. }
  9226. // Otherwise, this might be valid.
  9227. return false;
  9228. }
  9229. // The current scope is a record.
  9230. // If the named context is dependent, we can't decide much.
  9231. if (!NamedContext) {
  9232. // FIXME: in C++0x, we can diagnose if we can prove that the
  9233. // nested-name-specifier does not refer to a base class, which is
  9234. // still possible in some cases.
  9235. // Otherwise we have to conservatively report that things might be
  9236. // okay.
  9237. return false;
  9238. }
  9239. if (!NamedContext->isRecord()) {
  9240. // Ideally this would point at the last name in the specifier,
  9241. // but we don't have that level of source info.
  9242. Diag(SS.getRange().getBegin(),
  9243. diag::err_using_decl_nested_name_specifier_is_not_class)
  9244. << SS.getScopeRep() << SS.getRange();
  9245. return true;
  9246. }
  9247. if (!NamedContext->isDependentContext() &&
  9248. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  9249. return true;
  9250. if (getLangOpts().CPlusPlus11) {
  9251. // C++11 [namespace.udecl]p3:
  9252. // In a using-declaration used as a member-declaration, the
  9253. // nested-name-specifier shall name a base class of the class
  9254. // being defined.
  9255. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  9256. cast<CXXRecordDecl>(NamedContext))) {
  9257. if (CurContext == NamedContext) {
  9258. Diag(NameLoc,
  9259. diag::err_using_decl_nested_name_specifier_is_current_class)
  9260. << SS.getRange();
  9261. return true;
  9262. }
  9263. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9264. Diag(SS.getRange().getBegin(),
  9265. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9266. << SS.getScopeRep()
  9267. << cast<CXXRecordDecl>(CurContext)
  9268. << SS.getRange();
  9269. }
  9270. return true;
  9271. }
  9272. return false;
  9273. }
  9274. // C++03 [namespace.udecl]p4:
  9275. // A using-declaration used as a member-declaration shall refer
  9276. // to a member of a base class of the class being defined [etc.].
  9277. // Salient point: SS doesn't have to name a base class as long as
  9278. // lookup only finds members from base classes. Therefore we can
  9279. // diagnose here only if we can prove that that can't happen,
  9280. // i.e. if the class hierarchies provably don't intersect.
  9281. // TODO: it would be nice if "definitely valid" results were cached
  9282. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9283. // need to be repeated.
  9284. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9285. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9286. Bases.insert(Base);
  9287. return true;
  9288. };
  9289. // Collect all bases. Return false if we find a dependent base.
  9290. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9291. return false;
  9292. // Returns true if the base is dependent or is one of the accumulated base
  9293. // classes.
  9294. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9295. return !Bases.count(Base);
  9296. };
  9297. // Return false if the class has a dependent base or if it or one
  9298. // of its bases is present in the base set of the current context.
  9299. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9300. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9301. return false;
  9302. Diag(SS.getRange().getBegin(),
  9303. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9304. << SS.getScopeRep()
  9305. << cast<CXXRecordDecl>(CurContext)
  9306. << SS.getRange();
  9307. return true;
  9308. }
  9309. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9310. MultiTemplateParamsArg TemplateParamLists,
  9311. SourceLocation UsingLoc, UnqualifiedId &Name,
  9312. const ParsedAttributesView &AttrList,
  9313. TypeResult Type, Decl *DeclFromDeclSpec) {
  9314. // Skip up to the relevant declaration scope.
  9315. while (S->isTemplateParamScope())
  9316. S = S->getParent();
  9317. assert((S->getFlags() & Scope::DeclScope) &&
  9318. "got alias-declaration outside of declaration scope");
  9319. if (Type.isInvalid())
  9320. return nullptr;
  9321. bool Invalid = false;
  9322. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9323. TypeSourceInfo *TInfo = nullptr;
  9324. GetTypeFromParser(Type.get(), &TInfo);
  9325. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9326. return nullptr;
  9327. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9328. UPPC_DeclarationType)) {
  9329. Invalid = true;
  9330. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9331. TInfo->getTypeLoc().getBeginLoc());
  9332. }
  9333. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9334. TemplateParamLists.size()
  9335. ? forRedeclarationInCurContext()
  9336. : ForVisibleRedeclaration);
  9337. LookupName(Previous, S);
  9338. // Warn about shadowing the name of a template parameter.
  9339. if (Previous.isSingleResult() &&
  9340. Previous.getFoundDecl()->isTemplateParameter()) {
  9341. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9342. Previous.clear();
  9343. }
  9344. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9345. "name in alias declaration must be an identifier");
  9346. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9347. Name.StartLocation,
  9348. Name.Identifier, TInfo);
  9349. NewTD->setAccess(AS);
  9350. if (Invalid)
  9351. NewTD->setInvalidDecl();
  9352. ProcessDeclAttributeList(S, NewTD, AttrList);
  9353. AddPragmaAttributes(S, NewTD);
  9354. CheckTypedefForVariablyModifiedType(S, NewTD);
  9355. Invalid |= NewTD->isInvalidDecl();
  9356. bool Redeclaration = false;
  9357. NamedDecl *NewND;
  9358. if (TemplateParamLists.size()) {
  9359. TypeAliasTemplateDecl *OldDecl = nullptr;
  9360. TemplateParameterList *OldTemplateParams = nullptr;
  9361. if (TemplateParamLists.size() != 1) {
  9362. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9363. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9364. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9365. }
  9366. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9367. // Check that we can declare a template here.
  9368. if (CheckTemplateDeclScope(S, TemplateParams))
  9369. return nullptr;
  9370. // Only consider previous declarations in the same scope.
  9371. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9372. /*ExplicitInstantiationOrSpecialization*/false);
  9373. if (!Previous.empty()) {
  9374. Redeclaration = true;
  9375. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9376. if (!OldDecl && !Invalid) {
  9377. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9378. << Name.Identifier;
  9379. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9380. if (OldD->getLocation().isValid())
  9381. Diag(OldD->getLocation(), diag::note_previous_definition);
  9382. Invalid = true;
  9383. }
  9384. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9385. if (TemplateParameterListsAreEqual(TemplateParams,
  9386. OldDecl->getTemplateParameters(),
  9387. /*Complain=*/true,
  9388. TPL_TemplateMatch))
  9389. OldTemplateParams =
  9390. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9391. else
  9392. Invalid = true;
  9393. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9394. if (!Invalid &&
  9395. !Context.hasSameType(OldTD->getUnderlyingType(),
  9396. NewTD->getUnderlyingType())) {
  9397. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9398. // but we can't reasonably accept it.
  9399. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9400. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9401. if (OldTD->getLocation().isValid())
  9402. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9403. Invalid = true;
  9404. }
  9405. }
  9406. }
  9407. // Merge any previous default template arguments into our parameters,
  9408. // and check the parameter list.
  9409. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9410. TPC_TypeAliasTemplate))
  9411. return nullptr;
  9412. TypeAliasTemplateDecl *NewDecl =
  9413. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9414. Name.Identifier, TemplateParams,
  9415. NewTD);
  9416. NewTD->setDescribedAliasTemplate(NewDecl);
  9417. NewDecl->setAccess(AS);
  9418. if (Invalid)
  9419. NewDecl->setInvalidDecl();
  9420. else if (OldDecl) {
  9421. NewDecl->setPreviousDecl(OldDecl);
  9422. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9423. }
  9424. NewND = NewDecl;
  9425. } else {
  9426. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9427. setTagNameForLinkagePurposes(TD, NewTD);
  9428. handleTagNumbering(TD, S);
  9429. }
  9430. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9431. NewND = NewTD;
  9432. }
  9433. PushOnScopeChains(NewND, S);
  9434. ActOnDocumentableDecl(NewND);
  9435. return NewND;
  9436. }
  9437. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9438. SourceLocation AliasLoc,
  9439. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9440. SourceLocation IdentLoc,
  9441. IdentifierInfo *Ident) {
  9442. // Lookup the namespace name.
  9443. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9444. LookupParsedName(R, S, &SS);
  9445. if (R.isAmbiguous())
  9446. return nullptr;
  9447. if (R.empty()) {
  9448. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9449. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9450. return nullptr;
  9451. }
  9452. }
  9453. assert(!R.isAmbiguous() && !R.empty());
  9454. NamedDecl *ND = R.getRepresentativeDecl();
  9455. // Check if we have a previous declaration with the same name.
  9456. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9457. ForVisibleRedeclaration);
  9458. LookupName(PrevR, S);
  9459. // Check we're not shadowing a template parameter.
  9460. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9461. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9462. PrevR.clear();
  9463. }
  9464. // Filter out any other lookup result from an enclosing scope.
  9465. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9466. /*AllowInlineNamespace*/false);
  9467. // Find the previous declaration and check that we can redeclare it.
  9468. NamespaceAliasDecl *Prev = nullptr;
  9469. if (PrevR.isSingleResult()) {
  9470. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9471. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9472. // We already have an alias with the same name that points to the same
  9473. // namespace; check that it matches.
  9474. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9475. Prev = AD;
  9476. } else if (isVisible(PrevDecl)) {
  9477. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9478. << Alias;
  9479. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9480. << AD->getNamespace();
  9481. return nullptr;
  9482. }
  9483. } else if (isVisible(PrevDecl)) {
  9484. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9485. ? diag::err_redefinition
  9486. : diag::err_redefinition_different_kind;
  9487. Diag(AliasLoc, DiagID) << Alias;
  9488. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9489. return nullptr;
  9490. }
  9491. }
  9492. // The use of a nested name specifier may trigger deprecation warnings.
  9493. DiagnoseUseOfDecl(ND, IdentLoc);
  9494. NamespaceAliasDecl *AliasDecl =
  9495. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9496. Alias, SS.getWithLocInContext(Context),
  9497. IdentLoc, ND);
  9498. if (Prev)
  9499. AliasDecl->setPreviousDecl(Prev);
  9500. PushOnScopeChains(AliasDecl, S);
  9501. return AliasDecl;
  9502. }
  9503. namespace {
  9504. struct SpecialMemberExceptionSpecInfo
  9505. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9506. SourceLocation Loc;
  9507. Sema::ImplicitExceptionSpecification ExceptSpec;
  9508. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9509. Sema::CXXSpecialMember CSM,
  9510. Sema::InheritedConstructorInfo *ICI,
  9511. SourceLocation Loc)
  9512. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9513. bool visitBase(CXXBaseSpecifier *Base);
  9514. bool visitField(FieldDecl *FD);
  9515. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9516. unsigned Quals);
  9517. void visitSubobjectCall(Subobject Subobj,
  9518. Sema::SpecialMemberOverloadResult SMOR);
  9519. };
  9520. }
  9521. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9522. auto *RT = Base->getType()->getAs<RecordType>();
  9523. if (!RT)
  9524. return false;
  9525. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9526. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9527. if (auto *BaseCtor = SMOR.getMethod()) {
  9528. visitSubobjectCall(Base, BaseCtor);
  9529. return false;
  9530. }
  9531. visitClassSubobject(BaseClass, Base, 0);
  9532. return false;
  9533. }
  9534. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9535. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9536. Expr *E = FD->getInClassInitializer();
  9537. if (!E)
  9538. // FIXME: It's a little wasteful to build and throw away a
  9539. // CXXDefaultInitExpr here.
  9540. // FIXME: We should have a single context note pointing at Loc, and
  9541. // this location should be MD->getLocation() instead, since that's
  9542. // the location where we actually use the default init expression.
  9543. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9544. if (E)
  9545. ExceptSpec.CalledExpr(E);
  9546. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9547. ->getAs<RecordType>()) {
  9548. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9549. FD->getType().getCVRQualifiers());
  9550. }
  9551. return false;
  9552. }
  9553. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9554. Subobject Subobj,
  9555. unsigned Quals) {
  9556. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9557. bool IsMutable = Field && Field->isMutable();
  9558. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9559. }
  9560. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9561. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9562. // Note, if lookup fails, it doesn't matter what exception specification we
  9563. // choose because the special member will be deleted.
  9564. if (CXXMethodDecl *MD = SMOR.getMethod())
  9565. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9566. }
  9567. namespace {
  9568. /// RAII object to register a special member as being currently declared.
  9569. struct ComputingExceptionSpec {
  9570. Sema &S;
  9571. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9572. : S(S) {
  9573. Sema::CodeSynthesisContext Ctx;
  9574. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9575. Ctx.PointOfInstantiation = Loc;
  9576. Ctx.Entity = MD;
  9577. S.pushCodeSynthesisContext(Ctx);
  9578. }
  9579. ~ComputingExceptionSpec() {
  9580. S.popCodeSynthesisContext();
  9581. }
  9582. };
  9583. }
  9584. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  9585. llvm::APSInt Result;
  9586. ExprResult Converted = CheckConvertedConstantExpression(
  9587. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  9588. ExplicitSpec.setExpr(Converted.get());
  9589. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  9590. ExplicitSpec.setKind(Result.getBoolValue()
  9591. ? ExplicitSpecKind::ResolvedTrue
  9592. : ExplicitSpecKind::ResolvedFalse);
  9593. return true;
  9594. }
  9595. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  9596. return false;
  9597. }
  9598. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  9599. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  9600. if (!ExplicitExpr->isTypeDependent())
  9601. tryResolveExplicitSpecifier(ES);
  9602. return ES;
  9603. }
  9604. static Sema::ImplicitExceptionSpecification
  9605. ComputeDefaultedSpecialMemberExceptionSpec(
  9606. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9607. Sema::InheritedConstructorInfo *ICI) {
  9608. ComputingExceptionSpec CES(S, MD, Loc);
  9609. CXXRecordDecl *ClassDecl = MD->getParent();
  9610. // C++ [except.spec]p14:
  9611. // An implicitly declared special member function (Clause 12) shall have an
  9612. // exception-specification. [...]
  9613. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9614. if (ClassDecl->isInvalidDecl())
  9615. return Info.ExceptSpec;
  9616. // FIXME: If this diagnostic fires, we're probably missing a check for
  9617. // attempting to resolve an exception specification before it's known
  9618. // at a higher level.
  9619. if (S.RequireCompleteType(MD->getLocation(),
  9620. S.Context.getRecordType(ClassDecl),
  9621. diag::err_exception_spec_incomplete_type))
  9622. return Info.ExceptSpec;
  9623. // C++1z [except.spec]p7:
  9624. // [Look for exceptions thrown by] a constructor selected [...] to
  9625. // initialize a potentially constructed subobject,
  9626. // C++1z [except.spec]p8:
  9627. // The exception specification for an implicitly-declared destructor, or a
  9628. // destructor without a noexcept-specifier, is potentially-throwing if and
  9629. // only if any of the destructors for any of its potentially constructed
  9630. // subojects is potentially throwing.
  9631. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9632. // in the second rule to resolve a core issue (no number yet) that would have
  9633. // us reject:
  9634. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9635. // struct B : A {};
  9636. // struct C : B { void f(); };
  9637. // ... due to giving B::~B() a non-throwing exception specification.
  9638. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9639. : Info.VisitAllBases);
  9640. return Info.ExceptSpec;
  9641. }
  9642. namespace {
  9643. /// RAII object to register a special member as being currently declared.
  9644. struct DeclaringSpecialMember {
  9645. Sema &S;
  9646. Sema::SpecialMemberDecl D;
  9647. Sema::ContextRAII SavedContext;
  9648. bool WasAlreadyBeingDeclared;
  9649. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9650. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9651. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9652. if (WasAlreadyBeingDeclared)
  9653. // This almost never happens, but if it does, ensure that our cache
  9654. // doesn't contain a stale result.
  9655. S.SpecialMemberCache.clear();
  9656. else {
  9657. // Register a note to be produced if we encounter an error while
  9658. // declaring the special member.
  9659. Sema::CodeSynthesisContext Ctx;
  9660. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9661. // FIXME: We don't have a location to use here. Using the class's
  9662. // location maintains the fiction that we declare all special members
  9663. // with the class, but (1) it's not clear that lying about that helps our
  9664. // users understand what's going on, and (2) there may be outer contexts
  9665. // on the stack (some of which are relevant) and printing them exposes
  9666. // our lies.
  9667. Ctx.PointOfInstantiation = RD->getLocation();
  9668. Ctx.Entity = RD;
  9669. Ctx.SpecialMember = CSM;
  9670. S.pushCodeSynthesisContext(Ctx);
  9671. }
  9672. }
  9673. ~DeclaringSpecialMember() {
  9674. if (!WasAlreadyBeingDeclared) {
  9675. S.SpecialMembersBeingDeclared.erase(D);
  9676. S.popCodeSynthesisContext();
  9677. }
  9678. }
  9679. /// Are we already trying to declare this special member?
  9680. bool isAlreadyBeingDeclared() const {
  9681. return WasAlreadyBeingDeclared;
  9682. }
  9683. };
  9684. }
  9685. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9686. // Look up any existing declarations, but don't trigger declaration of all
  9687. // implicit special members with this name.
  9688. DeclarationName Name = FD->getDeclName();
  9689. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9690. ForExternalRedeclaration);
  9691. for (auto *D : FD->getParent()->lookup(Name))
  9692. if (auto *Acceptable = R.getAcceptableDecl(D))
  9693. R.addDecl(Acceptable);
  9694. R.resolveKind();
  9695. R.suppressDiagnostics();
  9696. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9697. }
  9698. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  9699. QualType ResultTy,
  9700. ArrayRef<QualType> Args) {
  9701. // Build an exception specification pointing back at this constructor.
  9702. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  9703. if (getLangOpts().OpenCLCPlusPlus) {
  9704. // OpenCL: Implicitly defaulted special member are of the generic address
  9705. // space.
  9706. EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
  9707. }
  9708. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  9709. SpecialMem->setType(QT);
  9710. }
  9711. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9712. CXXRecordDecl *ClassDecl) {
  9713. // C++ [class.ctor]p5:
  9714. // A default constructor for a class X is a constructor of class X
  9715. // that can be called without an argument. If there is no
  9716. // user-declared constructor for class X, a default constructor is
  9717. // implicitly declared. An implicitly-declared default constructor
  9718. // is an inline public member of its class.
  9719. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9720. "Should not build implicit default constructor!");
  9721. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9722. if (DSM.isAlreadyBeingDeclared())
  9723. return nullptr;
  9724. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9725. CXXDefaultConstructor,
  9726. false);
  9727. // Create the actual constructor declaration.
  9728. CanQualType ClassType
  9729. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9730. SourceLocation ClassLoc = ClassDecl->getLocation();
  9731. DeclarationName Name
  9732. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9733. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9734. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9735. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  9736. /*TInfo=*/nullptr, ExplicitSpecifier(),
  9737. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9738. Constexpr ? CSK_constexpr : CSK_unspecified);
  9739. DefaultCon->setAccess(AS_public);
  9740. DefaultCon->setDefaulted();
  9741. if (getLangOpts().CUDA) {
  9742. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9743. DefaultCon,
  9744. /* ConstRHS */ false,
  9745. /* Diagnose */ false);
  9746. }
  9747. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
  9748. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9749. // constructors is easy to compute.
  9750. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9751. // Note that we have declared this constructor.
  9752. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  9753. Scope *S = getScopeForContext(ClassDecl);
  9754. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9755. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9756. SetDeclDeleted(DefaultCon, ClassLoc);
  9757. if (S)
  9758. PushOnScopeChains(DefaultCon, S, false);
  9759. ClassDecl->addDecl(DefaultCon);
  9760. return DefaultCon;
  9761. }
  9762. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9763. CXXConstructorDecl *Constructor) {
  9764. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9765. !Constructor->doesThisDeclarationHaveABody() &&
  9766. !Constructor->isDeleted()) &&
  9767. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9768. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9769. return;
  9770. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9771. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9772. SynthesizedFunctionScope Scope(*this, Constructor);
  9773. // The exception specification is needed because we are defining the
  9774. // function.
  9775. ResolveExceptionSpec(CurrentLocation,
  9776. Constructor->getType()->castAs<FunctionProtoType>());
  9777. MarkVTableUsed(CurrentLocation, ClassDecl);
  9778. // Add a context note for diagnostics produced after this point.
  9779. Scope.addContextNote(CurrentLocation);
  9780. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9781. Constructor->setInvalidDecl();
  9782. return;
  9783. }
  9784. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9785. ? Constructor->getEndLoc()
  9786. : Constructor->getLocation();
  9787. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9788. Constructor->markUsed(Context);
  9789. if (ASTMutationListener *L = getASTMutationListener()) {
  9790. L->CompletedImplicitDefinition(Constructor);
  9791. }
  9792. DiagnoseUninitializedFields(*this, Constructor);
  9793. }
  9794. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9795. // Perform any delayed checks on exception specifications.
  9796. CheckDelayedMemberExceptionSpecs();
  9797. }
  9798. /// Find or create the fake constructor we synthesize to model constructing an
  9799. /// object of a derived class via a constructor of a base class.
  9800. CXXConstructorDecl *
  9801. Sema::findInheritingConstructor(SourceLocation Loc,
  9802. CXXConstructorDecl *BaseCtor,
  9803. ConstructorUsingShadowDecl *Shadow) {
  9804. CXXRecordDecl *Derived = Shadow->getParent();
  9805. SourceLocation UsingLoc = Shadow->getLocation();
  9806. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9807. // For now we use the name of the base class constructor as a member of the
  9808. // derived class to indicate a (fake) inherited constructor name.
  9809. DeclarationName Name = BaseCtor->getDeclName();
  9810. // Check to see if we already have a fake constructor for this inherited
  9811. // constructor call.
  9812. for (NamedDecl *Ctor : Derived->lookup(Name))
  9813. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9814. ->getInheritedConstructor()
  9815. .getConstructor(),
  9816. BaseCtor))
  9817. return cast<CXXConstructorDecl>(Ctor);
  9818. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9819. TypeSourceInfo *TInfo =
  9820. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9821. FunctionProtoTypeLoc ProtoLoc =
  9822. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9823. // Check the inherited constructor is valid and find the list of base classes
  9824. // from which it was inherited.
  9825. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9826. bool Constexpr =
  9827. BaseCtor->isConstexpr() &&
  9828. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9829. false, BaseCtor, &ICI);
  9830. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9831. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9832. BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
  9833. /*isImplicitlyDeclared=*/true,
  9834. Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
  9835. InheritedConstructor(Shadow, BaseCtor));
  9836. if (Shadow->isInvalidDecl())
  9837. DerivedCtor->setInvalidDecl();
  9838. // Build an unevaluated exception specification for this fake constructor.
  9839. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9840. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9841. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9842. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9843. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9844. FPT->getParamTypes(), EPI));
  9845. // Build the parameter declarations.
  9846. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9847. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9848. TypeSourceInfo *TInfo =
  9849. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9850. ParmVarDecl *PD = ParmVarDecl::Create(
  9851. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9852. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  9853. PD->setScopeInfo(0, I);
  9854. PD->setImplicit();
  9855. // Ensure attributes are propagated onto parameters (this matters for
  9856. // format, pass_object_size, ...).
  9857. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9858. ParamDecls.push_back(PD);
  9859. ProtoLoc.setParam(I, PD);
  9860. }
  9861. // Set up the new constructor.
  9862. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9863. DerivedCtor->setAccess(BaseCtor->getAccess());
  9864. DerivedCtor->setParams(ParamDecls);
  9865. Derived->addDecl(DerivedCtor);
  9866. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9867. SetDeclDeleted(DerivedCtor, UsingLoc);
  9868. return DerivedCtor;
  9869. }
  9870. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9871. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9872. Ctor->getInheritedConstructor().getShadowDecl());
  9873. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9874. /*Diagnose*/true);
  9875. }
  9876. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9877. CXXConstructorDecl *Constructor) {
  9878. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9879. assert(Constructor->getInheritedConstructor() &&
  9880. !Constructor->doesThisDeclarationHaveABody() &&
  9881. !Constructor->isDeleted());
  9882. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9883. return;
  9884. // Initializations are performed "as if by a defaulted default constructor",
  9885. // so enter the appropriate scope.
  9886. SynthesizedFunctionScope Scope(*this, Constructor);
  9887. // The exception specification is needed because we are defining the
  9888. // function.
  9889. ResolveExceptionSpec(CurrentLocation,
  9890. Constructor->getType()->castAs<FunctionProtoType>());
  9891. MarkVTableUsed(CurrentLocation, ClassDecl);
  9892. // Add a context note for diagnostics produced after this point.
  9893. Scope.addContextNote(CurrentLocation);
  9894. ConstructorUsingShadowDecl *Shadow =
  9895. Constructor->getInheritedConstructor().getShadowDecl();
  9896. CXXConstructorDecl *InheritedCtor =
  9897. Constructor->getInheritedConstructor().getConstructor();
  9898. // [class.inhctor.init]p1:
  9899. // initialization proceeds as if a defaulted default constructor is used to
  9900. // initialize the D object and each base class subobject from which the
  9901. // constructor was inherited
  9902. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9903. CXXRecordDecl *RD = Shadow->getParent();
  9904. SourceLocation InitLoc = Shadow->getLocation();
  9905. // Build explicit initializers for all base classes from which the
  9906. // constructor was inherited.
  9907. SmallVector<CXXCtorInitializer*, 8> Inits;
  9908. for (bool VBase : {false, true}) {
  9909. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9910. if (B.isVirtual() != VBase)
  9911. continue;
  9912. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9913. if (!BaseRD)
  9914. continue;
  9915. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9916. if (!BaseCtor.first)
  9917. continue;
  9918. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9919. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9920. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9921. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9922. Inits.push_back(new (Context) CXXCtorInitializer(
  9923. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9924. SourceLocation()));
  9925. }
  9926. }
  9927. // We now proceed as if for a defaulted default constructor, with the relevant
  9928. // initializers replaced.
  9929. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  9930. Constructor->setInvalidDecl();
  9931. return;
  9932. }
  9933. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9934. Constructor->markUsed(Context);
  9935. if (ASTMutationListener *L = getASTMutationListener()) {
  9936. L->CompletedImplicitDefinition(Constructor);
  9937. }
  9938. DiagnoseUninitializedFields(*this, Constructor);
  9939. }
  9940. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  9941. // C++ [class.dtor]p2:
  9942. // If a class has no user-declared destructor, a destructor is
  9943. // declared implicitly. An implicitly-declared destructor is an
  9944. // inline public member of its class.
  9945. assert(ClassDecl->needsImplicitDestructor());
  9946. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  9947. if (DSM.isAlreadyBeingDeclared())
  9948. return nullptr;
  9949. // Create the actual destructor declaration.
  9950. CanQualType ClassType
  9951. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9952. SourceLocation ClassLoc = ClassDecl->getLocation();
  9953. DeclarationName Name
  9954. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  9955. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9956. CXXDestructorDecl *Destructor
  9957. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  9958. QualType(), nullptr, /*isInline=*/true,
  9959. /*isImplicitlyDeclared=*/true);
  9960. Destructor->setAccess(AS_public);
  9961. Destructor->setDefaulted();
  9962. if (getLangOpts().CUDA) {
  9963. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  9964. Destructor,
  9965. /* ConstRHS */ false,
  9966. /* Diagnose */ false);
  9967. }
  9968. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
  9969. // We don't need to use SpecialMemberIsTrivial here; triviality for
  9970. // destructors is easy to compute.
  9971. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  9972. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  9973. ClassDecl->hasTrivialDestructorForCall());
  9974. // Note that we have declared this destructor.
  9975. ++getASTContext().NumImplicitDestructorsDeclared;
  9976. Scope *S = getScopeForContext(ClassDecl);
  9977. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  9978. // We can't check whether an implicit destructor is deleted before we complete
  9979. // the definition of the class, because its validity depends on the alignment
  9980. // of the class. We'll check this from ActOnFields once the class is complete.
  9981. if (ClassDecl->isCompleteDefinition() &&
  9982. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  9983. SetDeclDeleted(Destructor, ClassLoc);
  9984. // Introduce this destructor into its scope.
  9985. if (S)
  9986. PushOnScopeChains(Destructor, S, false);
  9987. ClassDecl->addDecl(Destructor);
  9988. return Destructor;
  9989. }
  9990. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  9991. CXXDestructorDecl *Destructor) {
  9992. assert((Destructor->isDefaulted() &&
  9993. !Destructor->doesThisDeclarationHaveABody() &&
  9994. !Destructor->isDeleted()) &&
  9995. "DefineImplicitDestructor - call it for implicit default dtor");
  9996. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  9997. return;
  9998. CXXRecordDecl *ClassDecl = Destructor->getParent();
  9999. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  10000. SynthesizedFunctionScope Scope(*this, Destructor);
  10001. // The exception specification is needed because we are defining the
  10002. // function.
  10003. ResolveExceptionSpec(CurrentLocation,
  10004. Destructor->getType()->castAs<FunctionProtoType>());
  10005. MarkVTableUsed(CurrentLocation, ClassDecl);
  10006. // Add a context note for diagnostics produced after this point.
  10007. Scope.addContextNote(CurrentLocation);
  10008. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  10009. Destructor->getParent());
  10010. if (CheckDestructor(Destructor)) {
  10011. Destructor->setInvalidDecl();
  10012. return;
  10013. }
  10014. SourceLocation Loc = Destructor->getEndLoc().isValid()
  10015. ? Destructor->getEndLoc()
  10016. : Destructor->getLocation();
  10017. Destructor->setBody(new (Context) CompoundStmt(Loc));
  10018. Destructor->markUsed(Context);
  10019. if (ASTMutationListener *L = getASTMutationListener()) {
  10020. L->CompletedImplicitDefinition(Destructor);
  10021. }
  10022. }
  10023. /// Perform any semantic analysis which needs to be delayed until all
  10024. /// pending class member declarations have been parsed.
  10025. void Sema::ActOnFinishCXXMemberDecls() {
  10026. // If the context is an invalid C++ class, just suppress these checks.
  10027. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  10028. if (Record->isInvalidDecl()) {
  10029. DelayedOverridingExceptionSpecChecks.clear();
  10030. DelayedEquivalentExceptionSpecChecks.clear();
  10031. return;
  10032. }
  10033. checkForMultipleExportedDefaultConstructors(*this, Record);
  10034. }
  10035. }
  10036. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  10037. referenceDLLExportedClassMethods();
  10038. if (!DelayedDllExportMemberFunctions.empty()) {
  10039. SmallVector<CXXMethodDecl*, 4> WorkList;
  10040. std::swap(DelayedDllExportMemberFunctions, WorkList);
  10041. for (CXXMethodDecl *M : WorkList) {
  10042. DefineImplicitSpecialMember(*this, M, M->getLocation());
  10043. // Pass the method to the consumer to get emitted. This is not necessary
  10044. // for explicit instantiation definitions, as they will get emitted
  10045. // anyway.
  10046. if (M->getParent()->getTemplateSpecializationKind() !=
  10047. TSK_ExplicitInstantiationDefinition)
  10048. ActOnFinishInlineFunctionDef(M);
  10049. }
  10050. }
  10051. }
  10052. void Sema::referenceDLLExportedClassMethods() {
  10053. if (!DelayedDllExportClasses.empty()) {
  10054. // Calling ReferenceDllExportedMembers might cause the current function to
  10055. // be called again, so use a local copy of DelayedDllExportClasses.
  10056. SmallVector<CXXRecordDecl *, 4> WorkList;
  10057. std::swap(DelayedDllExportClasses, WorkList);
  10058. for (CXXRecordDecl *Class : WorkList)
  10059. ReferenceDllExportedMembers(*this, Class);
  10060. }
  10061. }
  10062. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  10063. assert(getLangOpts().CPlusPlus11 &&
  10064. "adjusting dtor exception specs was introduced in c++11");
  10065. if (Destructor->isDependentContext())
  10066. return;
  10067. // C++11 [class.dtor]p3:
  10068. // A declaration of a destructor that does not have an exception-
  10069. // specification is implicitly considered to have the same exception-
  10070. // specification as an implicit declaration.
  10071. const FunctionProtoType *DtorType = Destructor->getType()->
  10072. getAs<FunctionProtoType>();
  10073. if (DtorType->hasExceptionSpec())
  10074. return;
  10075. // Replace the destructor's type, building off the existing one. Fortunately,
  10076. // the only thing of interest in the destructor type is its extended info.
  10077. // The return and arguments are fixed.
  10078. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  10079. EPI.ExceptionSpec.Type = EST_Unevaluated;
  10080. EPI.ExceptionSpec.SourceDecl = Destructor;
  10081. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  10082. // FIXME: If the destructor has a body that could throw, and the newly created
  10083. // spec doesn't allow exceptions, we should emit a warning, because this
  10084. // change in behavior can break conforming C++03 programs at runtime.
  10085. // However, we don't have a body or an exception specification yet, so it
  10086. // needs to be done somewhere else.
  10087. }
  10088. namespace {
  10089. /// An abstract base class for all helper classes used in building the
  10090. // copy/move operators. These classes serve as factory functions and help us
  10091. // avoid using the same Expr* in the AST twice.
  10092. class ExprBuilder {
  10093. ExprBuilder(const ExprBuilder&) = delete;
  10094. ExprBuilder &operator=(const ExprBuilder&) = delete;
  10095. protected:
  10096. static Expr *assertNotNull(Expr *E) {
  10097. assert(E && "Expression construction must not fail.");
  10098. return E;
  10099. }
  10100. public:
  10101. ExprBuilder() {}
  10102. virtual ~ExprBuilder() {}
  10103. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  10104. };
  10105. class RefBuilder: public ExprBuilder {
  10106. VarDecl *Var;
  10107. QualType VarType;
  10108. public:
  10109. Expr *build(Sema &S, SourceLocation Loc) const override {
  10110. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  10111. }
  10112. RefBuilder(VarDecl *Var, QualType VarType)
  10113. : Var(Var), VarType(VarType) {}
  10114. };
  10115. class ThisBuilder: public ExprBuilder {
  10116. public:
  10117. Expr *build(Sema &S, SourceLocation Loc) const override {
  10118. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  10119. }
  10120. };
  10121. class CastBuilder: public ExprBuilder {
  10122. const ExprBuilder &Builder;
  10123. QualType Type;
  10124. ExprValueKind Kind;
  10125. const CXXCastPath &Path;
  10126. public:
  10127. Expr *build(Sema &S, SourceLocation Loc) const override {
  10128. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  10129. CK_UncheckedDerivedToBase, Kind,
  10130. &Path).get());
  10131. }
  10132. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  10133. const CXXCastPath &Path)
  10134. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  10135. };
  10136. class DerefBuilder: public ExprBuilder {
  10137. const ExprBuilder &Builder;
  10138. public:
  10139. Expr *build(Sema &S, SourceLocation Loc) const override {
  10140. return assertNotNull(
  10141. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  10142. }
  10143. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10144. };
  10145. class MemberBuilder: public ExprBuilder {
  10146. const ExprBuilder &Builder;
  10147. QualType Type;
  10148. CXXScopeSpec SS;
  10149. bool IsArrow;
  10150. LookupResult &MemberLookup;
  10151. public:
  10152. Expr *build(Sema &S, SourceLocation Loc) const override {
  10153. return assertNotNull(S.BuildMemberReferenceExpr(
  10154. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  10155. nullptr, MemberLookup, nullptr, nullptr).get());
  10156. }
  10157. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  10158. LookupResult &MemberLookup)
  10159. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  10160. MemberLookup(MemberLookup) {}
  10161. };
  10162. class MoveCastBuilder: public ExprBuilder {
  10163. const ExprBuilder &Builder;
  10164. public:
  10165. Expr *build(Sema &S, SourceLocation Loc) const override {
  10166. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  10167. }
  10168. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10169. };
  10170. class LvalueConvBuilder: public ExprBuilder {
  10171. const ExprBuilder &Builder;
  10172. public:
  10173. Expr *build(Sema &S, SourceLocation Loc) const override {
  10174. return assertNotNull(
  10175. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  10176. }
  10177. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10178. };
  10179. class SubscriptBuilder: public ExprBuilder {
  10180. const ExprBuilder &Base;
  10181. const ExprBuilder &Index;
  10182. public:
  10183. Expr *build(Sema &S, SourceLocation Loc) const override {
  10184. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  10185. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  10186. }
  10187. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  10188. : Base(Base), Index(Index) {}
  10189. };
  10190. } // end anonymous namespace
  10191. /// When generating a defaulted copy or move assignment operator, if a field
  10192. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  10193. /// do so. This optimization only applies for arrays of scalars, and for arrays
  10194. /// of class type where the selected copy/move-assignment operator is trivial.
  10195. static StmtResult
  10196. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  10197. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  10198. // Compute the size of the memory buffer to be copied.
  10199. QualType SizeType = S.Context.getSizeType();
  10200. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  10201. S.Context.getTypeSizeInChars(T).getQuantity());
  10202. // Take the address of the field references for "from" and "to". We
  10203. // directly construct UnaryOperators here because semantic analysis
  10204. // does not permit us to take the address of an xvalue.
  10205. Expr *From = FromB.build(S, Loc);
  10206. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  10207. S.Context.getPointerType(From->getType()),
  10208. VK_RValue, OK_Ordinary, Loc, false);
  10209. Expr *To = ToB.build(S, Loc);
  10210. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  10211. S.Context.getPointerType(To->getType()),
  10212. VK_RValue, OK_Ordinary, Loc, false);
  10213. const Type *E = T->getBaseElementTypeUnsafe();
  10214. bool NeedsCollectableMemCpy =
  10215. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  10216. // Create a reference to the __builtin_objc_memmove_collectable function
  10217. StringRef MemCpyName = NeedsCollectableMemCpy ?
  10218. "__builtin_objc_memmove_collectable" :
  10219. "__builtin_memcpy";
  10220. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  10221. Sema::LookupOrdinaryName);
  10222. S.LookupName(R, S.TUScope, true);
  10223. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  10224. if (!MemCpy)
  10225. // Something went horribly wrong earlier, and we will have complained
  10226. // about it.
  10227. return StmtError();
  10228. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  10229. VK_RValue, Loc, nullptr);
  10230. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  10231. Expr *CallArgs[] = {
  10232. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  10233. };
  10234. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  10235. Loc, CallArgs, Loc);
  10236. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  10237. return Call.getAs<Stmt>();
  10238. }
  10239. /// Builds a statement that copies/moves the given entity from \p From to
  10240. /// \c To.
  10241. ///
  10242. /// This routine is used to copy/move the members of a class with an
  10243. /// implicitly-declared copy/move assignment operator. When the entities being
  10244. /// copied are arrays, this routine builds for loops to copy them.
  10245. ///
  10246. /// \param S The Sema object used for type-checking.
  10247. ///
  10248. /// \param Loc The location where the implicit copy/move is being generated.
  10249. ///
  10250. /// \param T The type of the expressions being copied/moved. Both expressions
  10251. /// must have this type.
  10252. ///
  10253. /// \param To The expression we are copying/moving to.
  10254. ///
  10255. /// \param From The expression we are copying/moving from.
  10256. ///
  10257. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  10258. /// Otherwise, it's a non-static member subobject.
  10259. ///
  10260. /// \param Copying Whether we're copying or moving.
  10261. ///
  10262. /// \param Depth Internal parameter recording the depth of the recursion.
  10263. ///
  10264. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  10265. /// if a memcpy should be used instead.
  10266. static StmtResult
  10267. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  10268. const ExprBuilder &To, const ExprBuilder &From,
  10269. bool CopyingBaseSubobject, bool Copying,
  10270. unsigned Depth = 0) {
  10271. // C++11 [class.copy]p28:
  10272. // Each subobject is assigned in the manner appropriate to its type:
  10273. //
  10274. // - if the subobject is of class type, as if by a call to operator= with
  10275. // the subobject as the object expression and the corresponding
  10276. // subobject of x as a single function argument (as if by explicit
  10277. // qualification; that is, ignoring any possible virtual overriding
  10278. // functions in more derived classes);
  10279. //
  10280. // C++03 [class.copy]p13:
  10281. // - if the subobject is of class type, the copy assignment operator for
  10282. // the class is used (as if by explicit qualification; that is,
  10283. // ignoring any possible virtual overriding functions in more derived
  10284. // classes);
  10285. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  10286. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  10287. // Look for operator=.
  10288. DeclarationName Name
  10289. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10290. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  10291. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  10292. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  10293. // operator.
  10294. if (!S.getLangOpts().CPlusPlus11) {
  10295. LookupResult::Filter F = OpLookup.makeFilter();
  10296. while (F.hasNext()) {
  10297. NamedDecl *D = F.next();
  10298. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  10299. if (Method->isCopyAssignmentOperator() ||
  10300. (!Copying && Method->isMoveAssignmentOperator()))
  10301. continue;
  10302. F.erase();
  10303. }
  10304. F.done();
  10305. }
  10306. // Suppress the protected check (C++ [class.protected]) for each of the
  10307. // assignment operators we found. This strange dance is required when
  10308. // we're assigning via a base classes's copy-assignment operator. To
  10309. // ensure that we're getting the right base class subobject (without
  10310. // ambiguities), we need to cast "this" to that subobject type; to
  10311. // ensure that we don't go through the virtual call mechanism, we need
  10312. // to qualify the operator= name with the base class (see below). However,
  10313. // this means that if the base class has a protected copy assignment
  10314. // operator, the protected member access check will fail. So, we
  10315. // rewrite "protected" access to "public" access in this case, since we
  10316. // know by construction that we're calling from a derived class.
  10317. if (CopyingBaseSubobject) {
  10318. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10319. L != LEnd; ++L) {
  10320. if (L.getAccess() == AS_protected)
  10321. L.setAccess(AS_public);
  10322. }
  10323. }
  10324. // Create the nested-name-specifier that will be used to qualify the
  10325. // reference to operator=; this is required to suppress the virtual
  10326. // call mechanism.
  10327. CXXScopeSpec SS;
  10328. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10329. SS.MakeTrivial(S.Context,
  10330. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10331. CanonicalT),
  10332. Loc);
  10333. // Create the reference to operator=.
  10334. ExprResult OpEqualRef
  10335. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  10336. SS, /*TemplateKWLoc=*/SourceLocation(),
  10337. /*FirstQualifierInScope=*/nullptr,
  10338. OpLookup,
  10339. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10340. /*SuppressQualifierCheck=*/true);
  10341. if (OpEqualRef.isInvalid())
  10342. return StmtError();
  10343. // Build the call to the assignment operator.
  10344. Expr *FromInst = From.build(S, Loc);
  10345. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10346. OpEqualRef.getAs<Expr>(),
  10347. Loc, FromInst, Loc);
  10348. if (Call.isInvalid())
  10349. return StmtError();
  10350. // If we built a call to a trivial 'operator=' while copying an array,
  10351. // bail out. We'll replace the whole shebang with a memcpy.
  10352. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10353. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10354. return StmtResult((Stmt*)nullptr);
  10355. // Convert to an expression-statement, and clean up any produced
  10356. // temporaries.
  10357. return S.ActOnExprStmt(Call);
  10358. }
  10359. // - if the subobject is of scalar type, the built-in assignment
  10360. // operator is used.
  10361. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10362. if (!ArrayTy) {
  10363. ExprResult Assignment = S.CreateBuiltinBinOp(
  10364. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10365. if (Assignment.isInvalid())
  10366. return StmtError();
  10367. return S.ActOnExprStmt(Assignment);
  10368. }
  10369. // - if the subobject is an array, each element is assigned, in the
  10370. // manner appropriate to the element type;
  10371. // Construct a loop over the array bounds, e.g.,
  10372. //
  10373. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10374. //
  10375. // that will copy each of the array elements.
  10376. QualType SizeType = S.Context.getSizeType();
  10377. // Create the iteration variable.
  10378. IdentifierInfo *IterationVarName = nullptr;
  10379. {
  10380. SmallString<8> Str;
  10381. llvm::raw_svector_ostream OS(Str);
  10382. OS << "__i" << Depth;
  10383. IterationVarName = &S.Context.Idents.get(OS.str());
  10384. }
  10385. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10386. IterationVarName, SizeType,
  10387. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10388. SC_None);
  10389. // Initialize the iteration variable to zero.
  10390. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10391. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10392. // Creates a reference to the iteration variable.
  10393. RefBuilder IterationVarRef(IterationVar, SizeType);
  10394. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10395. // Create the DeclStmt that holds the iteration variable.
  10396. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10397. // Subscript the "from" and "to" expressions with the iteration variable.
  10398. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10399. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10400. const ExprBuilder *FromIndex;
  10401. if (Copying)
  10402. FromIndex = &FromIndexCopy;
  10403. else
  10404. FromIndex = &FromIndexMove;
  10405. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10406. // Build the copy/move for an individual element of the array.
  10407. StmtResult Copy =
  10408. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10409. ToIndex, *FromIndex, CopyingBaseSubobject,
  10410. Copying, Depth + 1);
  10411. // Bail out if copying fails or if we determined that we should use memcpy.
  10412. if (Copy.isInvalid() || !Copy.get())
  10413. return Copy;
  10414. // Create the comparison against the array bound.
  10415. llvm::APInt Upper
  10416. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10417. Expr *Comparison
  10418. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10419. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10420. BO_NE, S.Context.BoolTy,
  10421. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10422. // Create the pre-increment of the iteration variable. We can determine
  10423. // whether the increment will overflow based on the value of the array
  10424. // bound.
  10425. Expr *Increment = new (S.Context)
  10426. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10427. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10428. // Construct the loop that copies all elements of this array.
  10429. return S.ActOnForStmt(
  10430. Loc, Loc, InitStmt,
  10431. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10432. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10433. }
  10434. static StmtResult
  10435. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10436. const ExprBuilder &To, const ExprBuilder &From,
  10437. bool CopyingBaseSubobject, bool Copying) {
  10438. // Maybe we should use a memcpy?
  10439. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10440. T.isTriviallyCopyableType(S.Context))
  10441. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10442. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10443. CopyingBaseSubobject,
  10444. Copying, 0));
  10445. // If we ended up picking a trivial assignment operator for an array of a
  10446. // non-trivially-copyable class type, just emit a memcpy.
  10447. if (!Result.isInvalid() && !Result.get())
  10448. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10449. return Result;
  10450. }
  10451. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10452. // Note: The following rules are largely analoguous to the copy
  10453. // constructor rules. Note that virtual bases are not taken into account
  10454. // for determining the argument type of the operator. Note also that
  10455. // operators taking an object instead of a reference are allowed.
  10456. assert(ClassDecl->needsImplicitCopyAssignment());
  10457. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10458. if (DSM.isAlreadyBeingDeclared())
  10459. return nullptr;
  10460. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10461. if (Context.getLangOpts().OpenCLCPlusPlus)
  10462. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10463. QualType RetType = Context.getLValueReferenceType(ArgType);
  10464. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10465. if (Const)
  10466. ArgType = ArgType.withConst();
  10467. ArgType = Context.getLValueReferenceType(ArgType);
  10468. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10469. CXXCopyAssignment,
  10470. Const);
  10471. // An implicitly-declared copy assignment operator is an inline public
  10472. // member of its class.
  10473. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10474. SourceLocation ClassLoc = ClassDecl->getLocation();
  10475. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10476. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  10477. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10478. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10479. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10480. SourceLocation());
  10481. CopyAssignment->setAccess(AS_public);
  10482. CopyAssignment->setDefaulted();
  10483. CopyAssignment->setImplicit();
  10484. if (getLangOpts().CUDA) {
  10485. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10486. CopyAssignment,
  10487. /* ConstRHS */ Const,
  10488. /* Diagnose */ false);
  10489. }
  10490. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  10491. // Add the parameter to the operator.
  10492. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10493. ClassLoc, ClassLoc,
  10494. /*Id=*/nullptr, ArgType,
  10495. /*TInfo=*/nullptr, SC_None,
  10496. nullptr);
  10497. CopyAssignment->setParams(FromParam);
  10498. CopyAssignment->setTrivial(
  10499. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10500. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10501. : ClassDecl->hasTrivialCopyAssignment());
  10502. // Note that we have added this copy-assignment operator.
  10503. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  10504. Scope *S = getScopeForContext(ClassDecl);
  10505. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10506. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10507. SetDeclDeleted(CopyAssignment, ClassLoc);
  10508. if (S)
  10509. PushOnScopeChains(CopyAssignment, S, false);
  10510. ClassDecl->addDecl(CopyAssignment);
  10511. return CopyAssignment;
  10512. }
  10513. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10514. /// which is deprecated because the class has a user-declared copy constructor,
  10515. /// copy assignment operator, or destructor.
  10516. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10517. assert(CopyOp->isImplicit());
  10518. CXXRecordDecl *RD = CopyOp->getParent();
  10519. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10520. // In Microsoft mode, assignment operations don't affect constructors and
  10521. // vice versa.
  10522. if (RD->hasUserDeclaredDestructor()) {
  10523. UserDeclaredOperation = RD->getDestructor();
  10524. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10525. RD->hasUserDeclaredCopyConstructor() &&
  10526. !S.getLangOpts().MSVCCompat) {
  10527. // Find any user-declared copy constructor.
  10528. for (auto *I : RD->ctors()) {
  10529. if (I->isCopyConstructor()) {
  10530. UserDeclaredOperation = I;
  10531. break;
  10532. }
  10533. }
  10534. assert(UserDeclaredOperation);
  10535. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10536. RD->hasUserDeclaredCopyAssignment() &&
  10537. !S.getLangOpts().MSVCCompat) {
  10538. // Find any user-declared move assignment operator.
  10539. for (auto *I : RD->methods()) {
  10540. if (I->isCopyAssignmentOperator()) {
  10541. UserDeclaredOperation = I;
  10542. break;
  10543. }
  10544. }
  10545. assert(UserDeclaredOperation);
  10546. }
  10547. if (UserDeclaredOperation) {
  10548. S.Diag(UserDeclaredOperation->getLocation(),
  10549. diag::warn_deprecated_copy_operation)
  10550. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10551. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10552. }
  10553. }
  10554. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10555. CXXMethodDecl *CopyAssignOperator) {
  10556. assert((CopyAssignOperator->isDefaulted() &&
  10557. CopyAssignOperator->isOverloadedOperator() &&
  10558. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10559. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10560. !CopyAssignOperator->isDeleted()) &&
  10561. "DefineImplicitCopyAssignment called for wrong function");
  10562. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10563. return;
  10564. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10565. if (ClassDecl->isInvalidDecl()) {
  10566. CopyAssignOperator->setInvalidDecl();
  10567. return;
  10568. }
  10569. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10570. // The exception specification is needed because we are defining the
  10571. // function.
  10572. ResolveExceptionSpec(CurrentLocation,
  10573. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10574. // Add a context note for diagnostics produced after this point.
  10575. Scope.addContextNote(CurrentLocation);
  10576. // C++11 [class.copy]p18:
  10577. // The [definition of an implicitly declared copy assignment operator] is
  10578. // deprecated if the class has a user-declared copy constructor or a
  10579. // user-declared destructor.
  10580. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10581. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10582. // C++0x [class.copy]p30:
  10583. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10584. // for a non-union class X performs memberwise copy assignment of its
  10585. // subobjects. The direct base classes of X are assigned first, in the
  10586. // order of their declaration in the base-specifier-list, and then the
  10587. // immediate non-static data members of X are assigned, in the order in
  10588. // which they were declared in the class definition.
  10589. // The statements that form the synthesized function body.
  10590. SmallVector<Stmt*, 8> Statements;
  10591. // The parameter for the "other" object, which we are copying from.
  10592. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10593. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10594. QualType OtherRefType = Other->getType();
  10595. if (const LValueReferenceType *OtherRef
  10596. = OtherRefType->getAs<LValueReferenceType>()) {
  10597. OtherRefType = OtherRef->getPointeeType();
  10598. OtherQuals = OtherRefType.getQualifiers();
  10599. }
  10600. // Our location for everything implicitly-generated.
  10601. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10602. ? CopyAssignOperator->getEndLoc()
  10603. : CopyAssignOperator->getLocation();
  10604. // Builds a DeclRefExpr for the "other" object.
  10605. RefBuilder OtherRef(Other, OtherRefType);
  10606. // Builds the "this" pointer.
  10607. ThisBuilder This;
  10608. // Assign base classes.
  10609. bool Invalid = false;
  10610. for (auto &Base : ClassDecl->bases()) {
  10611. // Form the assignment:
  10612. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10613. QualType BaseType = Base.getType().getUnqualifiedType();
  10614. if (!BaseType->isRecordType()) {
  10615. Invalid = true;
  10616. continue;
  10617. }
  10618. CXXCastPath BasePath;
  10619. BasePath.push_back(&Base);
  10620. // Construct the "from" expression, which is an implicit cast to the
  10621. // appropriately-qualified base type.
  10622. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10623. VK_LValue, BasePath);
  10624. // Dereference "this".
  10625. DerefBuilder DerefThis(This);
  10626. CastBuilder To(DerefThis,
  10627. Context.getQualifiedType(
  10628. BaseType, CopyAssignOperator->getMethodQualifiers()),
  10629. VK_LValue, BasePath);
  10630. // Build the copy.
  10631. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10632. To, From,
  10633. /*CopyingBaseSubobject=*/true,
  10634. /*Copying=*/true);
  10635. if (Copy.isInvalid()) {
  10636. CopyAssignOperator->setInvalidDecl();
  10637. return;
  10638. }
  10639. // Success! Record the copy.
  10640. Statements.push_back(Copy.getAs<Expr>());
  10641. }
  10642. // Assign non-static members.
  10643. for (auto *Field : ClassDecl->fields()) {
  10644. // FIXME: We should form some kind of AST representation for the implied
  10645. // memcpy in a union copy operation.
  10646. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10647. continue;
  10648. if (Field->isInvalidDecl()) {
  10649. Invalid = true;
  10650. continue;
  10651. }
  10652. // Check for members of reference type; we can't copy those.
  10653. if (Field->getType()->isReferenceType()) {
  10654. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10655. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10656. Diag(Field->getLocation(), diag::note_declared_at);
  10657. Invalid = true;
  10658. continue;
  10659. }
  10660. // Check for members of const-qualified, non-class type.
  10661. QualType BaseType = Context.getBaseElementType(Field->getType());
  10662. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10663. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10664. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10665. Diag(Field->getLocation(), diag::note_declared_at);
  10666. Invalid = true;
  10667. continue;
  10668. }
  10669. // Suppress assigning zero-width bitfields.
  10670. if (Field->isZeroLengthBitField(Context))
  10671. continue;
  10672. QualType FieldType = Field->getType().getNonReferenceType();
  10673. if (FieldType->isIncompleteArrayType()) {
  10674. assert(ClassDecl->hasFlexibleArrayMember() &&
  10675. "Incomplete array type is not valid");
  10676. continue;
  10677. }
  10678. // Build references to the field in the object we're copying from and to.
  10679. CXXScopeSpec SS; // Intentionally empty
  10680. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10681. LookupMemberName);
  10682. MemberLookup.addDecl(Field);
  10683. MemberLookup.resolveKind();
  10684. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10685. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10686. // Build the copy of this field.
  10687. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10688. To, From,
  10689. /*CopyingBaseSubobject=*/false,
  10690. /*Copying=*/true);
  10691. if (Copy.isInvalid()) {
  10692. CopyAssignOperator->setInvalidDecl();
  10693. return;
  10694. }
  10695. // Success! Record the copy.
  10696. Statements.push_back(Copy.getAs<Stmt>());
  10697. }
  10698. if (!Invalid) {
  10699. // Add a "return *this;"
  10700. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10701. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10702. if (Return.isInvalid())
  10703. Invalid = true;
  10704. else
  10705. Statements.push_back(Return.getAs<Stmt>());
  10706. }
  10707. if (Invalid) {
  10708. CopyAssignOperator->setInvalidDecl();
  10709. return;
  10710. }
  10711. StmtResult Body;
  10712. {
  10713. CompoundScopeRAII CompoundScope(*this);
  10714. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10715. /*isStmtExpr=*/false);
  10716. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10717. }
  10718. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10719. CopyAssignOperator->markUsed(Context);
  10720. if (ASTMutationListener *L = getASTMutationListener()) {
  10721. L->CompletedImplicitDefinition(CopyAssignOperator);
  10722. }
  10723. }
  10724. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10725. assert(ClassDecl->needsImplicitMoveAssignment());
  10726. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10727. if (DSM.isAlreadyBeingDeclared())
  10728. return nullptr;
  10729. // Note: The following rules are largely analoguous to the move
  10730. // constructor rules.
  10731. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10732. if (Context.getLangOpts().OpenCLCPlusPlus)
  10733. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10734. QualType RetType = Context.getLValueReferenceType(ArgType);
  10735. ArgType = Context.getRValueReferenceType(ArgType);
  10736. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10737. CXXMoveAssignment,
  10738. false);
  10739. // An implicitly-declared move assignment operator is an inline public
  10740. // member of its class.
  10741. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10742. SourceLocation ClassLoc = ClassDecl->getLocation();
  10743. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10744. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  10745. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10746. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10747. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10748. SourceLocation());
  10749. MoveAssignment->setAccess(AS_public);
  10750. MoveAssignment->setDefaulted();
  10751. MoveAssignment->setImplicit();
  10752. if (getLangOpts().CUDA) {
  10753. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10754. MoveAssignment,
  10755. /* ConstRHS */ false,
  10756. /* Diagnose */ false);
  10757. }
  10758. // Build an exception specification pointing back at this member.
  10759. FunctionProtoType::ExtProtoInfo EPI =
  10760. getImplicitMethodEPI(*this, MoveAssignment);
  10761. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10762. // Add the parameter to the operator.
  10763. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10764. ClassLoc, ClassLoc,
  10765. /*Id=*/nullptr, ArgType,
  10766. /*TInfo=*/nullptr, SC_None,
  10767. nullptr);
  10768. MoveAssignment->setParams(FromParam);
  10769. MoveAssignment->setTrivial(
  10770. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10771. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10772. : ClassDecl->hasTrivialMoveAssignment());
  10773. // Note that we have added this copy-assignment operator.
  10774. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  10775. Scope *S = getScopeForContext(ClassDecl);
  10776. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10777. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10778. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10779. SetDeclDeleted(MoveAssignment, ClassLoc);
  10780. }
  10781. if (S)
  10782. PushOnScopeChains(MoveAssignment, S, false);
  10783. ClassDecl->addDecl(MoveAssignment);
  10784. return MoveAssignment;
  10785. }
  10786. /// Check if we're implicitly defining a move assignment operator for a class
  10787. /// with virtual bases. Such a move assignment might move-assign the virtual
  10788. /// base multiple times.
  10789. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10790. SourceLocation CurrentLocation) {
  10791. assert(!Class->isDependentContext() && "should not define dependent move");
  10792. // Only a virtual base could get implicitly move-assigned multiple times.
  10793. // Only a non-trivial move assignment can observe this. We only want to
  10794. // diagnose if we implicitly define an assignment operator that assigns
  10795. // two base classes, both of which move-assign the same virtual base.
  10796. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10797. Class->getNumBases() < 2)
  10798. return;
  10799. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10800. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10801. VBaseMap VBases;
  10802. for (auto &BI : Class->bases()) {
  10803. Worklist.push_back(&BI);
  10804. while (!Worklist.empty()) {
  10805. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10806. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10807. // If the base has no non-trivial move assignment operators,
  10808. // we don't care about moves from it.
  10809. if (!Base->hasNonTrivialMoveAssignment())
  10810. continue;
  10811. // If there's nothing virtual here, skip it.
  10812. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10813. continue;
  10814. // If we're not actually going to call a move assignment for this base,
  10815. // or the selected move assignment is trivial, skip it.
  10816. Sema::SpecialMemberOverloadResult SMOR =
  10817. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10818. /*ConstArg*/false, /*VolatileArg*/false,
  10819. /*RValueThis*/true, /*ConstThis*/false,
  10820. /*VolatileThis*/false);
  10821. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10822. !SMOR.getMethod()->isMoveAssignmentOperator())
  10823. continue;
  10824. if (BaseSpec->isVirtual()) {
  10825. // We're going to move-assign this virtual base, and its move
  10826. // assignment operator is not trivial. If this can happen for
  10827. // multiple distinct direct bases of Class, diagnose it. (If it
  10828. // only happens in one base, we'll diagnose it when synthesizing
  10829. // that base class's move assignment operator.)
  10830. CXXBaseSpecifier *&Existing =
  10831. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10832. .first->second;
  10833. if (Existing && Existing != &BI) {
  10834. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10835. << Class << Base;
  10836. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10837. << (Base->getCanonicalDecl() ==
  10838. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10839. << Base << Existing->getType() << Existing->getSourceRange();
  10840. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10841. << (Base->getCanonicalDecl() ==
  10842. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10843. << Base << BI.getType() << BaseSpec->getSourceRange();
  10844. // Only diagnose each vbase once.
  10845. Existing = nullptr;
  10846. }
  10847. } else {
  10848. // Only walk over bases that have defaulted move assignment operators.
  10849. // We assume that any user-provided move assignment operator handles
  10850. // the multiple-moves-of-vbase case itself somehow.
  10851. if (!SMOR.getMethod()->isDefaulted())
  10852. continue;
  10853. // We're going to move the base classes of Base. Add them to the list.
  10854. for (auto &BI : Base->bases())
  10855. Worklist.push_back(&BI);
  10856. }
  10857. }
  10858. }
  10859. }
  10860. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10861. CXXMethodDecl *MoveAssignOperator) {
  10862. assert((MoveAssignOperator->isDefaulted() &&
  10863. MoveAssignOperator->isOverloadedOperator() &&
  10864. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10865. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10866. !MoveAssignOperator->isDeleted()) &&
  10867. "DefineImplicitMoveAssignment called for wrong function");
  10868. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10869. return;
  10870. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10871. if (ClassDecl->isInvalidDecl()) {
  10872. MoveAssignOperator->setInvalidDecl();
  10873. return;
  10874. }
  10875. // C++0x [class.copy]p28:
  10876. // The implicitly-defined or move assignment operator for a non-union class
  10877. // X performs memberwise move assignment of its subobjects. The direct base
  10878. // classes of X are assigned first, in the order of their declaration in the
  10879. // base-specifier-list, and then the immediate non-static data members of X
  10880. // are assigned, in the order in which they were declared in the class
  10881. // definition.
  10882. // Issue a warning if our implicit move assignment operator will move
  10883. // from a virtual base more than once.
  10884. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10885. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10886. // The exception specification is needed because we are defining the
  10887. // function.
  10888. ResolveExceptionSpec(CurrentLocation,
  10889. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10890. // Add a context note for diagnostics produced after this point.
  10891. Scope.addContextNote(CurrentLocation);
  10892. // The statements that form the synthesized function body.
  10893. SmallVector<Stmt*, 8> Statements;
  10894. // The parameter for the "other" object, which we are move from.
  10895. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10896. QualType OtherRefType = Other->getType()->
  10897. getAs<RValueReferenceType>()->getPointeeType();
  10898. // Our location for everything implicitly-generated.
  10899. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10900. ? MoveAssignOperator->getEndLoc()
  10901. : MoveAssignOperator->getLocation();
  10902. // Builds a reference to the "other" object.
  10903. RefBuilder OtherRef(Other, OtherRefType);
  10904. // Cast to rvalue.
  10905. MoveCastBuilder MoveOther(OtherRef);
  10906. // Builds the "this" pointer.
  10907. ThisBuilder This;
  10908. // Assign base classes.
  10909. bool Invalid = false;
  10910. for (auto &Base : ClassDecl->bases()) {
  10911. // C++11 [class.copy]p28:
  10912. // It is unspecified whether subobjects representing virtual base classes
  10913. // are assigned more than once by the implicitly-defined copy assignment
  10914. // operator.
  10915. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10916. // class. For a move-assignment, this can result in the vbase being moved
  10917. // multiple times.
  10918. // Form the assignment:
  10919. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10920. QualType BaseType = Base.getType().getUnqualifiedType();
  10921. if (!BaseType->isRecordType()) {
  10922. Invalid = true;
  10923. continue;
  10924. }
  10925. CXXCastPath BasePath;
  10926. BasePath.push_back(&Base);
  10927. // Construct the "from" expression, which is an implicit cast to the
  10928. // appropriately-qualified base type.
  10929. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  10930. // Dereference "this".
  10931. DerefBuilder DerefThis(This);
  10932. // Implicitly cast "this" to the appropriately-qualified base type.
  10933. CastBuilder To(DerefThis,
  10934. Context.getQualifiedType(
  10935. BaseType, MoveAssignOperator->getMethodQualifiers()),
  10936. VK_LValue, BasePath);
  10937. // Build the move.
  10938. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  10939. To, From,
  10940. /*CopyingBaseSubobject=*/true,
  10941. /*Copying=*/false);
  10942. if (Move.isInvalid()) {
  10943. MoveAssignOperator->setInvalidDecl();
  10944. return;
  10945. }
  10946. // Success! Record the move.
  10947. Statements.push_back(Move.getAs<Expr>());
  10948. }
  10949. // Assign non-static members.
  10950. for (auto *Field : ClassDecl->fields()) {
  10951. // FIXME: We should form some kind of AST representation for the implied
  10952. // memcpy in a union copy operation.
  10953. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10954. continue;
  10955. if (Field->isInvalidDecl()) {
  10956. Invalid = true;
  10957. continue;
  10958. }
  10959. // Check for members of reference type; we can't move those.
  10960. if (Field->getType()->isReferenceType()) {
  10961. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10962. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10963. Diag(Field->getLocation(), diag::note_declared_at);
  10964. Invalid = true;
  10965. continue;
  10966. }
  10967. // Check for members of const-qualified, non-class type.
  10968. QualType BaseType = Context.getBaseElementType(Field->getType());
  10969. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10970. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10971. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10972. Diag(Field->getLocation(), diag::note_declared_at);
  10973. Invalid = true;
  10974. continue;
  10975. }
  10976. // Suppress assigning zero-width bitfields.
  10977. if (Field->isZeroLengthBitField(Context))
  10978. continue;
  10979. QualType FieldType = Field->getType().getNonReferenceType();
  10980. if (FieldType->isIncompleteArrayType()) {
  10981. assert(ClassDecl->hasFlexibleArrayMember() &&
  10982. "Incomplete array type is not valid");
  10983. continue;
  10984. }
  10985. // Build references to the field in the object we're copying from and to.
  10986. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10987. LookupMemberName);
  10988. MemberLookup.addDecl(Field);
  10989. MemberLookup.resolveKind();
  10990. MemberBuilder From(MoveOther, OtherRefType,
  10991. /*IsArrow=*/false, MemberLookup);
  10992. MemberBuilder To(This, getCurrentThisType(),
  10993. /*IsArrow=*/true, MemberLookup);
  10994. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  10995. "Member reference with rvalue base must be rvalue except for reference "
  10996. "members, which aren't allowed for move assignment.");
  10997. // Build the move of this field.
  10998. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  10999. To, From,
  11000. /*CopyingBaseSubobject=*/false,
  11001. /*Copying=*/false);
  11002. if (Move.isInvalid()) {
  11003. MoveAssignOperator->setInvalidDecl();
  11004. return;
  11005. }
  11006. // Success! Record the copy.
  11007. Statements.push_back(Move.getAs<Stmt>());
  11008. }
  11009. if (!Invalid) {
  11010. // Add a "return *this;"
  11011. ExprResult ThisObj =
  11012. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  11013. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  11014. if (Return.isInvalid())
  11015. Invalid = true;
  11016. else
  11017. Statements.push_back(Return.getAs<Stmt>());
  11018. }
  11019. if (Invalid) {
  11020. MoveAssignOperator->setInvalidDecl();
  11021. return;
  11022. }
  11023. StmtResult Body;
  11024. {
  11025. CompoundScopeRAII CompoundScope(*this);
  11026. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  11027. /*isStmtExpr=*/false);
  11028. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  11029. }
  11030. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  11031. MoveAssignOperator->markUsed(Context);
  11032. if (ASTMutationListener *L = getASTMutationListener()) {
  11033. L->CompletedImplicitDefinition(MoveAssignOperator);
  11034. }
  11035. }
  11036. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  11037. CXXRecordDecl *ClassDecl) {
  11038. // C++ [class.copy]p4:
  11039. // If the class definition does not explicitly declare a copy
  11040. // constructor, one is declared implicitly.
  11041. assert(ClassDecl->needsImplicitCopyConstructor());
  11042. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  11043. if (DSM.isAlreadyBeingDeclared())
  11044. return nullptr;
  11045. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11046. QualType ArgType = ClassType;
  11047. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  11048. if (Const)
  11049. ArgType = ArgType.withConst();
  11050. if (Context.getLangOpts().OpenCLCPlusPlus)
  11051. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  11052. ArgType = Context.getLValueReferenceType(ArgType);
  11053. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11054. CXXCopyConstructor,
  11055. Const);
  11056. DeclarationName Name
  11057. = Context.DeclarationNames.getCXXConstructorName(
  11058. Context.getCanonicalType(ClassType));
  11059. SourceLocation ClassLoc = ClassDecl->getLocation();
  11060. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11061. // An implicitly-declared copy constructor is an inline public
  11062. // member of its class.
  11063. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  11064. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11065. ExplicitSpecifier(),
  11066. /*isInline=*/true,
  11067. /*isImplicitlyDeclared=*/true,
  11068. Constexpr ? CSK_constexpr : CSK_unspecified);
  11069. CopyConstructor->setAccess(AS_public);
  11070. CopyConstructor->setDefaulted();
  11071. if (getLangOpts().CUDA) {
  11072. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  11073. CopyConstructor,
  11074. /* ConstRHS */ Const,
  11075. /* Diagnose */ false);
  11076. }
  11077. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  11078. // Add the parameter to the constructor.
  11079. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  11080. ClassLoc, ClassLoc,
  11081. /*IdentifierInfo=*/nullptr,
  11082. ArgType, /*TInfo=*/nullptr,
  11083. SC_None, nullptr);
  11084. CopyConstructor->setParams(FromParam);
  11085. CopyConstructor->setTrivial(
  11086. ClassDecl->needsOverloadResolutionForCopyConstructor()
  11087. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  11088. : ClassDecl->hasTrivialCopyConstructor());
  11089. CopyConstructor->setTrivialForCall(
  11090. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11091. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  11092. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  11093. TAH_ConsiderTrivialABI)
  11094. : ClassDecl->hasTrivialCopyConstructorForCall()));
  11095. // Note that we have declared this constructor.
  11096. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  11097. Scope *S = getScopeForContext(ClassDecl);
  11098. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  11099. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  11100. ClassDecl->setImplicitCopyConstructorIsDeleted();
  11101. SetDeclDeleted(CopyConstructor, ClassLoc);
  11102. }
  11103. if (S)
  11104. PushOnScopeChains(CopyConstructor, S, false);
  11105. ClassDecl->addDecl(CopyConstructor);
  11106. return CopyConstructor;
  11107. }
  11108. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  11109. CXXConstructorDecl *CopyConstructor) {
  11110. assert((CopyConstructor->isDefaulted() &&
  11111. CopyConstructor->isCopyConstructor() &&
  11112. !CopyConstructor->doesThisDeclarationHaveABody() &&
  11113. !CopyConstructor->isDeleted()) &&
  11114. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  11115. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  11116. return;
  11117. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  11118. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  11119. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  11120. // The exception specification is needed because we are defining the
  11121. // function.
  11122. ResolveExceptionSpec(CurrentLocation,
  11123. CopyConstructor->getType()->castAs<FunctionProtoType>());
  11124. MarkVTableUsed(CurrentLocation, ClassDecl);
  11125. // Add a context note for diagnostics produced after this point.
  11126. Scope.addContextNote(CurrentLocation);
  11127. // C++11 [class.copy]p7:
  11128. // The [definition of an implicitly declared copy constructor] is
  11129. // deprecated if the class has a user-declared copy assignment operator
  11130. // or a user-declared destructor.
  11131. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  11132. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  11133. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  11134. CopyConstructor->setInvalidDecl();
  11135. } else {
  11136. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  11137. ? CopyConstructor->getEndLoc()
  11138. : CopyConstructor->getLocation();
  11139. Sema::CompoundScopeRAII CompoundScope(*this);
  11140. CopyConstructor->setBody(
  11141. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  11142. CopyConstructor->markUsed(Context);
  11143. }
  11144. if (ASTMutationListener *L = getASTMutationListener()) {
  11145. L->CompletedImplicitDefinition(CopyConstructor);
  11146. }
  11147. }
  11148. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  11149. CXXRecordDecl *ClassDecl) {
  11150. assert(ClassDecl->needsImplicitMoveConstructor());
  11151. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  11152. if (DSM.isAlreadyBeingDeclared())
  11153. return nullptr;
  11154. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11155. QualType ArgType = ClassType;
  11156. if (Context.getLangOpts().OpenCLCPlusPlus)
  11157. ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
  11158. ArgType = Context.getRValueReferenceType(ArgType);
  11159. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11160. CXXMoveConstructor,
  11161. false);
  11162. DeclarationName Name
  11163. = Context.DeclarationNames.getCXXConstructorName(
  11164. Context.getCanonicalType(ClassType));
  11165. SourceLocation ClassLoc = ClassDecl->getLocation();
  11166. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11167. // C++11 [class.copy]p11:
  11168. // An implicitly-declared copy/move constructor is an inline public
  11169. // member of its class.
  11170. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  11171. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11172. ExplicitSpecifier(),
  11173. /*isInline=*/true,
  11174. /*isImplicitlyDeclared=*/true,
  11175. Constexpr ? CSK_constexpr : CSK_unspecified);
  11176. MoveConstructor->setAccess(AS_public);
  11177. MoveConstructor->setDefaulted();
  11178. if (getLangOpts().CUDA) {
  11179. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  11180. MoveConstructor,
  11181. /* ConstRHS */ false,
  11182. /* Diagnose */ false);
  11183. }
  11184. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  11185. // Add the parameter to the constructor.
  11186. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  11187. ClassLoc, ClassLoc,
  11188. /*IdentifierInfo=*/nullptr,
  11189. ArgType, /*TInfo=*/nullptr,
  11190. SC_None, nullptr);
  11191. MoveConstructor->setParams(FromParam);
  11192. MoveConstructor->setTrivial(
  11193. ClassDecl->needsOverloadResolutionForMoveConstructor()
  11194. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  11195. : ClassDecl->hasTrivialMoveConstructor());
  11196. MoveConstructor->setTrivialForCall(
  11197. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11198. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  11199. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  11200. TAH_ConsiderTrivialABI)
  11201. : ClassDecl->hasTrivialMoveConstructorForCall()));
  11202. // Note that we have declared this constructor.
  11203. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  11204. Scope *S = getScopeForContext(ClassDecl);
  11205. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  11206. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  11207. ClassDecl->setImplicitMoveConstructorIsDeleted();
  11208. SetDeclDeleted(MoveConstructor, ClassLoc);
  11209. }
  11210. if (S)
  11211. PushOnScopeChains(MoveConstructor, S, false);
  11212. ClassDecl->addDecl(MoveConstructor);
  11213. return MoveConstructor;
  11214. }
  11215. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  11216. CXXConstructorDecl *MoveConstructor) {
  11217. assert((MoveConstructor->isDefaulted() &&
  11218. MoveConstructor->isMoveConstructor() &&
  11219. !MoveConstructor->doesThisDeclarationHaveABody() &&
  11220. !MoveConstructor->isDeleted()) &&
  11221. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  11222. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  11223. return;
  11224. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  11225. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  11226. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  11227. // The exception specification is needed because we are defining the
  11228. // function.
  11229. ResolveExceptionSpec(CurrentLocation,
  11230. MoveConstructor->getType()->castAs<FunctionProtoType>());
  11231. MarkVTableUsed(CurrentLocation, ClassDecl);
  11232. // Add a context note for diagnostics produced after this point.
  11233. Scope.addContextNote(CurrentLocation);
  11234. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  11235. MoveConstructor->setInvalidDecl();
  11236. } else {
  11237. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  11238. ? MoveConstructor->getEndLoc()
  11239. : MoveConstructor->getLocation();
  11240. Sema::CompoundScopeRAII CompoundScope(*this);
  11241. MoveConstructor->setBody(ActOnCompoundStmt(
  11242. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  11243. MoveConstructor->markUsed(Context);
  11244. }
  11245. if (ASTMutationListener *L = getASTMutationListener()) {
  11246. L->CompletedImplicitDefinition(MoveConstructor);
  11247. }
  11248. }
  11249. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  11250. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  11251. }
  11252. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  11253. SourceLocation CurrentLocation,
  11254. CXXConversionDecl *Conv) {
  11255. SynthesizedFunctionScope Scope(*this, Conv);
  11256. assert(!Conv->getReturnType()->isUndeducedType());
  11257. CXXRecordDecl *Lambda = Conv->getParent();
  11258. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  11259. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  11260. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  11261. CallOp = InstantiateFunctionDeclaration(
  11262. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11263. if (!CallOp)
  11264. return;
  11265. Invoker = InstantiateFunctionDeclaration(
  11266. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11267. if (!Invoker)
  11268. return;
  11269. }
  11270. if (CallOp->isInvalidDecl())
  11271. return;
  11272. // Mark the call operator referenced (and add to pending instantiations
  11273. // if necessary).
  11274. // For both the conversion and static-invoker template specializations
  11275. // we construct their body's in this function, so no need to add them
  11276. // to the PendingInstantiations.
  11277. MarkFunctionReferenced(CurrentLocation, CallOp);
  11278. // Fill in the __invoke function with a dummy implementation. IR generation
  11279. // will fill in the actual details. Update its type in case it contained
  11280. // an 'auto'.
  11281. Invoker->markUsed(Context);
  11282. Invoker->setReferenced();
  11283. Invoker->setType(Conv->getReturnType()->getPointeeType());
  11284. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  11285. // Construct the body of the conversion function { return __invoke; }.
  11286. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  11287. VK_LValue, Conv->getLocation());
  11288. assert(FunctionRef && "Can't refer to __invoke function?");
  11289. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  11290. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  11291. Conv->getLocation()));
  11292. Conv->markUsed(Context);
  11293. Conv->setReferenced();
  11294. if (ASTMutationListener *L = getASTMutationListener()) {
  11295. L->CompletedImplicitDefinition(Conv);
  11296. L->CompletedImplicitDefinition(Invoker);
  11297. }
  11298. }
  11299. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  11300. SourceLocation CurrentLocation,
  11301. CXXConversionDecl *Conv)
  11302. {
  11303. assert(!Conv->getParent()->isGenericLambda());
  11304. SynthesizedFunctionScope Scope(*this, Conv);
  11305. // Copy-initialize the lambda object as needed to capture it.
  11306. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11307. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11308. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11309. Conv->getLocation(),
  11310. Conv, DerefThis);
  11311. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11312. // behavior. Note that only the general conversion function does this
  11313. // (since it's unusable otherwise); in the case where we inline the
  11314. // block literal, it has block literal lifetime semantics.
  11315. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11316. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11317. CK_CopyAndAutoreleaseBlockObject,
  11318. BuildBlock.get(), nullptr, VK_RValue);
  11319. if (BuildBlock.isInvalid()) {
  11320. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11321. Conv->setInvalidDecl();
  11322. return;
  11323. }
  11324. // Create the return statement that returns the block from the conversion
  11325. // function.
  11326. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11327. if (Return.isInvalid()) {
  11328. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11329. Conv->setInvalidDecl();
  11330. return;
  11331. }
  11332. // Set the body of the conversion function.
  11333. Stmt *ReturnS = Return.get();
  11334. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11335. Conv->getLocation()));
  11336. Conv->markUsed(Context);
  11337. // We're done; notify the mutation listener, if any.
  11338. if (ASTMutationListener *L = getASTMutationListener()) {
  11339. L->CompletedImplicitDefinition(Conv);
  11340. }
  11341. }
  11342. /// Determine whether the given list arguments contains exactly one
  11343. /// "real" (non-default) argument.
  11344. static bool hasOneRealArgument(MultiExprArg Args) {
  11345. switch (Args.size()) {
  11346. case 0:
  11347. return false;
  11348. default:
  11349. if (!Args[1]->isDefaultArgument())
  11350. return false;
  11351. LLVM_FALLTHROUGH;
  11352. case 1:
  11353. return !Args[0]->isDefaultArgument();
  11354. }
  11355. return false;
  11356. }
  11357. ExprResult
  11358. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11359. NamedDecl *FoundDecl,
  11360. CXXConstructorDecl *Constructor,
  11361. MultiExprArg ExprArgs,
  11362. bool HadMultipleCandidates,
  11363. bool IsListInitialization,
  11364. bool IsStdInitListInitialization,
  11365. bool RequiresZeroInit,
  11366. unsigned ConstructKind,
  11367. SourceRange ParenRange) {
  11368. bool Elidable = false;
  11369. // C++0x [class.copy]p34:
  11370. // When certain criteria are met, an implementation is allowed to
  11371. // omit the copy/move construction of a class object, even if the
  11372. // copy/move constructor and/or destructor for the object have
  11373. // side effects. [...]
  11374. // - when a temporary class object that has not been bound to a
  11375. // reference (12.2) would be copied/moved to a class object
  11376. // with the same cv-unqualified type, the copy/move operation
  11377. // can be omitted by constructing the temporary object
  11378. // directly into the target of the omitted copy/move
  11379. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11380. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11381. Expr *SubExpr = ExprArgs[0];
  11382. Elidable = SubExpr->isTemporaryObject(
  11383. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11384. }
  11385. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11386. FoundDecl, Constructor,
  11387. Elidable, ExprArgs, HadMultipleCandidates,
  11388. IsListInitialization,
  11389. IsStdInitListInitialization, RequiresZeroInit,
  11390. ConstructKind, ParenRange);
  11391. }
  11392. ExprResult
  11393. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11394. NamedDecl *FoundDecl,
  11395. CXXConstructorDecl *Constructor,
  11396. bool Elidable,
  11397. MultiExprArg ExprArgs,
  11398. bool HadMultipleCandidates,
  11399. bool IsListInitialization,
  11400. bool IsStdInitListInitialization,
  11401. bool RequiresZeroInit,
  11402. unsigned ConstructKind,
  11403. SourceRange ParenRange) {
  11404. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11405. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11406. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11407. return ExprError();
  11408. }
  11409. return BuildCXXConstructExpr(
  11410. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11411. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11412. RequiresZeroInit, ConstructKind, ParenRange);
  11413. }
  11414. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11415. /// including handling of its default argument expressions.
  11416. ExprResult
  11417. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11418. CXXConstructorDecl *Constructor,
  11419. bool Elidable,
  11420. MultiExprArg ExprArgs,
  11421. bool HadMultipleCandidates,
  11422. bool IsListInitialization,
  11423. bool IsStdInitListInitialization,
  11424. bool RequiresZeroInit,
  11425. unsigned ConstructKind,
  11426. SourceRange ParenRange) {
  11427. assert(declaresSameEntity(
  11428. Constructor->getParent(),
  11429. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11430. "given constructor for wrong type");
  11431. MarkFunctionReferenced(ConstructLoc, Constructor);
  11432. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11433. return ExprError();
  11434. return CXXConstructExpr::Create(
  11435. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11436. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11437. IsStdInitListInitialization, RequiresZeroInit,
  11438. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11439. ParenRange);
  11440. }
  11441. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11442. assert(Field->hasInClassInitializer());
  11443. // If we already have the in-class initializer nothing needs to be done.
  11444. if (Field->getInClassInitializer())
  11445. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11446. // If we might have already tried and failed to instantiate, don't try again.
  11447. if (Field->isInvalidDecl())
  11448. return ExprError();
  11449. // Maybe we haven't instantiated the in-class initializer. Go check the
  11450. // pattern FieldDecl to see if it has one.
  11451. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11452. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11453. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11454. DeclContext::lookup_result Lookup =
  11455. ClassPattern->lookup(Field->getDeclName());
  11456. // Lookup can return at most two results: the pattern for the field, or the
  11457. // injected class name of the parent record. No other member can have the
  11458. // same name as the field.
  11459. // In modules mode, lookup can return multiple results (coming from
  11460. // different modules).
  11461. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11462. "more than two lookup results for field name");
  11463. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11464. if (!Pattern) {
  11465. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11466. "cannot have other non-field member with same name");
  11467. for (auto L : Lookup)
  11468. if (isa<FieldDecl>(L)) {
  11469. Pattern = cast<FieldDecl>(L);
  11470. break;
  11471. }
  11472. assert(Pattern && "We must have set the Pattern!");
  11473. }
  11474. if (!Pattern->hasInClassInitializer() ||
  11475. InstantiateInClassInitializer(Loc, Field, Pattern,
  11476. getTemplateInstantiationArgs(Field))) {
  11477. // Don't diagnose this again.
  11478. Field->setInvalidDecl();
  11479. return ExprError();
  11480. }
  11481. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11482. }
  11483. // DR1351:
  11484. // If the brace-or-equal-initializer of a non-static data member
  11485. // invokes a defaulted default constructor of its class or of an
  11486. // enclosing class in a potentially evaluated subexpression, the
  11487. // program is ill-formed.
  11488. //
  11489. // This resolution is unworkable: the exception specification of the
  11490. // default constructor can be needed in an unevaluated context, in
  11491. // particular, in the operand of a noexcept-expression, and we can be
  11492. // unable to compute an exception specification for an enclosed class.
  11493. //
  11494. // Any attempt to resolve the exception specification of a defaulted default
  11495. // constructor before the initializer is lexically complete will ultimately
  11496. // come here at which point we can diagnose it.
  11497. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11498. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11499. << OutermostClass << Field;
  11500. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11501. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11502. if (!isSFINAEContext())
  11503. Field->setInvalidDecl();
  11504. return ExprError();
  11505. }
  11506. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11507. if (VD->isInvalidDecl()) return;
  11508. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11509. if (ClassDecl->isInvalidDecl()) return;
  11510. if (ClassDecl->hasIrrelevantDestructor()) return;
  11511. if (ClassDecl->isDependentContext()) return;
  11512. if (VD->isNoDestroy(getASTContext()))
  11513. return;
  11514. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11515. // If this is an array, we'll require the destructor during initialization, so
  11516. // we can skip over this. We still want to emit exit-time destructor warnings
  11517. // though.
  11518. if (!VD->getType()->isArrayType()) {
  11519. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11520. CheckDestructorAccess(VD->getLocation(), Destructor,
  11521. PDiag(diag::err_access_dtor_var)
  11522. << VD->getDeclName() << VD->getType());
  11523. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11524. }
  11525. if (Destructor->isTrivial()) return;
  11526. if (!VD->hasGlobalStorage()) return;
  11527. // Emit warning for non-trivial dtor in global scope (a real global,
  11528. // class-static, function-static).
  11529. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11530. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11531. if (!VD->isStaticLocal())
  11532. Diag(VD->getLocation(), diag::warn_global_destructor);
  11533. }
  11534. /// Given a constructor and the set of arguments provided for the
  11535. /// constructor, convert the arguments and add any required default arguments
  11536. /// to form a proper call to this constructor.
  11537. ///
  11538. /// \returns true if an error occurred, false otherwise.
  11539. bool
  11540. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11541. MultiExprArg ArgsPtr,
  11542. SourceLocation Loc,
  11543. SmallVectorImpl<Expr*> &ConvertedArgs,
  11544. bool AllowExplicit,
  11545. bool IsListInitialization) {
  11546. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11547. unsigned NumArgs = ArgsPtr.size();
  11548. Expr **Args = ArgsPtr.data();
  11549. const FunctionProtoType *Proto
  11550. = Constructor->getType()->getAs<FunctionProtoType>();
  11551. assert(Proto && "Constructor without a prototype?");
  11552. unsigned NumParams = Proto->getNumParams();
  11553. // If too few arguments are available, we'll fill in the rest with defaults.
  11554. if (NumArgs < NumParams)
  11555. ConvertedArgs.reserve(NumParams);
  11556. else
  11557. ConvertedArgs.reserve(NumArgs);
  11558. VariadicCallType CallType =
  11559. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11560. SmallVector<Expr *, 8> AllArgs;
  11561. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11562. Proto, 0,
  11563. llvm::makeArrayRef(Args, NumArgs),
  11564. AllArgs,
  11565. CallType, AllowExplicit,
  11566. IsListInitialization);
  11567. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11568. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11569. CheckConstructorCall(Constructor,
  11570. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11571. Proto, Loc);
  11572. return Invalid;
  11573. }
  11574. static inline bool
  11575. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11576. const FunctionDecl *FnDecl) {
  11577. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11578. if (isa<NamespaceDecl>(DC)) {
  11579. return SemaRef.Diag(FnDecl->getLocation(),
  11580. diag::err_operator_new_delete_declared_in_namespace)
  11581. << FnDecl->getDeclName();
  11582. }
  11583. if (isa<TranslationUnitDecl>(DC) &&
  11584. FnDecl->getStorageClass() == SC_Static) {
  11585. return SemaRef.Diag(FnDecl->getLocation(),
  11586. diag::err_operator_new_delete_declared_static)
  11587. << FnDecl->getDeclName();
  11588. }
  11589. return false;
  11590. }
  11591. static QualType
  11592. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11593. QualType QTy = PtrTy->getPointeeType();
  11594. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11595. return SemaRef.Context.getPointerType(QTy);
  11596. }
  11597. static inline bool
  11598. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11599. CanQualType ExpectedResultType,
  11600. CanQualType ExpectedFirstParamType,
  11601. unsigned DependentParamTypeDiag,
  11602. unsigned InvalidParamTypeDiag) {
  11603. QualType ResultType =
  11604. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11605. // Check that the result type is not dependent.
  11606. if (ResultType->isDependentType())
  11607. return SemaRef.Diag(FnDecl->getLocation(),
  11608. diag::err_operator_new_delete_dependent_result_type)
  11609. << FnDecl->getDeclName() << ExpectedResultType;
  11610. // The operator is valid on any address space for OpenCL.
  11611. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11612. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11613. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11614. }
  11615. }
  11616. // Check that the result type is what we expect.
  11617. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11618. return SemaRef.Diag(FnDecl->getLocation(),
  11619. diag::err_operator_new_delete_invalid_result_type)
  11620. << FnDecl->getDeclName() << ExpectedResultType;
  11621. // A function template must have at least 2 parameters.
  11622. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11623. return SemaRef.Diag(FnDecl->getLocation(),
  11624. diag::err_operator_new_delete_template_too_few_parameters)
  11625. << FnDecl->getDeclName();
  11626. // The function decl must have at least 1 parameter.
  11627. if (FnDecl->getNumParams() == 0)
  11628. return SemaRef.Diag(FnDecl->getLocation(),
  11629. diag::err_operator_new_delete_too_few_parameters)
  11630. << FnDecl->getDeclName();
  11631. // Check the first parameter type is not dependent.
  11632. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11633. if (FirstParamType->isDependentType())
  11634. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11635. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11636. // Check that the first parameter type is what we expect.
  11637. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11638. // The operator is valid on any address space for OpenCL.
  11639. if (auto *PtrTy =
  11640. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11641. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11642. }
  11643. }
  11644. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11645. ExpectedFirstParamType)
  11646. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11647. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11648. return false;
  11649. }
  11650. static bool
  11651. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11652. // C++ [basic.stc.dynamic.allocation]p1:
  11653. // A program is ill-formed if an allocation function is declared in a
  11654. // namespace scope other than global scope or declared static in global
  11655. // scope.
  11656. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11657. return true;
  11658. CanQualType SizeTy =
  11659. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11660. // C++ [basic.stc.dynamic.allocation]p1:
  11661. // The return type shall be void*. The first parameter shall have type
  11662. // std::size_t.
  11663. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11664. SizeTy,
  11665. diag::err_operator_new_dependent_param_type,
  11666. diag::err_operator_new_param_type))
  11667. return true;
  11668. // C++ [basic.stc.dynamic.allocation]p1:
  11669. // The first parameter shall not have an associated default argument.
  11670. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11671. return SemaRef.Diag(FnDecl->getLocation(),
  11672. diag::err_operator_new_default_arg)
  11673. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11674. return false;
  11675. }
  11676. static bool
  11677. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11678. // C++ [basic.stc.dynamic.deallocation]p1:
  11679. // A program is ill-formed if deallocation functions are declared in a
  11680. // namespace scope other than global scope or declared static in global
  11681. // scope.
  11682. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11683. return true;
  11684. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11685. // C++ P0722:
  11686. // Within a class C, the first parameter of a destroying operator delete
  11687. // shall be of type C *. The first parameter of any other deallocation
  11688. // function shall be of type void *.
  11689. CanQualType ExpectedFirstParamType =
  11690. MD && MD->isDestroyingOperatorDelete()
  11691. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11692. SemaRef.Context.getRecordType(MD->getParent())))
  11693. : SemaRef.Context.VoidPtrTy;
  11694. // C++ [basic.stc.dynamic.deallocation]p2:
  11695. // Each deallocation function shall return void
  11696. if (CheckOperatorNewDeleteTypes(
  11697. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11698. diag::err_operator_delete_dependent_param_type,
  11699. diag::err_operator_delete_param_type))
  11700. return true;
  11701. // C++ P0722:
  11702. // A destroying operator delete shall be a usual deallocation function.
  11703. if (MD && !MD->getParent()->isDependentContext() &&
  11704. MD->isDestroyingOperatorDelete() &&
  11705. !SemaRef.isUsualDeallocationFunction(MD)) {
  11706. SemaRef.Diag(MD->getLocation(),
  11707. diag::err_destroying_operator_delete_not_usual);
  11708. return true;
  11709. }
  11710. return false;
  11711. }
  11712. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11713. /// of this overloaded operator is well-formed. If so, returns false;
  11714. /// otherwise, emits appropriate diagnostics and returns true.
  11715. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11716. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11717. "Expected an overloaded operator declaration");
  11718. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11719. // C++ [over.oper]p5:
  11720. // The allocation and deallocation functions, operator new,
  11721. // operator new[], operator delete and operator delete[], are
  11722. // described completely in 3.7.3. The attributes and restrictions
  11723. // found in the rest of this subclause do not apply to them unless
  11724. // explicitly stated in 3.7.3.
  11725. if (Op == OO_Delete || Op == OO_Array_Delete)
  11726. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11727. if (Op == OO_New || Op == OO_Array_New)
  11728. return CheckOperatorNewDeclaration(*this, FnDecl);
  11729. // C++ [over.oper]p6:
  11730. // An operator function shall either be a non-static member
  11731. // function or be a non-member function and have at least one
  11732. // parameter whose type is a class, a reference to a class, an
  11733. // enumeration, or a reference to an enumeration.
  11734. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11735. if (MethodDecl->isStatic())
  11736. return Diag(FnDecl->getLocation(),
  11737. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11738. } else {
  11739. bool ClassOrEnumParam = false;
  11740. for (auto Param : FnDecl->parameters()) {
  11741. QualType ParamType = Param->getType().getNonReferenceType();
  11742. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11743. ParamType->isEnumeralType()) {
  11744. ClassOrEnumParam = true;
  11745. break;
  11746. }
  11747. }
  11748. if (!ClassOrEnumParam)
  11749. return Diag(FnDecl->getLocation(),
  11750. diag::err_operator_overload_needs_class_or_enum)
  11751. << FnDecl->getDeclName();
  11752. }
  11753. // C++ [over.oper]p8:
  11754. // An operator function cannot have default arguments (8.3.6),
  11755. // except where explicitly stated below.
  11756. //
  11757. // Only the function-call operator allows default arguments
  11758. // (C++ [over.call]p1).
  11759. if (Op != OO_Call) {
  11760. for (auto Param : FnDecl->parameters()) {
  11761. if (Param->hasDefaultArg())
  11762. return Diag(Param->getLocation(),
  11763. diag::err_operator_overload_default_arg)
  11764. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11765. }
  11766. }
  11767. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11768. { false, false, false }
  11769. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11770. , { Unary, Binary, MemberOnly }
  11771. #include "clang/Basic/OperatorKinds.def"
  11772. };
  11773. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11774. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11775. bool MustBeMemberOperator = OperatorUses[Op][2];
  11776. // C++ [over.oper]p8:
  11777. // [...] Operator functions cannot have more or fewer parameters
  11778. // than the number required for the corresponding operator, as
  11779. // described in the rest of this subclause.
  11780. unsigned NumParams = FnDecl->getNumParams()
  11781. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11782. if (Op != OO_Call &&
  11783. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11784. (NumParams == 2 && !CanBeBinaryOperator) ||
  11785. (NumParams < 1) || (NumParams > 2))) {
  11786. // We have the wrong number of parameters.
  11787. unsigned ErrorKind;
  11788. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11789. ErrorKind = 2; // 2 -> unary or binary.
  11790. } else if (CanBeUnaryOperator) {
  11791. ErrorKind = 0; // 0 -> unary
  11792. } else {
  11793. assert(CanBeBinaryOperator &&
  11794. "All non-call overloaded operators are unary or binary!");
  11795. ErrorKind = 1; // 1 -> binary
  11796. }
  11797. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11798. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11799. }
  11800. // Overloaded operators other than operator() cannot be variadic.
  11801. if (Op != OO_Call &&
  11802. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11803. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11804. << FnDecl->getDeclName();
  11805. }
  11806. // Some operators must be non-static member functions.
  11807. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11808. return Diag(FnDecl->getLocation(),
  11809. diag::err_operator_overload_must_be_member)
  11810. << FnDecl->getDeclName();
  11811. }
  11812. // C++ [over.inc]p1:
  11813. // The user-defined function called operator++ implements the
  11814. // prefix and postfix ++ operator. If this function is a member
  11815. // function with no parameters, or a non-member function with one
  11816. // parameter of class or enumeration type, it defines the prefix
  11817. // increment operator ++ for objects of that type. If the function
  11818. // is a member function with one parameter (which shall be of type
  11819. // int) or a non-member function with two parameters (the second
  11820. // of which shall be of type int), it defines the postfix
  11821. // increment operator ++ for objects of that type.
  11822. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11823. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11824. QualType ParamType = LastParam->getType();
  11825. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11826. !ParamType->isDependentType())
  11827. return Diag(LastParam->getLocation(),
  11828. diag::err_operator_overload_post_incdec_must_be_int)
  11829. << LastParam->getType() << (Op == OO_MinusMinus);
  11830. }
  11831. return false;
  11832. }
  11833. static bool
  11834. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11835. FunctionTemplateDecl *TpDecl) {
  11836. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11837. // Must have one or two template parameters.
  11838. if (TemplateParams->size() == 1) {
  11839. NonTypeTemplateParmDecl *PmDecl =
  11840. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11841. // The template parameter must be a char parameter pack.
  11842. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11843. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11844. return false;
  11845. } else if (TemplateParams->size() == 2) {
  11846. TemplateTypeParmDecl *PmType =
  11847. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11848. NonTypeTemplateParmDecl *PmArgs =
  11849. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11850. // The second template parameter must be a parameter pack with the
  11851. // first template parameter as its type.
  11852. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11853. PmArgs->isTemplateParameterPack()) {
  11854. const TemplateTypeParmType *TArgs =
  11855. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11856. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11857. TArgs->getIndex() == PmType->getIndex()) {
  11858. if (!SemaRef.inTemplateInstantiation())
  11859. SemaRef.Diag(TpDecl->getLocation(),
  11860. diag::ext_string_literal_operator_template);
  11861. return false;
  11862. }
  11863. }
  11864. }
  11865. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11866. diag::err_literal_operator_template)
  11867. << TpDecl->getTemplateParameters()->getSourceRange();
  11868. return true;
  11869. }
  11870. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11871. /// of this literal operator function is well-formed. If so, returns
  11872. /// false; otherwise, emits appropriate diagnostics and returns true.
  11873. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11874. if (isa<CXXMethodDecl>(FnDecl)) {
  11875. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11876. << FnDecl->getDeclName();
  11877. return true;
  11878. }
  11879. if (FnDecl->isExternC()) {
  11880. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11881. if (const LinkageSpecDecl *LSD =
  11882. FnDecl->getDeclContext()->getExternCContext())
  11883. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11884. return true;
  11885. }
  11886. // This might be the definition of a literal operator template.
  11887. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11888. // This might be a specialization of a literal operator template.
  11889. if (!TpDecl)
  11890. TpDecl = FnDecl->getPrimaryTemplate();
  11891. // template <char...> type operator "" name() and
  11892. // template <class T, T...> type operator "" name() are the only valid
  11893. // template signatures, and the only valid signatures with no parameters.
  11894. if (TpDecl) {
  11895. if (FnDecl->param_size() != 0) {
  11896. Diag(FnDecl->getLocation(),
  11897. diag::err_literal_operator_template_with_params);
  11898. return true;
  11899. }
  11900. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11901. return true;
  11902. } else if (FnDecl->param_size() == 1) {
  11903. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11904. QualType ParamType = Param->getType().getUnqualifiedType();
  11905. // Only unsigned long long int, long double, any character type, and const
  11906. // char * are allowed as the only parameters.
  11907. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11908. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11909. Context.hasSameType(ParamType, Context.CharTy) ||
  11910. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11911. Context.hasSameType(ParamType, Context.Char8Ty) ||
  11912. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11913. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11914. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11915. QualType InnerType = Ptr->getPointeeType();
  11916. // Pointer parameter must be a const char *.
  11917. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  11918. Context.CharTy) &&
  11919. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  11920. Diag(Param->getSourceRange().getBegin(),
  11921. diag::err_literal_operator_param)
  11922. << ParamType << "'const char *'" << Param->getSourceRange();
  11923. return true;
  11924. }
  11925. } else if (ParamType->isRealFloatingType()) {
  11926. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11927. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  11928. return true;
  11929. } else if (ParamType->isIntegerType()) {
  11930. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11931. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  11932. return true;
  11933. } else {
  11934. Diag(Param->getSourceRange().getBegin(),
  11935. diag::err_literal_operator_invalid_param)
  11936. << ParamType << Param->getSourceRange();
  11937. return true;
  11938. }
  11939. } else if (FnDecl->param_size() == 2) {
  11940. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  11941. // First, verify that the first parameter is correct.
  11942. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  11943. // Two parameter function must have a pointer to const as a
  11944. // first parameter; let's strip those qualifiers.
  11945. const PointerType *PT = FirstParamType->getAs<PointerType>();
  11946. if (!PT) {
  11947. Diag((*Param)->getSourceRange().getBegin(),
  11948. diag::err_literal_operator_param)
  11949. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11950. return true;
  11951. }
  11952. QualType PointeeType = PT->getPointeeType();
  11953. // First parameter must be const
  11954. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  11955. Diag((*Param)->getSourceRange().getBegin(),
  11956. diag::err_literal_operator_param)
  11957. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11958. return true;
  11959. }
  11960. QualType InnerType = PointeeType.getUnqualifiedType();
  11961. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  11962. // const char32_t* are allowed as the first parameter to a two-parameter
  11963. // function
  11964. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  11965. Context.hasSameType(InnerType, Context.WideCharTy) ||
  11966. Context.hasSameType(InnerType, Context.Char8Ty) ||
  11967. Context.hasSameType(InnerType, Context.Char16Ty) ||
  11968. Context.hasSameType(InnerType, Context.Char32Ty))) {
  11969. Diag((*Param)->getSourceRange().getBegin(),
  11970. diag::err_literal_operator_param)
  11971. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11972. return true;
  11973. }
  11974. // Move on to the second and final parameter.
  11975. ++Param;
  11976. // The second parameter must be a std::size_t.
  11977. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  11978. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  11979. Diag((*Param)->getSourceRange().getBegin(),
  11980. diag::err_literal_operator_param)
  11981. << SecondParamType << Context.getSizeType()
  11982. << (*Param)->getSourceRange();
  11983. return true;
  11984. }
  11985. } else {
  11986. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  11987. return true;
  11988. }
  11989. // Parameters are good.
  11990. // A parameter-declaration-clause containing a default argument is not
  11991. // equivalent to any of the permitted forms.
  11992. for (auto Param : FnDecl->parameters()) {
  11993. if (Param->hasDefaultArg()) {
  11994. Diag(Param->getDefaultArgRange().getBegin(),
  11995. diag::err_literal_operator_default_argument)
  11996. << Param->getDefaultArgRange();
  11997. break;
  11998. }
  11999. }
  12000. StringRef LiteralName
  12001. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  12002. if (LiteralName[0] != '_' &&
  12003. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  12004. // C++11 [usrlit.suffix]p1:
  12005. // Literal suffix identifiers that do not start with an underscore
  12006. // are reserved for future standardization.
  12007. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  12008. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  12009. }
  12010. return false;
  12011. }
  12012. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  12013. /// linkage specification, including the language and (if present)
  12014. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  12015. /// language string literal. LBraceLoc, if valid, provides the location of
  12016. /// the '{' brace. Otherwise, this linkage specification does not
  12017. /// have any braces.
  12018. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  12019. Expr *LangStr,
  12020. SourceLocation LBraceLoc) {
  12021. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  12022. if (!Lit->isAscii()) {
  12023. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  12024. << LangStr->getSourceRange();
  12025. return nullptr;
  12026. }
  12027. StringRef Lang = Lit->getString();
  12028. LinkageSpecDecl::LanguageIDs Language;
  12029. if (Lang == "C")
  12030. Language = LinkageSpecDecl::lang_c;
  12031. else if (Lang == "C++")
  12032. Language = LinkageSpecDecl::lang_cxx;
  12033. else {
  12034. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  12035. << LangStr->getSourceRange();
  12036. return nullptr;
  12037. }
  12038. // FIXME: Add all the various semantics of linkage specifications
  12039. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  12040. LangStr->getExprLoc(), Language,
  12041. LBraceLoc.isValid());
  12042. CurContext->addDecl(D);
  12043. PushDeclContext(S, D);
  12044. return D;
  12045. }
  12046. /// ActOnFinishLinkageSpecification - Complete the definition of
  12047. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  12048. /// valid, it's the position of the closing '}' brace in a linkage
  12049. /// specification that uses braces.
  12050. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  12051. Decl *LinkageSpec,
  12052. SourceLocation RBraceLoc) {
  12053. if (RBraceLoc.isValid()) {
  12054. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  12055. LSDecl->setRBraceLoc(RBraceLoc);
  12056. }
  12057. PopDeclContext();
  12058. return LinkageSpec;
  12059. }
  12060. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  12061. const ParsedAttributesView &AttrList,
  12062. SourceLocation SemiLoc) {
  12063. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  12064. // Attribute declarations appertain to empty declaration so we handle
  12065. // them here.
  12066. ProcessDeclAttributeList(S, ED, AttrList);
  12067. CurContext->addDecl(ED);
  12068. return ED;
  12069. }
  12070. /// Perform semantic analysis for the variable declaration that
  12071. /// occurs within a C++ catch clause, returning the newly-created
  12072. /// variable.
  12073. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  12074. TypeSourceInfo *TInfo,
  12075. SourceLocation StartLoc,
  12076. SourceLocation Loc,
  12077. IdentifierInfo *Name) {
  12078. bool Invalid = false;
  12079. QualType ExDeclType = TInfo->getType();
  12080. // Arrays and functions decay.
  12081. if (ExDeclType->isArrayType())
  12082. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  12083. else if (ExDeclType->isFunctionType())
  12084. ExDeclType = Context.getPointerType(ExDeclType);
  12085. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  12086. // The exception-declaration shall not denote a pointer or reference to an
  12087. // incomplete type, other than [cv] void*.
  12088. // N2844 forbids rvalue references.
  12089. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  12090. Diag(Loc, diag::err_catch_rvalue_ref);
  12091. Invalid = true;
  12092. }
  12093. if (ExDeclType->isVariablyModifiedType()) {
  12094. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  12095. Invalid = true;
  12096. }
  12097. QualType BaseType = ExDeclType;
  12098. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  12099. unsigned DK = diag::err_catch_incomplete;
  12100. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  12101. BaseType = Ptr->getPointeeType();
  12102. Mode = 1;
  12103. DK = diag::err_catch_incomplete_ptr;
  12104. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  12105. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  12106. BaseType = Ref->getPointeeType();
  12107. Mode = 2;
  12108. DK = diag::err_catch_incomplete_ref;
  12109. }
  12110. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  12111. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  12112. Invalid = true;
  12113. if (!Invalid && !ExDeclType->isDependentType() &&
  12114. RequireNonAbstractType(Loc, ExDeclType,
  12115. diag::err_abstract_type_in_decl,
  12116. AbstractVariableType))
  12117. Invalid = true;
  12118. // Only the non-fragile NeXT runtime currently supports C++ catches
  12119. // of ObjC types, and no runtime supports catching ObjC types by value.
  12120. if (!Invalid && getLangOpts().ObjC) {
  12121. QualType T = ExDeclType;
  12122. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  12123. T = RT->getPointeeType();
  12124. if (T->isObjCObjectType()) {
  12125. Diag(Loc, diag::err_objc_object_catch);
  12126. Invalid = true;
  12127. } else if (T->isObjCObjectPointerType()) {
  12128. // FIXME: should this be a test for macosx-fragile specifically?
  12129. if (getLangOpts().ObjCRuntime.isFragile())
  12130. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  12131. }
  12132. }
  12133. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  12134. ExDeclType, TInfo, SC_None);
  12135. ExDecl->setExceptionVariable(true);
  12136. // In ARC, infer 'retaining' for variables of retainable type.
  12137. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  12138. Invalid = true;
  12139. if (!Invalid && !ExDeclType->isDependentType()) {
  12140. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  12141. // Insulate this from anything else we might currently be parsing.
  12142. EnterExpressionEvaluationContext scope(
  12143. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12144. // C++ [except.handle]p16:
  12145. // The object declared in an exception-declaration or, if the
  12146. // exception-declaration does not specify a name, a temporary (12.2) is
  12147. // copy-initialized (8.5) from the exception object. [...]
  12148. // The object is destroyed when the handler exits, after the destruction
  12149. // of any automatic objects initialized within the handler.
  12150. //
  12151. // We just pretend to initialize the object with itself, then make sure
  12152. // it can be destroyed later.
  12153. QualType initType = Context.getExceptionObjectType(ExDeclType);
  12154. InitializedEntity entity =
  12155. InitializedEntity::InitializeVariable(ExDecl);
  12156. InitializationKind initKind =
  12157. InitializationKind::CreateCopy(Loc, SourceLocation());
  12158. Expr *opaqueValue =
  12159. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  12160. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  12161. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  12162. if (result.isInvalid())
  12163. Invalid = true;
  12164. else {
  12165. // If the constructor used was non-trivial, set this as the
  12166. // "initializer".
  12167. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  12168. if (!construct->getConstructor()->isTrivial()) {
  12169. Expr *init = MaybeCreateExprWithCleanups(construct);
  12170. ExDecl->setInit(init);
  12171. }
  12172. // And make sure it's destructable.
  12173. FinalizeVarWithDestructor(ExDecl, recordType);
  12174. }
  12175. }
  12176. }
  12177. if (Invalid)
  12178. ExDecl->setInvalidDecl();
  12179. return ExDecl;
  12180. }
  12181. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  12182. /// handler.
  12183. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  12184. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12185. bool Invalid = D.isInvalidType();
  12186. // Check for unexpanded parameter packs.
  12187. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12188. UPPC_ExceptionType)) {
  12189. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  12190. D.getIdentifierLoc());
  12191. Invalid = true;
  12192. }
  12193. IdentifierInfo *II = D.getIdentifier();
  12194. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  12195. LookupOrdinaryName,
  12196. ForVisibleRedeclaration)) {
  12197. // The scope should be freshly made just for us. There is just no way
  12198. // it contains any previous declaration, except for function parameters in
  12199. // a function-try-block's catch statement.
  12200. assert(!S->isDeclScope(PrevDecl));
  12201. if (isDeclInScope(PrevDecl, CurContext, S)) {
  12202. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  12203. << D.getIdentifier();
  12204. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12205. Invalid = true;
  12206. } else if (PrevDecl->isTemplateParameter())
  12207. // Maybe we will complain about the shadowed template parameter.
  12208. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12209. }
  12210. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  12211. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  12212. << D.getCXXScopeSpec().getRange();
  12213. Invalid = true;
  12214. }
  12215. VarDecl *ExDecl = BuildExceptionDeclaration(
  12216. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  12217. if (Invalid)
  12218. ExDecl->setInvalidDecl();
  12219. // Add the exception declaration into this scope.
  12220. if (II)
  12221. PushOnScopeChains(ExDecl, S);
  12222. else
  12223. CurContext->addDecl(ExDecl);
  12224. ProcessDeclAttributes(S, ExDecl, D);
  12225. return ExDecl;
  12226. }
  12227. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12228. Expr *AssertExpr,
  12229. Expr *AssertMessageExpr,
  12230. SourceLocation RParenLoc) {
  12231. StringLiteral *AssertMessage =
  12232. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  12233. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  12234. return nullptr;
  12235. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  12236. AssertMessage, RParenLoc, false);
  12237. }
  12238. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12239. Expr *AssertExpr,
  12240. StringLiteral *AssertMessage,
  12241. SourceLocation RParenLoc,
  12242. bool Failed) {
  12243. assert(AssertExpr != nullptr && "Expected non-null condition");
  12244. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  12245. !Failed) {
  12246. // In a static_assert-declaration, the constant-expression shall be a
  12247. // constant expression that can be contextually converted to bool.
  12248. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  12249. if (Converted.isInvalid())
  12250. Failed = true;
  12251. llvm::APSInt Cond;
  12252. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  12253. diag::err_static_assert_expression_is_not_constant,
  12254. /*AllowFold=*/false).isInvalid())
  12255. Failed = true;
  12256. if (!Failed && !Cond) {
  12257. SmallString<256> MsgBuffer;
  12258. llvm::raw_svector_ostream Msg(MsgBuffer);
  12259. if (AssertMessage)
  12260. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  12261. Expr *InnerCond = nullptr;
  12262. std::string InnerCondDescription;
  12263. std::tie(InnerCond, InnerCondDescription) =
  12264. findFailedBooleanCondition(Converted.get());
  12265. if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  12266. && !isa<IntegerLiteral>(InnerCond)) {
  12267. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  12268. << InnerCondDescription << !AssertMessage
  12269. << Msg.str() << InnerCond->getSourceRange();
  12270. } else {
  12271. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  12272. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  12273. }
  12274. Failed = true;
  12275. }
  12276. }
  12277. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  12278. /*DiscardedValue*/false,
  12279. /*IsConstexpr*/true);
  12280. if (FullAssertExpr.isInvalid())
  12281. Failed = true;
  12282. else
  12283. AssertExpr = FullAssertExpr.get();
  12284. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  12285. AssertExpr, AssertMessage, RParenLoc,
  12286. Failed);
  12287. CurContext->addDecl(Decl);
  12288. return Decl;
  12289. }
  12290. /// Perform semantic analysis of the given friend type declaration.
  12291. ///
  12292. /// \returns A friend declaration that.
  12293. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  12294. SourceLocation FriendLoc,
  12295. TypeSourceInfo *TSInfo) {
  12296. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  12297. QualType T = TSInfo->getType();
  12298. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  12299. // C++03 [class.friend]p2:
  12300. // An elaborated-type-specifier shall be used in a friend declaration
  12301. // for a class.*
  12302. //
  12303. // * The class-key of the elaborated-type-specifier is required.
  12304. if (!CodeSynthesisContexts.empty()) {
  12305. // Do not complain about the form of friend template types during any kind
  12306. // of code synthesis. For template instantiation, we will have complained
  12307. // when the template was defined.
  12308. } else {
  12309. if (!T->isElaboratedTypeSpecifier()) {
  12310. // If we evaluated the type to a record type, suggest putting
  12311. // a tag in front.
  12312. if (const RecordType *RT = T->getAs<RecordType>()) {
  12313. RecordDecl *RD = RT->getDecl();
  12314. SmallString<16> InsertionText(" ");
  12315. InsertionText += RD->getKindName();
  12316. Diag(TypeRange.getBegin(),
  12317. getLangOpts().CPlusPlus11 ?
  12318. diag::warn_cxx98_compat_unelaborated_friend_type :
  12319. diag::ext_unelaborated_friend_type)
  12320. << (unsigned) RD->getTagKind()
  12321. << T
  12322. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12323. InsertionText);
  12324. } else {
  12325. Diag(FriendLoc,
  12326. getLangOpts().CPlusPlus11 ?
  12327. diag::warn_cxx98_compat_nonclass_type_friend :
  12328. diag::ext_nonclass_type_friend)
  12329. << T
  12330. << TypeRange;
  12331. }
  12332. } else if (T->getAs<EnumType>()) {
  12333. Diag(FriendLoc,
  12334. getLangOpts().CPlusPlus11 ?
  12335. diag::warn_cxx98_compat_enum_friend :
  12336. diag::ext_enum_friend)
  12337. << T
  12338. << TypeRange;
  12339. }
  12340. // C++11 [class.friend]p3:
  12341. // A friend declaration that does not declare a function shall have one
  12342. // of the following forms:
  12343. // friend elaborated-type-specifier ;
  12344. // friend simple-type-specifier ;
  12345. // friend typename-specifier ;
  12346. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12347. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12348. }
  12349. // If the type specifier in a friend declaration designates a (possibly
  12350. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12351. // the friend declaration is ignored.
  12352. return FriendDecl::Create(Context, CurContext,
  12353. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12354. FriendLoc);
  12355. }
  12356. /// Handle a friend tag declaration where the scope specifier was
  12357. /// templated.
  12358. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12359. unsigned TagSpec, SourceLocation TagLoc,
  12360. CXXScopeSpec &SS, IdentifierInfo *Name,
  12361. SourceLocation NameLoc,
  12362. const ParsedAttributesView &Attr,
  12363. MultiTemplateParamsArg TempParamLists) {
  12364. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12365. bool IsMemberSpecialization = false;
  12366. bool Invalid = false;
  12367. if (TemplateParameterList *TemplateParams =
  12368. MatchTemplateParametersToScopeSpecifier(
  12369. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12370. IsMemberSpecialization, Invalid)) {
  12371. if (TemplateParams->size() > 0) {
  12372. // This is a declaration of a class template.
  12373. if (Invalid)
  12374. return nullptr;
  12375. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12376. NameLoc, Attr, TemplateParams, AS_public,
  12377. /*ModulePrivateLoc=*/SourceLocation(),
  12378. FriendLoc, TempParamLists.size() - 1,
  12379. TempParamLists.data()).get();
  12380. } else {
  12381. // The "template<>" header is extraneous.
  12382. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12383. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12384. IsMemberSpecialization = true;
  12385. }
  12386. }
  12387. if (Invalid) return nullptr;
  12388. bool isAllExplicitSpecializations = true;
  12389. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12390. if (TempParamLists[I]->size()) {
  12391. isAllExplicitSpecializations = false;
  12392. break;
  12393. }
  12394. }
  12395. // FIXME: don't ignore attributes.
  12396. // If it's explicit specializations all the way down, just forget
  12397. // about the template header and build an appropriate non-templated
  12398. // friend. TODO: for source fidelity, remember the headers.
  12399. if (isAllExplicitSpecializations) {
  12400. if (SS.isEmpty()) {
  12401. bool Owned = false;
  12402. bool IsDependent = false;
  12403. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12404. Attr, AS_public,
  12405. /*ModulePrivateLoc=*/SourceLocation(),
  12406. MultiTemplateParamsArg(), Owned, IsDependent,
  12407. /*ScopedEnumKWLoc=*/SourceLocation(),
  12408. /*ScopedEnumUsesClassTag=*/false,
  12409. /*UnderlyingType=*/TypeResult(),
  12410. /*IsTypeSpecifier=*/false,
  12411. /*IsTemplateParamOrArg=*/false);
  12412. }
  12413. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12414. ElaboratedTypeKeyword Keyword
  12415. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12416. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12417. *Name, NameLoc);
  12418. if (T.isNull())
  12419. return nullptr;
  12420. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12421. if (isa<DependentNameType>(T)) {
  12422. DependentNameTypeLoc TL =
  12423. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12424. TL.setElaboratedKeywordLoc(TagLoc);
  12425. TL.setQualifierLoc(QualifierLoc);
  12426. TL.setNameLoc(NameLoc);
  12427. } else {
  12428. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12429. TL.setElaboratedKeywordLoc(TagLoc);
  12430. TL.setQualifierLoc(QualifierLoc);
  12431. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12432. }
  12433. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12434. TSI, FriendLoc, TempParamLists);
  12435. Friend->setAccess(AS_public);
  12436. CurContext->addDecl(Friend);
  12437. return Friend;
  12438. }
  12439. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12440. // Handle the case of a templated-scope friend class. e.g.
  12441. // template <class T> class A<T>::B;
  12442. // FIXME: we don't support these right now.
  12443. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12444. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12445. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12446. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12447. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12448. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12449. TL.setElaboratedKeywordLoc(TagLoc);
  12450. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12451. TL.setNameLoc(NameLoc);
  12452. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12453. TSI, FriendLoc, TempParamLists);
  12454. Friend->setAccess(AS_public);
  12455. Friend->setUnsupportedFriend(true);
  12456. CurContext->addDecl(Friend);
  12457. return Friend;
  12458. }
  12459. /// Handle a friend type declaration. This works in tandem with
  12460. /// ActOnTag.
  12461. ///
  12462. /// Notes on friend class templates:
  12463. ///
  12464. /// We generally treat friend class declarations as if they were
  12465. /// declaring a class. So, for example, the elaborated type specifier
  12466. /// in a friend declaration is required to obey the restrictions of a
  12467. /// class-head (i.e. no typedefs in the scope chain), template
  12468. /// parameters are required to match up with simple template-ids, &c.
  12469. /// However, unlike when declaring a template specialization, it's
  12470. /// okay to refer to a template specialization without an empty
  12471. /// template parameter declaration, e.g.
  12472. /// friend class A<T>::B<unsigned>;
  12473. /// We permit this as a special case; if there are any template
  12474. /// parameters present at all, require proper matching, i.e.
  12475. /// template <> template \<class T> friend class A<int>::B;
  12476. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12477. MultiTemplateParamsArg TempParams) {
  12478. SourceLocation Loc = DS.getBeginLoc();
  12479. assert(DS.isFriendSpecified());
  12480. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12481. // C++ [class.friend]p3:
  12482. // A friend declaration that does not declare a function shall have one of
  12483. // the following forms:
  12484. // friend elaborated-type-specifier ;
  12485. // friend simple-type-specifier ;
  12486. // friend typename-specifier ;
  12487. //
  12488. // Any declaration with a type qualifier does not have that form. (It's
  12489. // legal to specify a qualified type as a friend, you just can't write the
  12490. // keywords.)
  12491. if (DS.getTypeQualifiers()) {
  12492. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12493. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12494. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12495. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12496. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12497. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12498. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12499. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12500. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12501. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12502. }
  12503. // Try to convert the decl specifier to a type. This works for
  12504. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12505. // for a TUK_Friend.
  12506. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12507. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12508. QualType T = TSI->getType();
  12509. if (TheDeclarator.isInvalidType())
  12510. return nullptr;
  12511. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12512. return nullptr;
  12513. // This is definitely an error in C++98. It's probably meant to
  12514. // be forbidden in C++0x, too, but the specification is just
  12515. // poorly written.
  12516. //
  12517. // The problem is with declarations like the following:
  12518. // template <T> friend A<T>::foo;
  12519. // where deciding whether a class C is a friend or not now hinges
  12520. // on whether there exists an instantiation of A that causes
  12521. // 'foo' to equal C. There are restrictions on class-heads
  12522. // (which we declare (by fiat) elaborated friend declarations to
  12523. // be) that makes this tractable.
  12524. //
  12525. // FIXME: handle "template <> friend class A<T>;", which
  12526. // is possibly well-formed? Who even knows?
  12527. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12528. Diag(Loc, diag::err_tagless_friend_type_template)
  12529. << DS.getSourceRange();
  12530. return nullptr;
  12531. }
  12532. // C++98 [class.friend]p1: A friend of a class is a function
  12533. // or class that is not a member of the class . . .
  12534. // This is fixed in DR77, which just barely didn't make the C++03
  12535. // deadline. It's also a very silly restriction that seriously
  12536. // affects inner classes and which nobody else seems to implement;
  12537. // thus we never diagnose it, not even in -pedantic.
  12538. //
  12539. // But note that we could warn about it: it's always useless to
  12540. // friend one of your own members (it's not, however, worthless to
  12541. // friend a member of an arbitrary specialization of your template).
  12542. Decl *D;
  12543. if (!TempParams.empty())
  12544. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12545. TempParams,
  12546. TSI,
  12547. DS.getFriendSpecLoc());
  12548. else
  12549. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12550. if (!D)
  12551. return nullptr;
  12552. D->setAccess(AS_public);
  12553. CurContext->addDecl(D);
  12554. return D;
  12555. }
  12556. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12557. MultiTemplateParamsArg TemplateParams) {
  12558. const DeclSpec &DS = D.getDeclSpec();
  12559. assert(DS.isFriendSpecified());
  12560. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12561. SourceLocation Loc = D.getIdentifierLoc();
  12562. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12563. // C++ [class.friend]p1
  12564. // A friend of a class is a function or class....
  12565. // Note that this sees through typedefs, which is intended.
  12566. // It *doesn't* see through dependent types, which is correct
  12567. // according to [temp.arg.type]p3:
  12568. // If a declaration acquires a function type through a
  12569. // type dependent on a template-parameter and this causes
  12570. // a declaration that does not use the syntactic form of a
  12571. // function declarator to have a function type, the program
  12572. // is ill-formed.
  12573. if (!TInfo->getType()->isFunctionType()) {
  12574. Diag(Loc, diag::err_unexpected_friend);
  12575. // It might be worthwhile to try to recover by creating an
  12576. // appropriate declaration.
  12577. return nullptr;
  12578. }
  12579. // C++ [namespace.memdef]p3
  12580. // - If a friend declaration in a non-local class first declares a
  12581. // class or function, the friend class or function is a member
  12582. // of the innermost enclosing namespace.
  12583. // - The name of the friend is not found by simple name lookup
  12584. // until a matching declaration is provided in that namespace
  12585. // scope (either before or after the class declaration granting
  12586. // friendship).
  12587. // - If a friend function is called, its name may be found by the
  12588. // name lookup that considers functions from namespaces and
  12589. // classes associated with the types of the function arguments.
  12590. // - When looking for a prior declaration of a class or a function
  12591. // declared as a friend, scopes outside the innermost enclosing
  12592. // namespace scope are not considered.
  12593. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12594. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12595. assert(NameInfo.getName());
  12596. // Check for unexpanded parameter packs.
  12597. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12598. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12599. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12600. return nullptr;
  12601. // The context we found the declaration in, or in which we should
  12602. // create the declaration.
  12603. DeclContext *DC;
  12604. Scope *DCScope = S;
  12605. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12606. ForExternalRedeclaration);
  12607. // There are five cases here.
  12608. // - There's no scope specifier and we're in a local class. Only look
  12609. // for functions declared in the immediately-enclosing block scope.
  12610. // We recover from invalid scope qualifiers as if they just weren't there.
  12611. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12612. if ((SS.isInvalid() || !SS.isSet()) &&
  12613. (FunctionContainingLocalClass =
  12614. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12615. // C++11 [class.friend]p11:
  12616. // If a friend declaration appears in a local class and the name
  12617. // specified is an unqualified name, a prior declaration is
  12618. // looked up without considering scopes that are outside the
  12619. // innermost enclosing non-class scope. For a friend function
  12620. // declaration, if there is no prior declaration, the program is
  12621. // ill-formed.
  12622. // Find the innermost enclosing non-class scope. This is the block
  12623. // scope containing the local class definition (or for a nested class,
  12624. // the outer local class).
  12625. DCScope = S->getFnParent();
  12626. // Look up the function name in the scope.
  12627. Previous.clear(LookupLocalFriendName);
  12628. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12629. if (!Previous.empty()) {
  12630. // All possible previous declarations must have the same context:
  12631. // either they were declared at block scope or they are members of
  12632. // one of the enclosing local classes.
  12633. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12634. } else {
  12635. // This is ill-formed, but provide the context that we would have
  12636. // declared the function in, if we were permitted to, for error recovery.
  12637. DC = FunctionContainingLocalClass;
  12638. }
  12639. adjustContextForLocalExternDecl(DC);
  12640. // C++ [class.friend]p6:
  12641. // A function can be defined in a friend declaration of a class if and
  12642. // only if the class is a non-local class (9.8), the function name is
  12643. // unqualified, and the function has namespace scope.
  12644. if (D.isFunctionDefinition()) {
  12645. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12646. }
  12647. // - There's no scope specifier, in which case we just go to the
  12648. // appropriate scope and look for a function or function template
  12649. // there as appropriate.
  12650. } else if (SS.isInvalid() || !SS.isSet()) {
  12651. // C++11 [namespace.memdef]p3:
  12652. // If the name in a friend declaration is neither qualified nor
  12653. // a template-id and the declaration is a function or an
  12654. // elaborated-type-specifier, the lookup to determine whether
  12655. // the entity has been previously declared shall not consider
  12656. // any scopes outside the innermost enclosing namespace.
  12657. bool isTemplateId =
  12658. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12659. // Find the appropriate context according to the above.
  12660. DC = CurContext;
  12661. // Skip class contexts. If someone can cite chapter and verse
  12662. // for this behavior, that would be nice --- it's what GCC and
  12663. // EDG do, and it seems like a reasonable intent, but the spec
  12664. // really only says that checks for unqualified existing
  12665. // declarations should stop at the nearest enclosing namespace,
  12666. // not that they should only consider the nearest enclosing
  12667. // namespace.
  12668. while (DC->isRecord())
  12669. DC = DC->getParent();
  12670. DeclContext *LookupDC = DC;
  12671. while (LookupDC->isTransparentContext())
  12672. LookupDC = LookupDC->getParent();
  12673. while (true) {
  12674. LookupQualifiedName(Previous, LookupDC);
  12675. if (!Previous.empty()) {
  12676. DC = LookupDC;
  12677. break;
  12678. }
  12679. if (isTemplateId) {
  12680. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12681. } else {
  12682. if (LookupDC->isFileContext()) break;
  12683. }
  12684. LookupDC = LookupDC->getParent();
  12685. }
  12686. DCScope = getScopeForDeclContext(S, DC);
  12687. // - There's a non-dependent scope specifier, in which case we
  12688. // compute it and do a previous lookup there for a function
  12689. // or function template.
  12690. } else if (!SS.getScopeRep()->isDependent()) {
  12691. DC = computeDeclContext(SS);
  12692. if (!DC) return nullptr;
  12693. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12694. LookupQualifiedName(Previous, DC);
  12695. // C++ [class.friend]p1: A friend of a class is a function or
  12696. // class that is not a member of the class . . .
  12697. if (DC->Equals(CurContext))
  12698. Diag(DS.getFriendSpecLoc(),
  12699. getLangOpts().CPlusPlus11 ?
  12700. diag::warn_cxx98_compat_friend_is_member :
  12701. diag::err_friend_is_member);
  12702. if (D.isFunctionDefinition()) {
  12703. // C++ [class.friend]p6:
  12704. // A function can be defined in a friend declaration of a class if and
  12705. // only if the class is a non-local class (9.8), the function name is
  12706. // unqualified, and the function has namespace scope.
  12707. //
  12708. // FIXME: We should only do this if the scope specifier names the
  12709. // innermost enclosing namespace; otherwise the fixit changes the
  12710. // meaning of the code.
  12711. SemaDiagnosticBuilder DB
  12712. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12713. DB << SS.getScopeRep();
  12714. if (DC->isFileContext())
  12715. DB << FixItHint::CreateRemoval(SS.getRange());
  12716. SS.clear();
  12717. }
  12718. // - There's a scope specifier that does not match any template
  12719. // parameter lists, in which case we use some arbitrary context,
  12720. // create a method or method template, and wait for instantiation.
  12721. // - There's a scope specifier that does match some template
  12722. // parameter lists, which we don't handle right now.
  12723. } else {
  12724. if (D.isFunctionDefinition()) {
  12725. // C++ [class.friend]p6:
  12726. // A function can be defined in a friend declaration of a class if and
  12727. // only if the class is a non-local class (9.8), the function name is
  12728. // unqualified, and the function has namespace scope.
  12729. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12730. << SS.getScopeRep();
  12731. }
  12732. DC = CurContext;
  12733. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12734. }
  12735. if (!DC->isRecord()) {
  12736. int DiagArg = -1;
  12737. switch (D.getName().getKind()) {
  12738. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12739. case UnqualifiedIdKind::IK_ConstructorName:
  12740. DiagArg = 0;
  12741. break;
  12742. case UnqualifiedIdKind::IK_DestructorName:
  12743. DiagArg = 1;
  12744. break;
  12745. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12746. DiagArg = 2;
  12747. break;
  12748. case UnqualifiedIdKind::IK_DeductionGuideName:
  12749. DiagArg = 3;
  12750. break;
  12751. case UnqualifiedIdKind::IK_Identifier:
  12752. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12753. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12754. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12755. case UnqualifiedIdKind::IK_TemplateId:
  12756. break;
  12757. }
  12758. // This implies that it has to be an operator or function.
  12759. if (DiagArg >= 0) {
  12760. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12761. return nullptr;
  12762. }
  12763. }
  12764. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12765. // does not contain the declaration context, i.e., in an out-of-line
  12766. // definition of a class.
  12767. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12768. if (!DCScope) {
  12769. FakeDCScope.setEntity(DC);
  12770. DCScope = &FakeDCScope;
  12771. }
  12772. bool AddToScope = true;
  12773. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12774. TemplateParams, AddToScope);
  12775. if (!ND) return nullptr;
  12776. assert(ND->getLexicalDeclContext() == CurContext);
  12777. // If we performed typo correction, we might have added a scope specifier
  12778. // and changed the decl context.
  12779. DC = ND->getDeclContext();
  12780. // Add the function declaration to the appropriate lookup tables,
  12781. // adjusting the redeclarations list as necessary. We don't
  12782. // want to do this yet if the friending class is dependent.
  12783. //
  12784. // Also update the scope-based lookup if the target context's
  12785. // lookup context is in lexical scope.
  12786. if (!CurContext->isDependentContext()) {
  12787. DC = DC->getRedeclContext();
  12788. DC->makeDeclVisibleInContext(ND);
  12789. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12790. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12791. }
  12792. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12793. D.getIdentifierLoc(), ND,
  12794. DS.getFriendSpecLoc());
  12795. FrD->setAccess(AS_public);
  12796. CurContext->addDecl(FrD);
  12797. if (ND->isInvalidDecl()) {
  12798. FrD->setInvalidDecl();
  12799. } else {
  12800. if (DC->isRecord()) CheckFriendAccess(ND);
  12801. FunctionDecl *FD;
  12802. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12803. FD = FTD->getTemplatedDecl();
  12804. else
  12805. FD = cast<FunctionDecl>(ND);
  12806. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12807. // default argument expression, that declaration shall be a definition
  12808. // and shall be the only declaration of the function or function
  12809. // template in the translation unit.
  12810. if (functionDeclHasDefaultArgument(FD)) {
  12811. // We can't look at FD->getPreviousDecl() because it may not have been set
  12812. // if we're in a dependent context. If the function is known to be a
  12813. // redeclaration, we will have narrowed Previous down to the right decl.
  12814. if (D.isRedeclaration()) {
  12815. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12816. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12817. diag::note_previous_declaration);
  12818. } else if (!D.isFunctionDefinition())
  12819. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12820. }
  12821. // Mark templated-scope function declarations as unsupported.
  12822. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12823. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12824. << SS.getScopeRep() << SS.getRange()
  12825. << cast<CXXRecordDecl>(CurContext);
  12826. FrD->setUnsupportedFriend(true);
  12827. }
  12828. }
  12829. return ND;
  12830. }
  12831. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12832. AdjustDeclIfTemplate(Dcl);
  12833. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12834. if (!Fn) {
  12835. Diag(DelLoc, diag::err_deleted_non_function);
  12836. return;
  12837. }
  12838. // Deleted function does not have a body.
  12839. Fn->setWillHaveBody(false);
  12840. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12841. // Don't consider the implicit declaration we generate for explicit
  12842. // specializations. FIXME: Do not generate these implicit declarations.
  12843. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12844. Prev->getPreviousDecl()) &&
  12845. !Prev->isDefined()) {
  12846. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12847. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12848. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12849. : diag::note_previous_declaration);
  12850. }
  12851. // If the declaration wasn't the first, we delete the function anyway for
  12852. // recovery.
  12853. Fn = Fn->getCanonicalDecl();
  12854. }
  12855. // dllimport/dllexport cannot be deleted.
  12856. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12857. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12858. Fn->setInvalidDecl();
  12859. }
  12860. if (Fn->isDeleted())
  12861. return;
  12862. // See if we're deleting a function which is already known to override a
  12863. // non-deleted virtual function.
  12864. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12865. bool IssuedDiagnostic = false;
  12866. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12867. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12868. if (!IssuedDiagnostic) {
  12869. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12870. IssuedDiagnostic = true;
  12871. }
  12872. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12873. }
  12874. }
  12875. // If this function was implicitly deleted because it was defaulted,
  12876. // explain why it was deleted.
  12877. if (IssuedDiagnostic && MD->isDefaulted())
  12878. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12879. /*Diagnose*/true);
  12880. }
  12881. // C++11 [basic.start.main]p3:
  12882. // A program that defines main as deleted [...] is ill-formed.
  12883. if (Fn->isMain())
  12884. Diag(DelLoc, diag::err_deleted_main);
  12885. // C++11 [dcl.fct.def.delete]p4:
  12886. // A deleted function is implicitly inline.
  12887. Fn->setImplicitlyInline();
  12888. Fn->setDeletedAsWritten();
  12889. }
  12890. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12891. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12892. if (MD) {
  12893. if (MD->getParent()->isDependentType()) {
  12894. MD->setDefaulted();
  12895. MD->setExplicitlyDefaulted();
  12896. return;
  12897. }
  12898. CXXSpecialMember Member = getSpecialMember(MD);
  12899. if (Member == CXXInvalid) {
  12900. if (!MD->isInvalidDecl())
  12901. Diag(DefaultLoc, diag::err_default_special_members);
  12902. return;
  12903. }
  12904. MD->setDefaulted();
  12905. MD->setExplicitlyDefaulted();
  12906. // Unset that we will have a body for this function. We might not,
  12907. // if it turns out to be trivial, and we don't need this marking now
  12908. // that we've marked it as defaulted.
  12909. MD->setWillHaveBody(false);
  12910. // If this definition appears within the record, do the checking when
  12911. // the record is complete.
  12912. const FunctionDecl *Primary = MD;
  12913. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  12914. // Ask the template instantiation pattern that actually had the
  12915. // '= default' on it.
  12916. Primary = Pattern;
  12917. // If the method was defaulted on its first declaration, we will have
  12918. // already performed the checking in CheckCompletedCXXClass. Such a
  12919. // declaration doesn't trigger an implicit definition.
  12920. if (Primary->getCanonicalDecl()->isDefaulted())
  12921. return;
  12922. CheckExplicitlyDefaultedSpecialMember(MD);
  12923. if (!MD->isInvalidDecl())
  12924. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  12925. } else {
  12926. Diag(DefaultLoc, diag::err_default_special_members);
  12927. }
  12928. }
  12929. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  12930. for (Stmt *SubStmt : S->children()) {
  12931. if (!SubStmt)
  12932. continue;
  12933. if (isa<ReturnStmt>(SubStmt))
  12934. Self.Diag(SubStmt->getBeginLoc(),
  12935. diag::err_return_in_constructor_handler);
  12936. if (!isa<Expr>(SubStmt))
  12937. SearchForReturnInStmt(Self, SubStmt);
  12938. }
  12939. }
  12940. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  12941. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  12942. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  12943. SearchForReturnInStmt(*this, Handler);
  12944. }
  12945. }
  12946. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  12947. const CXXMethodDecl *Old) {
  12948. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  12949. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  12950. if (OldFT->hasExtParameterInfos()) {
  12951. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  12952. // A parameter of the overriding method should be annotated with noescape
  12953. // if the corresponding parameter of the overridden method is annotated.
  12954. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  12955. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  12956. Diag(New->getParamDecl(I)->getLocation(),
  12957. diag::warn_overriding_method_missing_noescape);
  12958. Diag(Old->getParamDecl(I)->getLocation(),
  12959. diag::note_overridden_marked_noescape);
  12960. }
  12961. }
  12962. // Virtual overrides must have the same code_seg.
  12963. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  12964. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  12965. if ((NewCSA || OldCSA) &&
  12966. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  12967. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  12968. Diag(Old->getLocation(), diag::note_previous_declaration);
  12969. return true;
  12970. }
  12971. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  12972. // If the calling conventions match, everything is fine
  12973. if (NewCC == OldCC)
  12974. return false;
  12975. // If the calling conventions mismatch because the new function is static,
  12976. // suppress the calling convention mismatch error; the error about static
  12977. // function override (err_static_overrides_virtual from
  12978. // Sema::CheckFunctionDeclaration) is more clear.
  12979. if (New->getStorageClass() == SC_Static)
  12980. return false;
  12981. Diag(New->getLocation(),
  12982. diag::err_conflicting_overriding_cc_attributes)
  12983. << New->getDeclName() << New->getType() << Old->getType();
  12984. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  12985. return true;
  12986. }
  12987. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  12988. const CXXMethodDecl *Old) {
  12989. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  12990. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  12991. if (Context.hasSameType(NewTy, OldTy) ||
  12992. NewTy->isDependentType() || OldTy->isDependentType())
  12993. return false;
  12994. // Check if the return types are covariant
  12995. QualType NewClassTy, OldClassTy;
  12996. /// Both types must be pointers or references to classes.
  12997. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  12998. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  12999. NewClassTy = NewPT->getPointeeType();
  13000. OldClassTy = OldPT->getPointeeType();
  13001. }
  13002. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  13003. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  13004. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  13005. NewClassTy = NewRT->getPointeeType();
  13006. OldClassTy = OldRT->getPointeeType();
  13007. }
  13008. }
  13009. }
  13010. // The return types aren't either both pointers or references to a class type.
  13011. if (NewClassTy.isNull()) {
  13012. Diag(New->getLocation(),
  13013. diag::err_different_return_type_for_overriding_virtual_function)
  13014. << New->getDeclName() << NewTy << OldTy
  13015. << New->getReturnTypeSourceRange();
  13016. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13017. << Old->getReturnTypeSourceRange();
  13018. return true;
  13019. }
  13020. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  13021. // C++14 [class.virtual]p8:
  13022. // If the class type in the covariant return type of D::f differs from
  13023. // that of B::f, the class type in the return type of D::f shall be
  13024. // complete at the point of declaration of D::f or shall be the class
  13025. // type D.
  13026. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  13027. if (!RT->isBeingDefined() &&
  13028. RequireCompleteType(New->getLocation(), NewClassTy,
  13029. diag::err_covariant_return_incomplete,
  13030. New->getDeclName()))
  13031. return true;
  13032. }
  13033. // Check if the new class derives from the old class.
  13034. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  13035. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  13036. << New->getDeclName() << NewTy << OldTy
  13037. << New->getReturnTypeSourceRange();
  13038. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13039. << Old->getReturnTypeSourceRange();
  13040. return true;
  13041. }
  13042. // Check if we the conversion from derived to base is valid.
  13043. if (CheckDerivedToBaseConversion(
  13044. NewClassTy, OldClassTy,
  13045. diag::err_covariant_return_inaccessible_base,
  13046. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  13047. New->getLocation(), New->getReturnTypeSourceRange(),
  13048. New->getDeclName(), nullptr)) {
  13049. // FIXME: this note won't trigger for delayed access control
  13050. // diagnostics, and it's impossible to get an undelayed error
  13051. // here from access control during the original parse because
  13052. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  13053. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13054. << Old->getReturnTypeSourceRange();
  13055. return true;
  13056. }
  13057. }
  13058. // The qualifiers of the return types must be the same.
  13059. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  13060. Diag(New->getLocation(),
  13061. diag::err_covariant_return_type_different_qualifications)
  13062. << New->getDeclName() << NewTy << OldTy
  13063. << New->getReturnTypeSourceRange();
  13064. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13065. << Old->getReturnTypeSourceRange();
  13066. return true;
  13067. }
  13068. // The new class type must have the same or less qualifiers as the old type.
  13069. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  13070. Diag(New->getLocation(),
  13071. diag::err_covariant_return_type_class_type_more_qualified)
  13072. << New->getDeclName() << NewTy << OldTy
  13073. << New->getReturnTypeSourceRange();
  13074. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  13075. << Old->getReturnTypeSourceRange();
  13076. return true;
  13077. }
  13078. return false;
  13079. }
  13080. /// Mark the given method pure.
  13081. ///
  13082. /// \param Method the method to be marked pure.
  13083. ///
  13084. /// \param InitRange the source range that covers the "0" initializer.
  13085. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  13086. SourceLocation EndLoc = InitRange.getEnd();
  13087. if (EndLoc.isValid())
  13088. Method->setRangeEnd(EndLoc);
  13089. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  13090. Method->setPure();
  13091. return false;
  13092. }
  13093. if (!Method->isInvalidDecl())
  13094. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  13095. << Method->getDeclName() << InitRange;
  13096. return true;
  13097. }
  13098. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  13099. if (D->getFriendObjectKind())
  13100. Diag(D->getLocation(), diag::err_pure_friend);
  13101. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  13102. CheckPureMethod(M, ZeroLoc);
  13103. else
  13104. Diag(D->getLocation(), diag::err_illegal_initializer);
  13105. }
  13106. /// Determine whether the given declaration is a global variable or
  13107. /// static data member.
  13108. static bool isNonlocalVariable(const Decl *D) {
  13109. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  13110. return Var->hasGlobalStorage();
  13111. return false;
  13112. }
  13113. /// Invoked when we are about to parse an initializer for the declaration
  13114. /// 'Dcl'.
  13115. ///
  13116. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  13117. /// static data member of class X, names should be looked up in the scope of
  13118. /// class X. If the declaration had a scope specifier, a scope will have
  13119. /// been created and passed in for this purpose. Otherwise, S will be null.
  13120. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  13121. // If there is no declaration, there was an error parsing it.
  13122. if (!D || D->isInvalidDecl())
  13123. return;
  13124. // We will always have a nested name specifier here, but this declaration
  13125. // might not be out of line if the specifier names the current namespace:
  13126. // extern int n;
  13127. // int ::n = 0;
  13128. if (S && D->isOutOfLine())
  13129. EnterDeclaratorContext(S, D->getDeclContext());
  13130. // If we are parsing the initializer for a static data member, push a
  13131. // new expression evaluation context that is associated with this static
  13132. // data member.
  13133. if (isNonlocalVariable(D))
  13134. PushExpressionEvaluationContext(
  13135. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  13136. }
  13137. /// Invoked after we are finished parsing an initializer for the declaration D.
  13138. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  13139. // If there is no declaration, there was an error parsing it.
  13140. if (!D || D->isInvalidDecl())
  13141. return;
  13142. if (isNonlocalVariable(D))
  13143. PopExpressionEvaluationContext();
  13144. if (S && D->isOutOfLine())
  13145. ExitDeclaratorContext(S);
  13146. }
  13147. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  13148. /// C++ if/switch/while/for statement.
  13149. /// e.g: "if (int x = f()) {...}"
  13150. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  13151. // C++ 6.4p2:
  13152. // The declarator shall not specify a function or an array.
  13153. // The type-specifier-seq shall not contain typedef and shall not declare a
  13154. // new class or enumeration.
  13155. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  13156. "Parser allowed 'typedef' as storage class of condition decl.");
  13157. Decl *Dcl = ActOnDeclarator(S, D);
  13158. if (!Dcl)
  13159. return true;
  13160. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  13161. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  13162. << D.getSourceRange();
  13163. return true;
  13164. }
  13165. return Dcl;
  13166. }
  13167. void Sema::LoadExternalVTableUses() {
  13168. if (!ExternalSource)
  13169. return;
  13170. SmallVector<ExternalVTableUse, 4> VTables;
  13171. ExternalSource->ReadUsedVTables(VTables);
  13172. SmallVector<VTableUse, 4> NewUses;
  13173. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  13174. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  13175. = VTablesUsed.find(VTables[I].Record);
  13176. // Even if a definition wasn't required before, it may be required now.
  13177. if (Pos != VTablesUsed.end()) {
  13178. if (!Pos->second && VTables[I].DefinitionRequired)
  13179. Pos->second = true;
  13180. continue;
  13181. }
  13182. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  13183. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  13184. }
  13185. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  13186. }
  13187. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  13188. bool DefinitionRequired) {
  13189. // Ignore any vtable uses in unevaluated operands or for classes that do
  13190. // not have a vtable.
  13191. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  13192. CurContext->isDependentContext() || isUnevaluatedContext())
  13193. return;
  13194. // Do not mark as used if compiling for the device outside of the target
  13195. // region.
  13196. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  13197. !isInOpenMPDeclareTargetContext() &&
  13198. !isInOpenMPTargetExecutionDirective()) {
  13199. if (!DefinitionRequired)
  13200. MarkVirtualMembersReferenced(Loc, Class);
  13201. return;
  13202. }
  13203. // Try to insert this class into the map.
  13204. LoadExternalVTableUses();
  13205. Class = Class->getCanonicalDecl();
  13206. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  13207. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  13208. if (!Pos.second) {
  13209. // If we already had an entry, check to see if we are promoting this vtable
  13210. // to require a definition. If so, we need to reappend to the VTableUses
  13211. // list, since we may have already processed the first entry.
  13212. if (DefinitionRequired && !Pos.first->second) {
  13213. Pos.first->second = true;
  13214. } else {
  13215. // Otherwise, we can early exit.
  13216. return;
  13217. }
  13218. } else {
  13219. // The Microsoft ABI requires that we perform the destructor body
  13220. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  13221. // the deleting destructor is emitted with the vtable, not with the
  13222. // destructor definition as in the Itanium ABI.
  13223. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  13224. CXXDestructorDecl *DD = Class->getDestructor();
  13225. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  13226. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  13227. // If this is an out-of-line declaration, marking it referenced will
  13228. // not do anything. Manually call CheckDestructor to look up operator
  13229. // delete().
  13230. ContextRAII SavedContext(*this, DD);
  13231. CheckDestructor(DD);
  13232. } else {
  13233. MarkFunctionReferenced(Loc, Class->getDestructor());
  13234. }
  13235. }
  13236. }
  13237. }
  13238. // Local classes need to have their virtual members marked
  13239. // immediately. For all other classes, we mark their virtual members
  13240. // at the end of the translation unit.
  13241. if (Class->isLocalClass())
  13242. MarkVirtualMembersReferenced(Loc, Class);
  13243. else
  13244. VTableUses.push_back(std::make_pair(Class, Loc));
  13245. }
  13246. bool Sema::DefineUsedVTables() {
  13247. LoadExternalVTableUses();
  13248. if (VTableUses.empty())
  13249. return false;
  13250. // Note: The VTableUses vector could grow as a result of marking
  13251. // the members of a class as "used", so we check the size each
  13252. // time through the loop and prefer indices (which are stable) to
  13253. // iterators (which are not).
  13254. bool DefinedAnything = false;
  13255. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  13256. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  13257. if (!Class)
  13258. continue;
  13259. TemplateSpecializationKind ClassTSK =
  13260. Class->getTemplateSpecializationKind();
  13261. SourceLocation Loc = VTableUses[I].second;
  13262. bool DefineVTable = true;
  13263. // If this class has a key function, but that key function is
  13264. // defined in another translation unit, we don't need to emit the
  13265. // vtable even though we're using it.
  13266. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  13267. if (KeyFunction && !KeyFunction->hasBody()) {
  13268. // The key function is in another translation unit.
  13269. DefineVTable = false;
  13270. TemplateSpecializationKind TSK =
  13271. KeyFunction->getTemplateSpecializationKind();
  13272. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  13273. TSK != TSK_ImplicitInstantiation &&
  13274. "Instantiations don't have key functions");
  13275. (void)TSK;
  13276. } else if (!KeyFunction) {
  13277. // If we have a class with no key function that is the subject
  13278. // of an explicit instantiation declaration, suppress the
  13279. // vtable; it will live with the explicit instantiation
  13280. // definition.
  13281. bool IsExplicitInstantiationDeclaration =
  13282. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  13283. for (auto R : Class->redecls()) {
  13284. TemplateSpecializationKind TSK
  13285. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  13286. if (TSK == TSK_ExplicitInstantiationDeclaration)
  13287. IsExplicitInstantiationDeclaration = true;
  13288. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  13289. IsExplicitInstantiationDeclaration = false;
  13290. break;
  13291. }
  13292. }
  13293. if (IsExplicitInstantiationDeclaration)
  13294. DefineVTable = false;
  13295. }
  13296. // The exception specifications for all virtual members may be needed even
  13297. // if we are not providing an authoritative form of the vtable in this TU.
  13298. // We may choose to emit it available_externally anyway.
  13299. if (!DefineVTable) {
  13300. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13301. continue;
  13302. }
  13303. // Mark all of the virtual members of this class as referenced, so
  13304. // that we can build a vtable. Then, tell the AST consumer that a
  13305. // vtable for this class is required.
  13306. DefinedAnything = true;
  13307. MarkVirtualMembersReferenced(Loc, Class);
  13308. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13309. if (VTablesUsed[Canonical])
  13310. Consumer.HandleVTable(Class);
  13311. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13312. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13313. // that lack key functions, since the user won't be able to make one.
  13314. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13315. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13316. const FunctionDecl *KeyFunctionDef = nullptr;
  13317. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13318. KeyFunctionDef->isInlined())) {
  13319. Diag(Class->getLocation(),
  13320. ClassTSK == TSK_ExplicitInstantiationDefinition
  13321. ? diag::warn_weak_template_vtable
  13322. : diag::warn_weak_vtable)
  13323. << Class;
  13324. }
  13325. }
  13326. }
  13327. VTableUses.clear();
  13328. return DefinedAnything;
  13329. }
  13330. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13331. const CXXRecordDecl *RD) {
  13332. for (const auto *I : RD->methods())
  13333. if (I->isVirtual() && !I->isPure())
  13334. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13335. }
  13336. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13337. const CXXRecordDecl *RD,
  13338. bool ConstexprOnly) {
  13339. // Mark all functions which will appear in RD's vtable as used.
  13340. CXXFinalOverriderMap FinalOverriders;
  13341. RD->getFinalOverriders(FinalOverriders);
  13342. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13343. E = FinalOverriders.end();
  13344. I != E; ++I) {
  13345. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13346. OE = I->second.end();
  13347. OI != OE; ++OI) {
  13348. assert(OI->second.size() > 0 && "no final overrider");
  13349. CXXMethodDecl *Overrider = OI->second.front().Method;
  13350. // C++ [basic.def.odr]p2:
  13351. // [...] A virtual member function is used if it is not pure. [...]
  13352. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  13353. MarkFunctionReferenced(Loc, Overrider);
  13354. }
  13355. }
  13356. // Only classes that have virtual bases need a VTT.
  13357. if (RD->getNumVBases() == 0)
  13358. return;
  13359. for (const auto &I : RD->bases()) {
  13360. const CXXRecordDecl *Base =
  13361. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  13362. if (Base->getNumVBases() == 0)
  13363. continue;
  13364. MarkVirtualMembersReferenced(Loc, Base);
  13365. }
  13366. }
  13367. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13368. /// Objective-C implementation whose ivars need be initialized.
  13369. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13370. if (!getLangOpts().CPlusPlus)
  13371. return;
  13372. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13373. SmallVector<ObjCIvarDecl*, 8> ivars;
  13374. CollectIvarsToConstructOrDestruct(OID, ivars);
  13375. if (ivars.empty())
  13376. return;
  13377. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13378. for (unsigned i = 0; i < ivars.size(); i++) {
  13379. FieldDecl *Field = ivars[i];
  13380. if (Field->isInvalidDecl())
  13381. continue;
  13382. CXXCtorInitializer *Member;
  13383. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13384. InitializationKind InitKind =
  13385. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13386. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13387. ExprResult MemberInit =
  13388. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13389. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13390. // Note, MemberInit could actually come back empty if no initialization
  13391. // is required (e.g., because it would call a trivial default constructor)
  13392. if (!MemberInit.get() || MemberInit.isInvalid())
  13393. continue;
  13394. Member =
  13395. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13396. SourceLocation(),
  13397. MemberInit.getAs<Expr>(),
  13398. SourceLocation());
  13399. AllToInit.push_back(Member);
  13400. // Be sure that the destructor is accessible and is marked as referenced.
  13401. if (const RecordType *RecordTy =
  13402. Context.getBaseElementType(Field->getType())
  13403. ->getAs<RecordType>()) {
  13404. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13405. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13406. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13407. CheckDestructorAccess(Field->getLocation(), Destructor,
  13408. PDiag(diag::err_access_dtor_ivar)
  13409. << Context.getBaseElementType(Field->getType()));
  13410. }
  13411. }
  13412. }
  13413. ObjCImplementation->setIvarInitializers(Context,
  13414. AllToInit.data(), AllToInit.size());
  13415. }
  13416. }
  13417. static
  13418. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13419. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13420. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13421. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13422. Sema &S) {
  13423. if (Ctor->isInvalidDecl())
  13424. return;
  13425. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13426. // Target may not be determinable yet, for instance if this is a dependent
  13427. // call in an uninstantiated template.
  13428. if (Target) {
  13429. const FunctionDecl *FNTarget = nullptr;
  13430. (void)Target->hasBody(FNTarget);
  13431. Target = const_cast<CXXConstructorDecl*>(
  13432. cast_or_null<CXXConstructorDecl>(FNTarget));
  13433. }
  13434. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13435. // Avoid dereferencing a null pointer here.
  13436. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13437. if (!Current.insert(Canonical).second)
  13438. return;
  13439. // We know that beyond here, we aren't chaining into a cycle.
  13440. if (!Target || !Target->isDelegatingConstructor() ||
  13441. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13442. Valid.insert(Current.begin(), Current.end());
  13443. Current.clear();
  13444. // We've hit a cycle.
  13445. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13446. Current.count(TCanonical)) {
  13447. // If we haven't diagnosed this cycle yet, do so now.
  13448. if (!Invalid.count(TCanonical)) {
  13449. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13450. diag::warn_delegating_ctor_cycle)
  13451. << Ctor;
  13452. // Don't add a note for a function delegating directly to itself.
  13453. if (TCanonical != Canonical)
  13454. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13455. CXXConstructorDecl *C = Target;
  13456. while (C->getCanonicalDecl() != Canonical) {
  13457. const FunctionDecl *FNTarget = nullptr;
  13458. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13459. assert(FNTarget && "Ctor cycle through bodiless function");
  13460. C = const_cast<CXXConstructorDecl*>(
  13461. cast<CXXConstructorDecl>(FNTarget));
  13462. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13463. }
  13464. }
  13465. Invalid.insert(Current.begin(), Current.end());
  13466. Current.clear();
  13467. } else {
  13468. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13469. }
  13470. }
  13471. void Sema::CheckDelegatingCtorCycles() {
  13472. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13473. for (DelegatingCtorDeclsType::iterator
  13474. I = DelegatingCtorDecls.begin(ExternalSource),
  13475. E = DelegatingCtorDecls.end();
  13476. I != E; ++I)
  13477. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13478. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13479. (*CI)->setInvalidDecl();
  13480. }
  13481. namespace {
  13482. /// AST visitor that finds references to the 'this' expression.
  13483. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13484. Sema &S;
  13485. public:
  13486. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13487. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13488. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13489. << E->isImplicit();
  13490. return false;
  13491. }
  13492. };
  13493. }
  13494. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13495. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13496. if (!TSInfo)
  13497. return false;
  13498. TypeLoc TL = TSInfo->getTypeLoc();
  13499. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13500. if (!ProtoTL)
  13501. return false;
  13502. // C++11 [expr.prim.general]p3:
  13503. // [The expression this] shall not appear before the optional
  13504. // cv-qualifier-seq and it shall not appear within the declaration of a
  13505. // static member function (although its type and value category are defined
  13506. // within a static member function as they are within a non-static member
  13507. // function). [ Note: this is because declaration matching does not occur
  13508. // until the complete declarator is known. - end note ]
  13509. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13510. FindCXXThisExpr Finder(*this);
  13511. // If the return type came after the cv-qualifier-seq, check it now.
  13512. if (Proto->hasTrailingReturn() &&
  13513. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13514. return true;
  13515. // Check the exception specification.
  13516. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13517. return true;
  13518. return checkThisInStaticMemberFunctionAttributes(Method);
  13519. }
  13520. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13521. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13522. if (!TSInfo)
  13523. return false;
  13524. TypeLoc TL = TSInfo->getTypeLoc();
  13525. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13526. if (!ProtoTL)
  13527. return false;
  13528. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13529. FindCXXThisExpr Finder(*this);
  13530. switch (Proto->getExceptionSpecType()) {
  13531. case EST_Unparsed:
  13532. case EST_Uninstantiated:
  13533. case EST_Unevaluated:
  13534. case EST_BasicNoexcept:
  13535. case EST_NoThrow:
  13536. case EST_DynamicNone:
  13537. case EST_MSAny:
  13538. case EST_None:
  13539. break;
  13540. case EST_DependentNoexcept:
  13541. case EST_NoexceptFalse:
  13542. case EST_NoexceptTrue:
  13543. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13544. return true;
  13545. LLVM_FALLTHROUGH;
  13546. case EST_Dynamic:
  13547. for (const auto &E : Proto->exceptions()) {
  13548. if (!Finder.TraverseType(E))
  13549. return true;
  13550. }
  13551. break;
  13552. }
  13553. return false;
  13554. }
  13555. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13556. FindCXXThisExpr Finder(*this);
  13557. // Check attributes.
  13558. for (const auto *A : Method->attrs()) {
  13559. // FIXME: This should be emitted by tblgen.
  13560. Expr *Arg = nullptr;
  13561. ArrayRef<Expr *> Args;
  13562. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13563. Arg = G->getArg();
  13564. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13565. Arg = G->getArg();
  13566. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13567. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13568. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13569. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13570. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13571. Arg = ETLF->getSuccessValue();
  13572. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13573. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13574. Arg = STLF->getSuccessValue();
  13575. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13576. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13577. Arg = LR->getArg();
  13578. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13579. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13580. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13581. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13582. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13583. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13584. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13585. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13586. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13587. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13588. if (Arg && !Finder.TraverseStmt(Arg))
  13589. return true;
  13590. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13591. if (!Finder.TraverseStmt(Args[I]))
  13592. return true;
  13593. }
  13594. }
  13595. return false;
  13596. }
  13597. void Sema::checkExceptionSpecification(
  13598. bool IsTopLevel, ExceptionSpecificationType EST,
  13599. ArrayRef<ParsedType> DynamicExceptions,
  13600. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13601. SmallVectorImpl<QualType> &Exceptions,
  13602. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13603. Exceptions.clear();
  13604. ESI.Type = EST;
  13605. if (EST == EST_Dynamic) {
  13606. Exceptions.reserve(DynamicExceptions.size());
  13607. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13608. // FIXME: Preserve type source info.
  13609. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13610. if (IsTopLevel) {
  13611. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13612. collectUnexpandedParameterPacks(ET, Unexpanded);
  13613. if (!Unexpanded.empty()) {
  13614. DiagnoseUnexpandedParameterPacks(
  13615. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13616. Unexpanded);
  13617. continue;
  13618. }
  13619. }
  13620. // Check that the type is valid for an exception spec, and
  13621. // drop it if not.
  13622. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13623. Exceptions.push_back(ET);
  13624. }
  13625. ESI.Exceptions = Exceptions;
  13626. return;
  13627. }
  13628. if (isComputedNoexcept(EST)) {
  13629. assert((NoexceptExpr->isTypeDependent() ||
  13630. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13631. Context.BoolTy) &&
  13632. "Parser should have made sure that the expression is boolean");
  13633. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13634. ESI.Type = EST_BasicNoexcept;
  13635. return;
  13636. }
  13637. ESI.NoexceptExpr = NoexceptExpr;
  13638. return;
  13639. }
  13640. }
  13641. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13642. ExceptionSpecificationType EST,
  13643. SourceRange SpecificationRange,
  13644. ArrayRef<ParsedType> DynamicExceptions,
  13645. ArrayRef<SourceRange> DynamicExceptionRanges,
  13646. Expr *NoexceptExpr) {
  13647. if (!MethodD)
  13648. return;
  13649. // Dig out the method we're referring to.
  13650. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13651. MethodD = FunTmpl->getTemplatedDecl();
  13652. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13653. if (!Method)
  13654. return;
  13655. // Check the exception specification.
  13656. llvm::SmallVector<QualType, 4> Exceptions;
  13657. FunctionProtoType::ExceptionSpecInfo ESI;
  13658. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13659. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13660. ESI);
  13661. // Update the exception specification on the function type.
  13662. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13663. if (Method->isStatic())
  13664. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13665. if (Method->isVirtual()) {
  13666. // Check overrides, which we previously had to delay.
  13667. for (const CXXMethodDecl *O : Method->overridden_methods())
  13668. CheckOverridingFunctionExceptionSpec(Method, O);
  13669. }
  13670. }
  13671. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13672. ///
  13673. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13674. SourceLocation DeclStart, Declarator &D,
  13675. Expr *BitWidth,
  13676. InClassInitStyle InitStyle,
  13677. AccessSpecifier AS,
  13678. const ParsedAttr &MSPropertyAttr) {
  13679. IdentifierInfo *II = D.getIdentifier();
  13680. if (!II) {
  13681. Diag(DeclStart, diag::err_anonymous_property);
  13682. return nullptr;
  13683. }
  13684. SourceLocation Loc = D.getIdentifierLoc();
  13685. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13686. QualType T = TInfo->getType();
  13687. if (getLangOpts().CPlusPlus) {
  13688. CheckExtraCXXDefaultArguments(D);
  13689. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13690. UPPC_DataMemberType)) {
  13691. D.setInvalidType();
  13692. T = Context.IntTy;
  13693. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13694. }
  13695. }
  13696. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13697. if (D.getDeclSpec().isInlineSpecified())
  13698. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13699. << getLangOpts().CPlusPlus17;
  13700. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13701. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13702. diag::err_invalid_thread)
  13703. << DeclSpec::getSpecifierName(TSCS);
  13704. // Check to see if this name was declared as a member previously
  13705. NamedDecl *PrevDecl = nullptr;
  13706. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13707. ForVisibleRedeclaration);
  13708. LookupName(Previous, S);
  13709. switch (Previous.getResultKind()) {
  13710. case LookupResult::Found:
  13711. case LookupResult::FoundUnresolvedValue:
  13712. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13713. break;
  13714. case LookupResult::FoundOverloaded:
  13715. PrevDecl = Previous.getRepresentativeDecl();
  13716. break;
  13717. case LookupResult::NotFound:
  13718. case LookupResult::NotFoundInCurrentInstantiation:
  13719. case LookupResult::Ambiguous:
  13720. break;
  13721. }
  13722. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13723. // Maybe we will complain about the shadowed template parameter.
  13724. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13725. // Just pretend that we didn't see the previous declaration.
  13726. PrevDecl = nullptr;
  13727. }
  13728. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13729. PrevDecl = nullptr;
  13730. SourceLocation TSSL = D.getBeginLoc();
  13731. MSPropertyDecl *NewPD =
  13732. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13733. MSPropertyAttr.getPropertyDataGetter(),
  13734. MSPropertyAttr.getPropertyDataSetter());
  13735. ProcessDeclAttributes(TUScope, NewPD, D);
  13736. NewPD->setAccess(AS);
  13737. if (NewPD->isInvalidDecl())
  13738. Record->setInvalidDecl();
  13739. if (D.getDeclSpec().isModulePrivateSpecified())
  13740. NewPD->setModulePrivate();
  13741. if (NewPD->isInvalidDecl() && PrevDecl) {
  13742. // Don't introduce NewFD into scope; there's already something
  13743. // with the same name in the same scope.
  13744. } else if (II) {
  13745. PushOnScopeChains(NewPD, S);
  13746. } else
  13747. Record->addDecl(NewPD);
  13748. return NewPD;
  13749. }